GHSA-Q8W8-6CQ5-J4H2
Scheduler\Job::createLockFile() follows symlinks in the world-writable system temp directory (local symlink attack)
Texto original en inglés · Ver en español
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-Q8W8-6CQ5-J4H2 divulgada | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
Summary
`Grav\Common\Scheduler\Job::createLockFile()` writes the job's overlap-prevention lock file with a plain `file_put_contents($this->lockFile, $content)` call, no check for whether `$this->lockFile` is already a symlink. The lock file's default directory is `sys_get_temp_dir()` (world-writable on typical Linux setups, `/tmp`), and its filename is derived directly from the job's `$id`, which for any job constructed with an explicit ID (the normal, documented way to use `Job`, and the only way `onlyOne()`'s overlap protection is meaningful for a recurring named task) is a predictable, human-chosen string, `hyphenize($id) . '.lock'`.
A local attacker who can write to the shared temp directory, another tenant on shared hosting, or another local account, can pre-create a symlink at the predictable lock file path pointing at any file the web server process can write to. The next time the scheduler runs that job, PHP's `file_put_contents()` follows the symlink and overwrites the real target file's content with the job ID string, corrupting it.
Affected product and version
Product: Grav CMS, getgrav/grav
Confirmed present in: 2.0.15, commit c2b46866857a93a0aa7048e7ed707ed3ed45dbc3
Affected code
`system/src/Grav/Common/Scheduler/Job.php`, constructor (default temp directory):
public function __construct($command, private $args = [], $id = null)
{
if (is_string($id)) {
$this->id = Grav::instance()['inflector']->hyphenize($id);
} else {
...
}
...
// initialize the directory path for lock files
$this->tempDir = sys_get_temp_dir();
...`onlyOne()`, where the lock file path is built from that ID with no randomness:
public function onlyOne($tempDir = null, ?callable $whenOverlapping = null)
{
if ($tempDir === null || !is_dir($tempDir)) {
$tempDir = $this->tempDir;
}
$this->lockFile = implode('/', [
trim($tempDir),
trim($this->id) . '.lock',
]);
...`createLockFile()`, the vulnerable write:
private function createLockFile(mixed $content = null)
{
if ($this->lockFile) {
if ($content === null || !is_string($content)) {
$content = $this->getId();
}
file_put_contents($this->lockFile, $content);
}
}No `is_link()` check, no `realpath()` containment check, no `O_NOFOLLOW`-equivalent flag, before the write.
Root cause
PHP's `file_put_contents()` follows symlinks by default, it operates on whatever the path resolves to, not on the path's own name. Combined with a predictable path in a directory other local users can write to, this is a standard TOCTOU-adjacent symlink attack (CWE-59).
Proof of concept, verified, real output
I confirmed PHP's actual symlink-following behavior for this exact call shape, `file_put_contents($path, $content)` with no flags, rather than assuming it from documentation:
<?php
// verify_symlink_behavior.php
$lockPath = '/tmp/symlink_poc/predictable-job-id.lock';
@unlink($lockPath);
symlink('/tmp/symlink_poc/target-file.txt', $lockPath);
echo "Target file before:\n";
echo file_get_contents('/tmp/symlink_poc/target-file.txt') . "\n";
// This is exactly Job::createLockFile()'s call:
// file_put_contents($this->lockFile, $content);
file_put_contents($lockPath, 'some-job-id');
echo "Target file after Job::createLockFile()-equivalent call:\n";
echo file_get_contents('/tmp/symlink_poc/target-file.txt') . "\n";
echo "Was the symlink target overwritten? " . (trim(file_get_contents('/tmp/symlink_poc/target-file.txt')) === 'some-job-id' ? 'YES' : 'NO') . "\n";Setup and run:
$ mkdir -p /tmp/symlink_poc
$ echo "original protected content - must not be overwritten" > /tmp/symlink_poc/target-file.txt
$ php verify_symlink_behavior.phpActual output:
Target file before:
original protected content - must not be overwritten
Target file after Job::createLockFile()-equivalent call:
some-job-id
Was the symlink target overwritten? YESThe attack file's original content is gone, replaced with the job-id string, through nothing more than a pre-placed symlink at the predictable lock path. This is the literal call `createLockFile()` makes, `file_put_contents($this->lockFile, $content)`, run against a symlink at the exact kind of predictable path (`<tempDir>/<job-id>.lock`) the real code constructs. I did not additionally spin up a full multi-user OS environment to demonstrate the cross-tenant angle, that's an infrastructure setup, not a code question, and the underlying PHP behavior demonstrated above is the entire mechanism, there is nothing further in Grav's own code that would prevent it.
Impact
Any local actor who can write to the scheduler's temp directory, default `sys_get_temp_dir()`, world-writable `/tmp` on typical Linux hosts, can, for any job an admin has configured with `.onlyOne()` and a predictable ID (the normal way to use this feature for a recurring named task, backups, log rotation, GPM update checks, whatever an operator names it), pre-place a symlink at `<tempDir>/<job-id>.lock` pointing at any file the web server process can write to. The next scheduled run of that job overwrites the target file's content with the job ID string. Depending on what the attacker points the symlink at, this ranges from denial of service (corrupting a file the site depends on) to a stepping stone in a larger chain if the corrupted content happens to matter for some other check. On single-tenant hosting this isn't reachable by an external attacker; on shared hosting, which Grav's own code comments elsewhere treat as an expected deployment scenario, it's a real boundary crossing between tenants.
Suggested fix
Refuse to write through an existing symlink, and/or move the default lock directory out of the shared system temp path into something scoped to the Grav install (a `cache://` or `tmp://` stream, consistent with how the rest of the codebase avoids raw `sys_get_temp_dir()` for anything security-relevant):
private function createLockFile(mixed $content = null)
{
if ($this->lockFile) {
if ($content === null || !is_string($content)) {
$content = $this->getId();
}
if (is_link($this->lockFile)) {
// Refuse to follow a pre-existing symlink at the lock path.
return;
}
file_put_contents($this->lockFile, $content, LOCK_EX);
}
}`is_link()` alone has a small TOCTOU window between the check and the write; a more complete fix opens the file with `fopen($this->lockFile, 'x')` (fails if the path already exists in any form, including as a symlink, since the file doesn't already exist under that exact name unless created by a prior legitimate run) or writes to a temp file and atomically renames it into place after verifying the destination directory itself, not just the final path, is not attacker-writable.
===========================================================
CWE FIELD
===========================================================
CWE-59, Improper Link Resolution Before File Access ('Link Following')
===========================================================
CVSS CALCULATOR SELECTIONS (v3.1)
===========================================================
Attack Vector: Local
Attack Complexity: Low
Privileges Required: Low
User Interaction: None
Scope: Unchanged
Confidentiality: None
Integrity: High
Availability: Low
Resulting vector: CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L
Approximate score: 6.1, severity Medium (I computed this by hand rather than pulling it from the calculator UI, please re-derive it there since I may be off by a small margin)
Note for the maintainer: Attack Vector is Local because this requires local filesystem access to the shared temp directory, another account on shared hosting, or another local process, it is not remotely triggerable. I set Privileges Required to Low to reflect "some local account, not root, not the Grav app's own account" rather than the web-facing privilege scale used in my other reports.
===========================================================
SEVERITY FIELD
===========================================================
Moderate
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
Packagistgetgrav/grav |
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-q8w8-6cq5-j4h2Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
