CVE-2021-29454 (published 2022-01-10T20:15Z)

Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic. Prior to versions 3.1.42 and 4.0.2, template authors could run arbitrary PHP code by crafting a malicious math string. If a math string was passed through as user provided data to the math function, external users could run arbitrary PHP code by crafting a malicious math string. Users should upgrade to version 3.1.42 or 4.0.2 to receive a patch.

Severity: MEDIUM
CVSS v2 base score: 6.5 (AV:N/AC:L/Au:S/C:P/I:P/A:P)
CVSS v3 base score: 8.8, HIGH (CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-74
cwe_name: Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
description: The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
extended_description: Software or other automated logic has certain assumptions about what constitutes data and control respectively. It is the lack of verification of these assumptions for user-controlled input that leads to injection problems. Injection problems encompass a wide variety of issues -- all mitigated in very different ways and usually attempted in order to alter the control flow of the process. For this reason, the most effective way to discuss these weaknesses is to note the distinct features that classify them as injection weaknesses. The most important issue to note is that all injection problems share one thing in common -- i.e., they allow for the injection of control plane data into the user-controlled data plane. This means that the execution of the process may be altered by sending code in through legitimate data channels, using no other mechanism. While buffer overflows, and many other flaws, involve the use of some further issue to gain execution, injection problems need only for the data to be parsed.
         

Fix information:
repo_url: https://github.com/smarty-php/smarty
commit_details: repo_url: https://github.com/smarty-php/smarty
author: Simon Wisselink
author_date: 2022-01-10 00:01:43+01:00
msg: Merge pull request from GHSA-29gp-2c3m-3j6m

* Temporary fix. Waiting for CVE

* Add CVE
repository: repo_url: https://github.com/smarty-php/smarty
repo_name: smarty-php/smarty
description: Smarty is a template engine for PHP, facilitating the separation of presentation (HTML/CSS) from application logic.
repo_language: PHP
owner: smarty-php
file_changes: filename: CHANGELOG.md
change_type: ModificationType.MODIFY
diff: @@ -6,6 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ## [Unreleased]
 
+### Security
+- Prevent arbitrary PHP code execution through maliciously crafted expression for the math function. This addresses CVE-2021-29454
+
 ## [4.0.1] - 2022-01-09
 
 ### Security

programming_language: Markdown
filename: function.math.php
change_type: ModificationType.MODIFY
diff: @@ -28,7 +28,12 @@ function smarty_function_math($params, $template)
             'int'   => true,
             'abs'   => true,
             'ceil'  => true,
+            'acos'   => true,
+            'acosh'   => true,
             'cos'   => true,
+            'cosh'   => true,
+            'deg2rad'   => true,
+            'rad2deg'   => true,
             'exp'   => true,
             'floor' => true,
             'log'   => true,
@@ -39,27 +44,51 @@ function smarty_function_math($params, $template)
             'pow'   => true,
             'rand'  => true,
             'round' => true,
+            'asin'   => true,
+            'asinh'   => true,
             'sin'   => true,
+            'sinh'   => true,
             'sqrt'  => true,
             'srand' => true,
-            'tan'   => true
+            'atan'   => true,
+            'atanh'   => true,
+            'tan'   => true,
+            'tanh'   => true
         );
+
     // be sure equation parameter is present
     if (empty($params[ 'equation' ])) {
         trigger_error("math: missing equation parameter", E_USER_WARNING);
         return;
     }
     $equation = $params[ 'equation' ];
+
+    // Remove whitespaces
+    $equation = preg_replace('/\s+/', '', $equation);
+
+    // Adapted from https://www.php.net/manual/en/function.eval.php#107377
+    $number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
+    $functionsOrVars = '((?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))';
+    $operators = '[+\/*\^%-]'; // Allowed math operators
+    $regexp = '/^(('.$number.'|'.$functionsOrVars.'|('.$functionsOrVars.'\s*\((?1)+\)|\((?1)+\)))(?:'.$operators.'(?2))?)+$/';
+
+    if (!preg_match($regexp, $equation)) {
+        trigger_error("math: illegal characters", E_USER_WARNING);
+        return;
+    }
+
     // make sure parenthesis are balanced
     if (substr_count($equation, '(') !== substr_count($equation, ')')) {
         trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
         return;
     }
+
     // disallow backticks
     if (strpos($equation, '`') !== false) {
         trigger_error("math: backtick character not allowed in equation", E_USER_WARNING);
         return;
     }
+
     // also disallow dollar signs
     if (strpos($equation, '$') !== false) {
         trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING);
@@ -96,6 +125,7 @@ function smarty_function_math($params, $template)
     }
     $smarty_math_result = null;
     eval("\$smarty_math_result = " . $equation . ";");
+
     if (empty($params[ 'format' ])) {
         if (empty($params[ 'assign' ])) {
             return $smarty_math_result;

programming_language: PHP
filename: MathTest.php
change_type: ModificationType.MODIFY
diff: @@ -107,4 +107,35 @@ class MathTest extends PHPUnit_Smarty
         $tpl = $this->smarty->createTemplate('eval:{$x = "4"}{$y = "5.5"}{math equation="x * y" x=$x y=$y format="%0.2f"} -- {math equation="20.5 / 5" format="%0.2f"}');
         $this->assertEquals($expected, $this->smarty->fetch($tpl));
     }
+
+	/**
+	 * @expectedException PHPUnit_Framework_Error_Warning
+	 */
+	public function testBackticksIllegal()
+	{
+		$expected = "22.00";
+		$tpl = $this->smarty->createTemplate('eval:{$x = "4"}{$y = "5.5"}{math equation="`ls` x * y" x=$x y=$y}');
+		$this->assertEquals($expected, $this->smarty->fetch($tpl));
+	}
+
+	/**
+	 * @expectedException PHPUnit_Framework_Error_Warning
+	 */
+	public function testDollarSignsIllegal()
+	{
+		$expected = "22.00";
+		$tpl = $this->smarty->createTemplate('eval:{$x = "4"}{$y = "5.5"}{math equation="$" x=$x y=$y}');
+		$this->assertEquals($expected, $this->smarty->fetch($tpl));
+	}
+
+	/**
+	 * @expectedException PHPUnit_Framework_Error_Warning
+	 */
+	public function testBracketsIllegal()
+	{
+		$expected = "I";
+		$tpl = $this->smarty->createTemplate('eval:{$x = "0"}{$y = "1"}{math equation="((y/x).(x))[x]" x=$x y=$y}');
+		$this->assertEquals($expected, $this->smarty->fetch($tpl));
+	}
+
 }

programming_language: PHP