GHSA-96xv-rmwj-6p9w Grav Server-side Template Injection (SSTI) via Twig Default Filters
Hi,actually we have sent the bug report to [security@getgrav.org](mailto:security@getgrav.org) on 27th March 2023 and on 10th April 2023.Grav Server-side Template Injection (SSTI) via Insufficient Validation in filterFilterSummary:| **Product**             | Grav CMS                                      |
| ----------------------- | --------------------------------------------- |
| **Vendor**              | Grav                                          |
| **Severity**            | High - Users with login access to Grav Admin panel and page creation/update permissions are able to obtain remote code/command execution |
| **Affected Versions**   | <= [v1.7.40](https://github.com/getgrav/grav/tree/1.7.40) (Commit [685d762](https://github.com/getgrav/grav/commit/685d76231a057416651ed192a6a2e83720800e61)) (Latest version as of writing) |
| **Tested Versions**     | v1.7.40                                       |
| **Internal Identifier** | STAR-2023-0007                                |
| **CVE Identifier**      | TBD                                           |
| **CWE(s)**              | CWE-20: Improper Input Validation, CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine |CVSS3.1 Scoring System:**Base Score:** 7.2 (High)  
**Vector String:** `CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H`  
| **Metric**                   | **Value** |
| ---------------------------- | --------- |
| **Attack Vector (AV)**       | Network   |
| **Attack Complexity (AC)**   | Low       |
| **Privileges Required (PR)** | High      |
| **User Interaction (UI)**    | None      |
| **Scope (S)**                | Unchanged |
| **Confidentiality \(C)**     | High      |
| **Integrity (I)**            | High      |
| **Availability (A)**         | High      |Product Overview:Grav is a PHP-based flat-file content management system (CMS) designed to provide a fast and simple way to build websites. It supports rendering of web pages written in Markdown and Twig expressions, and provides an administration panel to manage the entire website via an optional Admin plugin.Vulnerability Summary:There is a logic flaw in the `GravExtension.filterFilter()` function whereby validation against a denylist of unsafe functions is only performed when the argument passed to filter is a string. However, passing an array as a callable argument allows the validation check to be skipped. Consequently, a low privileged attacker with login access to Grav Admin panel and page creation/update permissions is able to inject malicious templates to obtain remote code execution.Vulnerability Details:The vulnerability can be found in the `GravExtension.filterFilter()` function declared in [`/system/src/Grav/Common/Twig/Extension/GravExtension.php`](https://github.com/getgrav/grav/blob/1.7.40/system/src/Grav/Common/Twig/Extension/GravExtension.php#L1692-L1698):At [1], the `$arrow` parameter contains the argument supplied to the filter. For example, it may refer to `"funcname"` in `{{ array|filter("funcname") }}` or the closure (a.k.a. arrow function) `el => el != 'exclude'` in `{{ array|filter(el => el != 'exclude') }}`. Observe that `Utils::isDangerousFunction($arrow)` is only invoked if `$arrow` is a string. As such, non-string arguments may be passed to `twig_array_filter()` at [2] due to the absence of type enforcement at [1].The implementation of the `twig_array_filter()` function can be found in [/src/Extension/CoreExtension.php](https://github.com/twigphp/Twig/blob/v1.44.7/src/Extension/CoreExtension.php) within Twig's codebase:At [3], a runtime error is thrown if `$arrow` is not a closure and Twig sandbox is enabled. However, since Grav does not use the Twig Sandbox extension, the check passes successfully even when `$arrow` is not a closure. Subsequently at [4], `array_filter()` is invoked with the user-controlled `$array` input and `$arrow` parameter.Note that the method signature of `array_filter()` is as follows:A common mistake that developers make is assuming that the `callable` type refers to a `string` type. This is untrue, and it is [well documented in the PHP Manual](https://www.php.net/manual/en/language.types.callable.php):A method of an instantiated object is passed as an **array containing an object at index 0 and the method name at index 1**. Accessing protected and private methods from within a class is allowed.
Static class methods can also be passed without instantiating an object of that class by either, **passing the class name instead of an object at index 0, or passing `ClassName::methodName`**.This means that all of the following method calls are valid:Going back to [1], if `$arrow` is an `array` instead of a `string` or `closure`, the validation check to prevent invocation of unsafe functions is completely skipped. Multiple static class methods within Grav's codebase and its dependencies were found to be suitable gadgets for achieving for remote code execution:Exploit Conditions:This vulnerability can be exploited if the attacker has access to:an administrator account, ora non-administrator, user account that are granted the following permissions:login access to Grav admin panel, andpage creation or update rightsReproduction Steps:Log in to Grav Admin using an administrator account.Navigate to `Accounts > Add`, and ensure that the following permissions are assigned when creating a new low-privileged user:Login to Admin - AllowedPage Update - AllowedLog out of Grav Admin, and log back in using the account created in step 2.Navigate to `http://<grav_installation>/admin/pages/home`.Click the `Advanced` tab and select the checkbox beside `Twig` to ensure that Twig processing is enabled for the modified webpage.Under the `Content` tab, insert the following payload within the editor:Click the Preview button. Observe that the output of the `id` shell command is returned in the preview.Suggested Mitigations:Patch the logic flaw in the `GravExtension.filterFilter()` function declared in `/system/src/Grav/Common/Twig/Extension/GravExtension.php` to ensure that the `$arrow` paramater passed to the `filterFilter()` function must either be a `string` or an arrow function as such:`Utils::isDangerousFunction()` in [/system/src/Grav/Common/Utils.php](https://github.com/getgrav/grav/blob/1.7.40/system/src/Grav/Common/Utils.php#L1956-L2074) should also be patched to prevent static class methods from being invoked. For example,End users should also ensure that `twig.undefined_functions` and `twig.undefined_filters` properties in `/path/to/webroot/system/config/system.yaml` configuration file are set to `false` to disallow Twig from treating undefined filters/functions as PHP functions and executing them.Detection Guidance:The following strategies may be used to detect potential exploitation attempts.Searching within Markdown pages using the following shell command:  
`grep -Priz -e '\|\s*(filter|map|reduce)\s*\(' /path/to/webroot/user/pages/`Searching within Doctrine cache data using the following shell command:  
`grep -Priz -e '\|\s*(filter|map|reduce)\s*\('  --include '*.doctrinecache.data' /path/to/webroot/cache/`Searching within Twig cache using the following shell command:  
`grep -Priz -e 'twig_array_(filter|map|reduce)' /path/to/webroot/cache/twig/`Searching within compiled Twig template files using the following shell command:  
`grep -Priz -e '\|\s*(filter|map|reduce)\s*\(' /path/to/webroot/cache/compiled/files/`Note that it is not possible to detect indicators of compromise reliably using the Grav log file (located at `/path/to/webroot/logs/grav.log` by default), as successful exploitation attempts do not generate any additional logs. However, it is worthwhile to examine any PHP errors or warnings logged to determine the existence of any failed exploitation attempts.Credits:Ngo Wei Lin ([@Creastery](https://twitter.com/Creastery)) & Wang Hengyue ([@w_hy_04](https://twitter.com/w_hy_04)) of STAR Labs SG Pte. Ltd. ([@starlabs_sg](https://twitter.com/starlabs_sg))Kindly note that STAR Labs reserved and assigned the following CVE identifiers to the respective vulnerabilities presented in this report:**CVE-2023-30595**
 Server-side Template Injection (SSTI) in getgrav/grav <= v1.7.40 allows Grav Admin users with page creation or update rights to bypass the dangerous functions denylist check in `GravExtension.filterFilter()` and to achieve remote code execution via usage of fully-qualified names, supplied as arrays of strings, when referencing callables. This is a bypass of CVE-2022-2073.
CVSS v3.1 score: 7.2