Skip to content

Commit 515876c

Browse files
Merge commit from fork
* fix: restrict parser conditionals for untrusted templates * apply review suggestions Co-authored-by: John Paul E Balandan <paulbalandan@gmail.com> --------- Co-authored-by: John Paul E Balandan <paulbalandan@gmail.com>
1 parent e3d201b commit 515876c

15 files changed

Lines changed: 593 additions & 56 deletions

File tree

‎app/Config/View.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,14 @@ class View extends BaseView
4343
*/
4444
public $plugins = [];
4545

46+
/**
47+
* When true, Parser conditionals may only contain variables, literals,
48+
* arithmetic, comparison and logical operators, and parentheses. Enable
49+
* this when less-trusted users can edit Parser templates. Can be overridden per
50+
* call with the `restrictConditionals` render option.
51+
*/
52+
public bool $restrictParserConditionals = false;
53+
4654
/**
4755
* View Decorators are class methods that will be run in sequence to
4856
* have a chance to alter the generated output just prior to caching

‎system/Config/View.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,14 @@ class View extends BaseConfig
5252
*/
5353
public $plugins = [];
5454

55+
/**
56+
* When true, Parser conditionals may only contain variables, literals,
57+
* arithmetic, comparison and logical operators, and parentheses. Enable
58+
* this when less-trusted users can edit Parser templates. Can be overridden per
59+
* call with the `restrictConditionals` render option.
60+
*/
61+
public bool $restrictParserConditionals = false;
62+
5563
/**
5664
* Built-in View filters.
5765
*

‎system/Language/en/View.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@
2020
'invalidCellClass' => 'Unable to locate view cell class: "{0}".',
2121
'tagSyntaxError' => 'You have a syntax error in your Parser tags: "{0}"',
2222
'invalidDecoratorClass' => '"{0}" is not a valid View Decorator.',
23+
'restrictedConditional' => 'The Parser conditional is not allowed in restricted mode: "{0}"',
2324
];

‎system/View/Exceptions/ViewException.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ public static function forTagSyntaxError(string $output)
6565
return new static(lang('View.tagSyntaxError', [$output]));
6666
}
6767

68+
/**
69+
* @return static
70+
*/
71+
public static function forRestrictedConditional(string $tag)
72+
{
73+
return new static(lang('View.restrictedConditional', [$tag]));
74+
}
75+
6876
/**
6977
* @return static
7078
*/

‎system/View/Parser.php‎

Lines changed: 128 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use CodeIgniter\View\Exceptions\ViewException;
1616
use Config\View as ViewConfig;
1717
use ParseError;
18+
use PhpToken;
1819
use Psr\Log\LoggerInterface;
1920

2021
/**
@@ -87,6 +88,12 @@ class Parser extends View
8788
*/
8889
private array $conditionalSources = [];
8990

