diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f65103..4da1322 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## 2.9.4 - Upcoming + +* Fixed the compiled runtime to use a private default cache directory, preventing local code execution. + ## 2.9.3 - 2026-11-16 * Fixed merge() to error on scalar and null arguments instead of triggering PHP errors. diff --git a/README.md b/README.md index 23b89bc..bd5f304 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,11 @@ $runtime('foo.bar', ['foo' => ['bar' => 'baz']]); // > 'baz' ``` +The cache directory holds PHP files that are executed when loaded, so it must +not be writable by untrusted users. When no directory is provided, a private +per-user directory inside the system temp directory is used, except on +Windows, where the system temp directory itself is used. + ##### Environment Variables You can utilize the CompilerRuntime in `JmesPath\search()` by setting the diff --git a/bin/perf.php b/bin/perf.php index aa93959..2155a15 100755 --- a/bin/perf.php +++ b/bin/perf.php @@ -57,7 +57,7 @@ function runCase($given, $expression, $name) $runtime = \JmesPath\Env::createRuntime(); // Delete compiled scripts if not caching. if ($runtime instanceof \JmesPath\CompilerRuntime) { - array_map('unlink', glob(sys_get_temp_dir() . '/jmespath_*.php')); + array_map('unlink', glob($runtime->getCacheDir() . '/jmespath_*.php')); } } } diff --git a/src/CompilerRuntime.php b/src/CompilerRuntime.php index 3edab38..af55a2e 100644 --- a/src/CompilerRuntime.php +++ b/src/CompilerRuntime.php @@ -20,6 +20,7 @@ class CompilerRuntime private $compiler; private $cacheDir; private $interpreter; + private $tempDir; /** * @param string|null $dir Directory used to store compiled PHP files. @@ -30,7 +31,11 @@ public function __construct($dir = null, ?Parser $parser = null) { $this->parser = $parser ?: new Parser(); $this->compiler = new TreeCompiler(); - $dir = $dir ?: sys_get_temp_dir(); + + if (!$dir) { + $dir = self::defaultCacheDir(); + $this->tempDir = realpath(sys_get_temp_dir()); + } if (!is_dir($dir) && !mkdir($dir, 0755, true)) { throw new \RuntimeException("Unable to create cache directory: $dir"); @@ -57,6 +62,11 @@ public function __invoke($expression, $data) $functionName = self::functionName($expression); if (!function_exists($functionName)) { + if ($this->tempDir) { + // A long-lived process can outlive the directory it checked. + $this->cacheDir = self::defaultCacheDir($this->tempDir); + } + $filename = "{$this->cacheDir}/{$functionName}.php"; if (!file_exists($filename)) { $this->compile($filename, $expression, $functionName); @@ -78,12 +88,66 @@ public static function functionName($expression) ); } + /** + * @internal Shared with Env so the default location cannot drift. + */ + public static function defaultCacheDir($temp = null) + { + $dir = $temp ?: sys_get_temp_dir(); + + if (PHP_OS_FAMILY === 'Windows') { + return $dir; + } + + $uid = self::effectiveUserId(); + $dir = rtrim($dir, '/') . "/jmespath-{$uid}"; + + clearstatcache(true, $dir); + + if (!is_dir($dir)) { + @mkdir($dir, 0700, true); + } + + // A single lstat() so the type, owner and mode describe the same file. + $stat = @lstat($dir); + + if (!$stat + || ($stat['mode'] & 0170000) !== 0040000 + || $stat['uid'] !== $uid + || ($stat['mode'] & 0077) !== 0 + ) { + throw new \RuntimeException( + "Unable to use private cache directory: {$dir}" + ); + } + + return $dir; + } + /** @internal */ public function getCacheDir() { return $this->cacheDir; } + private static function effectiveUserId() + { + if (function_exists('posix_geteuid')) { + return posix_geteuid(); + } + + $file = tmpfile(); + + if (!$file) { + throw new \RuntimeException('Unable to determine the current user'); + } + + $uid = fstat($file)['uid']; + fclose($file); + + return $uid; + } + private function compile($filename, $expression, $functionName) { $code = $this->compiler->visit( diff --git a/src/Env.php b/src/Env.php index b894b80..61024b3 100644 --- a/src/Env.php +++ b/src/Env.php @@ -50,7 +50,7 @@ public static function createRuntime() /** * Delete all previously compiled JMESPath files from the JP_COMPILE_DIR - * directory or sys_get_temp_dir(). + * directory or the default cache directory. * * @return int Returns the number of deleted files. */ @@ -59,7 +59,11 @@ public static function cleanCompileDir() $total = 0; $compileDir = self::getEnvVariable(self::COMPILE_DIR); if ($compileDir === 'on' || !$compileDir) { - $compileDir = sys_get_temp_dir(); + try { + $compileDir = CompilerRuntime::defaultCacheDir(); + } catch (\RuntimeException $e) { + return $total; + } } foreach (glob("{$compileDir}/jmespath_*.php") as $file) { diff --git a/tests/CompilerRuntimeTest.php b/tests/CompilerRuntimeTest.php index 504756f..414a742 100644 --- a/tests/CompilerRuntimeTest.php +++ b/tests/CompilerRuntimeTest.php @@ -36,6 +36,128 @@ public function testFunctionNameUsesVersionedSalt(): void ); } + /** + * @requires function posix_geteuid + */ + public function testDefaultCacheDirIsPrivateToCurrentUser(): void + { + $temp = $this->createTempDir(); + $dir = $temp . '/jmespath-' . posix_geteuid(); + + try { + $this->assertSame($dir, $this->runInTempDir($temp, 'echo (new JmesPath\CompilerRuntime())->getCacheDir();')); + $this->assertSame(posix_geteuid(), fileowner($dir)); + $this->assertSame(0700, fileperms($dir) & 0777); + } finally { + $this->removeTempDir($dir); + $this->removeTempDir($temp); + } + } + + /** + * @requires function posix_geteuid + */ + public function testDefaultCacheDirIgnoresFilesInSystemTempDir(): void + { + $temp = $this->createTempDir(); + $name = CompilerRuntime::functionName('foo'); + file_put_contents($temp . '/' . $name . '.php', "assertSame('123', $this->runInTempDir($temp, 'echo (new JmesPath\CompilerRuntime())("foo", ["foo" => 123]);')); + } finally { + $this->removeTempDir($temp . '/jmespath-' . posix_geteuid()); + $this->removeTempDir($temp); + } + } + + /** + * @requires function posix_geteuid + */ + public function testRejectsDefaultCacheDirAccessibleByOthers(): void + { + $temp = $this->createTempDir(); + $dir = $temp . '/jmespath-' . posix_geteuid(); + mkdir($dir); + chmod($dir, 0755); + + try { + $this->assertSame( + "Unable to use private cache directory: {$dir}", + $this->runInTempDir($temp, 'new JmesPath\CompilerRuntime();') + ); + } finally { + $this->removeTempDir($dir); + $this->removeTempDir($temp); + } + } + + /** + * @requires function posix_geteuid + */ + public function testRejectsSymlinkedDefaultCacheDir(): void + { + $temp = $this->createTempDir(); + $dir = $temp . '/jmespath-' . posix_geteuid(); + $target = $this->createTempDir(); + chmod($target, 0700); + symlink($target, $dir); + + try { + $this->assertSame( + "Unable to use private cache directory: {$dir}", + $this->runInTempDir($temp, 'new JmesPath\CompilerRuntime();') + ); + } finally { + unlink($dir); + $this->removeTempDir($target); + $this->removeTempDir($temp); + } + } + + /** + * @requires function posix_geteuid + */ + public function testChecksDefaultCacheDirAgainBeforeLoading(): void + { + $temp = $this->createTempDir(); + $dir = $temp . '/jmespath-' . posix_geteuid(); + + try { + $this->runInTempDir($temp, '(new JmesPath\CompilerRuntime())("foo", []);'); + $this->assertSame( + "Unable to use private cache directory: {$dir}", + $this->runInTempDir( + $temp, + '$runtime = new JmesPath\CompilerRuntime(); chmod($runtime->getCacheDir(), 0755); $runtime("foo", []);' + ) + ); + } finally { + $this->removeTempDir($dir); + $this->removeTempDir($temp); + } + } + + /** + * @requires function posix_geteuid + */ + public function testKeepsDefaultCacheDirWhenWorkingDirectoryChanges(): void + { + $temp = $this->createTempDir(); + $dir = $temp . '/jmespath-' . posix_geteuid(); + $code = sprintf( + 'chdir(%s); $runtime = new JmesPath\CompilerRuntime(); chdir("/"); $runtime("foo", []); echo $runtime->getCacheDir();', + var_export($temp, true) + ); + + try { + $this->assertSame($dir, $this->runInTempDir('.', $code)); + } finally { + $this->removeTempDir($dir); + $this->removeTempDir($temp); + } + } + public function testRuntimesUseJmesPathTruthinessForEmptyObjects(): void { $dir = $this->createTempDir(); @@ -192,6 +314,23 @@ public function testStillCompilesValidFunctions(): void } } + private function runInTempDir($temp, $code) + { + $command = sprintf( + '%s -d sys_temp_dir=%s -r %s 2>&1', + escapeshellarg(PHP_BINARY), + escapeshellarg($temp), + escapeshellarg(sprintf( + 'require %s; try { %s } catch (RuntimeException $e) { echo $e->getMessage(); }', + var_export(__DIR__ . '/../vendor/autoload.php', true), + $code + )) + ); + exec($command, $output); + + return implode("\n", $output); + } + private function createTempDir() { $dir = sys_get_temp_dir() . '/jmespath-compiler-' . bin2hex(random_bytes(12)); diff --git a/tests/ComplianceTest.php b/tests/ComplianceTest.php index b79d33c..39f5885 100644 --- a/tests/ComplianceTest.php +++ b/tests/ComplianceTest.php @@ -12,11 +12,8 @@ class ComplianceTest extends TestCase public static function setUpBeforeClass(): void { - self::$path = sys_get_temp_dir() . '/jmespath-compliance-compiled'; - if (!is_dir(self::$path)) { - mkdir(self::$path, 0777, true); - } - array_map('unlink', glob(self::$path . '/jmespath_*.php') ?: []); + self::$path = sys_get_temp_dir() . '/jmespath-compliance-' . bin2hex(random_bytes(12)); + mkdir(self::$path); } public static function tearDownAfterClass(): void diff --git a/tests/EnvTest.php b/tests/EnvTest.php index 4e1eb43..4f01695 100644 --- a/tests/EnvTest.php +++ b/tests/EnvTest.php @@ -22,8 +22,8 @@ public function testSearchesWithFunction(): void public function testCleansCompileDir(): void { - $dir = sys_get_temp_dir(); - $runtime = new CompilerRuntime($dir); + $runtime = new CompilerRuntime(); + $dir = $runtime->getCacheDir(); $runtime('@ | @ | @[0][0][0]', []); $this->assertNotEmpty(glob($dir . '/jmespath_*.php')); $this->assertGreaterThan(0, Env::cleanCompileDir()); @@ -37,8 +37,8 @@ public function testCleansCompileDirWhenCompileEnvIsOn(): void $_SERVER[Env::COMPILE_DIR] = 'on'; $expr = 'env' . bin2hex(random_bytes(12)); - $filename = sys_get_temp_dir() . '/' . CompilerRuntime::functionName($expr) . '.php'; - $runtime = new CompilerRuntime(sys_get_temp_dir()); + $runtime = new CompilerRuntime(); + $filename = $runtime->getCacheDir() . '/' . CompilerRuntime::functionName($expr) . '.php'; try { $this->assertSame(1, $runtime($expr, [$expr => 1]));