91+
/**
92+
* Whether conditionals in the template being parsed are restricted
93+
* to variables, literals, arithmetic, comparison and logical operators.
94+
*/
95+
private bool $restrictConditionals = false;
96+
9097
/**
9198
* Constructor
9299
*
@@ -255,7 +262,7 @@ protected function parse(string $template, array $data = [], ?array $options = n
255262
$this->replacementTokenPrefix = bin2hex(random_bytes(16));
256263

257264
try {
258-
return $this->parseTemplate($template, $data);
265+
return $this->parseTemplate($template, $data, $options);
259266
} finally {
260267
[
261268
$this->replacementTokens,
@@ -265,63 +272,75 @@ protected function parse(string $template, array $data = [], ?array $options = n
265272
}
266273

267274
/**
268-
* @param array<string, mixed> $data
275+
* @param array<string, mixed> $data
276+
* @param array<string, mixed>|null $options
269277
*/
270-
private function parseTemplate(string $template, array $data): string
278+
private function parseTemplate(string $template, array $data, ?array $options): string
271279
{
272-
// Remove any possible PHP tags since we don't support it
273-
// and parseConditionals needs it clean anyway...
274-
$template = str_replace(['<?', '?>'], ['&lt;?', '?&gt;'], $template);
275-
276280
$template = $this->parseComments($template);
277-
$template = $this->extractNoparse($template);
278281

279-
// Replace any conditional code here so we don't have to parse as much
280-
$template = $this->parseConditionals($template);
282+
// Neutralize PHP tags after stripping comments, which can assemble them.
283+
// parseConditionals() evaluates the template as PHP.
284+
$template = str_replace(['<?', '?>'], ['&lt;?', '?&gt;'], $template);
281285

282-
// Handle any plugins before normal data, so that
283-
// it can potentially modify any template between its tags.
284-
$template = $this->parsePlugins($template);
286+
$template = $this->extractNoparse($template);
285287

286-
// Parse stack for each parse type (Single and Pairs)
287-
$replaceSingleStack = [];
288-
$replacePairsStack = [];
288+
$restrictConditionals = $this->restrictConditionals;
289289

290-
// loop over the data variables, saving regex and data
291-
// for later replacement.
292-
foreach ($data as $key => $val) {
293-
$escape = true;
290+
// Nested renders must not weaken the restriction of the outer render.
291+
$this->restrictConditionals = $restrictConditionals
292+
|| (bool) ($options['restrictConditionals'] ?? $this->config->restrictParserConditionals);
294293

295-
if (is_array($val)) {
296-
$escape = false;
297-
$replacePairsStack[] = [
298-
'replace' => $this->parsePair($key, $val, $template),
299-
'escape' => $escape,
300-
];
301-
} else {
302-
$replaceSingleStack[] = [
303-
'replace' => $this->parseSingle($key, (string) $val),
304-
'escape' => $escape,
305-
];
294+
try {
295+
// Replace any conditional code here so we don't have to parse as much
296+
$template = $this->parseConditionals($template);
297+
298+
// Handle any plugins before normal data, so that
299+
// it can potentially modify any template between its tags.
300+
$template = $this->parsePlugins($template);
301+
302+
// Parse stack for each parse type (Single and Pairs)
303+
$replaceSingleStack = [];
304+
$replacePairsStack = [];
305+
306+
// loop over the data variables, saving regex and data
307+
// for later replacement.
308+
foreach ($data as $key => $val) {
309+
$escape = true;
310+
311+
if (is_array($val)) {
312+
$escape = false;
313+
$replacePairsStack[] = [
314+
'replace' => $this->parsePair($key, $val, $template),
315+
'escape' => $escape,
316+
];
317+
} else {
318+
$replaceSingleStack[] = [
319+
'replace' => $this->parseSingle($key, (string) $val),
320+
'escape' => $escape,
321+
];
322+
}
306323
}
307-
}
308324

309-
// Merge both stacks, pairs first + single stacks
310-
// This allows for nested data with the same key to be replaced properly
311-
$replace = array_merge($replacePairsStack, $replaceSingleStack);
325+
// Merge both stacks, pairs first + single stacks
326+
// This allows for nested data with the same key to be replaced properly
327+
$replace = array_merge($replacePairsStack, $replaceSingleStack);
312328

313-
// Loop over each replace array item which
314-
// holds all the data to be replaced
315-
foreach ($replace as $replaceItem) {
316-
// Loop over the actual data to be replaced
317-
foreach ($replaceItem['replace'] as $pattern => $content) {
318-
$template = $this->replaceSingle($pattern, $content, $template, $replaceItem['escape']);
329+
// Loop over each replace array item which
330+
// holds all the data to be replaced
331+
foreach ($replace as $replaceItem) {
332+
// Loop over the actual data to be replaced
333+
foreach ($replaceItem['replace'] as $pattern => $content) {
334+
$template = $this->replaceSingle($pattern, $content, $template, $replaceItem['escape']);
335+
}
319336
}
320-
}
321337

322-
$template = $this->insertNoparse($template);
338+
$template = $this->insertNoparse($template);
323339

324-
return strtr($template, $this->replacementTokens);
340+
return strtr($template, $this->replacementTokens);
341+
} finally {
342+
$this->restrictConditionals = $restrictConditionals;
343+
}
325344
}
326345

327346
/**
@@ -510,6 +529,10 @@ protected function parseConditionals(string $template): string
510529
// Build the string to replace the `if` statement with.
511530
$condition = $match[2];
512531

532+
if ($this->restrictConditionals && ! $this->isRestrictedCondition($condition)) {
533+
throw ViewException::forRestrictedConditional($match[0]);
534+
}
535+
513536
$statement = $match[1] === 'elseif' ? '<?php elseif (' . $condition . '): ?>' : '<?php if (' . $condition . '): ?>';
514537
$template = str_replace($match[0], $statement, $template);
515538
}
@@ -551,6 +574,67 @@ protected function parseConditionals(string $template): string
551574
return ob_get_clean();
552575
}
553576

577+
/**
578+
* Checks that a conditional expression only contains variables,
579+
* literals, arithmetic, comparison and logical operators, and grouping parentheses.
580+
*/
581+
private function isRestrictedCondition(string $condition): bool
582+
{
583+
$allowedTokens = [
584+
T_VARIABLE,
585+
T_CONSTANT_ENCAPSED_STRING,
586+
T_LNUMBER,
587+
T_DNUMBER,
588+
T_POW,
589+
T_IS_EQUAL,
590+
T_IS_NOT_EQUAL,
591+
T_IS_IDENTICAL,
592+
T_IS_NOT_IDENTICAL,
593+
T_IS_SMALLER_OR_EQUAL,
594+
T_IS_GREATER_OR_EQUAL,
595+
T_BOOLEAN_AND,
596+
T_BOOLEAN_OR,
597+
T_LOGICAL_AND,
598+
T_LOGICAL_OR,
599+
];
600+
$valueTokens = [
601+
T_VARIABLE,
602+
T_CONSTANT_ENCAPSED_STRING,
603+
T_LNUMBER,
604+
T_DNUMBER,
605+
T_STRING,
606+
];
607+
608+
$afterValue = false;
609+
610+
foreach (PhpToken::tokenize('<?php ' . $condition) as $index => $token) {
611+
if ($index === 0 || $token->is(T_WHITESPACE)) {
612+
continue;
613+
}
614+
615+
if ($token->text === '(') {
616+
// A parenthesis after a value would be a call.
617+
if ($afterValue) {
618+
return false;
619+
}
620+
} elseif ($token->is(T_STRING)) {
621+
if (! in_array(strtolower($token->text), ['true', 'false', 'null'], true)) {
622+
return false;
623+
}
624+
} elseif ($token->is(T_VARIABLE)) {
625+
if ($token->text === '$this') {
626+
return false;
627+
}
628+
} elseif (! $token->is($allowedTokens) && ! in_array($token->text, [')', '<', '>', '!', '+', '-', '*', '/', '%'], true)) {
629+
return false;
630+
}
631+
632+
$afterValue = $token->is($valueTokens) || $token->text === ')';
633+
}
634+
635+
return true;
636+
}
637+
554638
/**
555639
* Over-ride the substitution field delimiters.
556640
*

0 commit comments

Comments
 (0)