Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Not released yet

* Fixed PHAR resources being extracted to a predictable directory shared between users: another local user could tamper with the extracted binaries and FFI header. They are now extracted to a private per-user cache directory
* Fixed argument injection in `NotifySendDriver`: notification titles and bodies could be interpreted as `notify-send` options, potentially causing denial of service

## 3.4.0 (2026-09-09)
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"php": ">=8.3",
"jolicode/php-os-helper": "^0.3",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"symfony/filesystem": "^6.4 || ^7.3 || ^8.0",
"symfony/process": "^6.4 || ^7.3 || ^8.0"
},
"require-dev": {
Expand Down
14 changes: 14 additions & 0 deletions doc/05-cli-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ page](https://github.com/jolicode/JoliNotif/releases):
curl https://github.com/jolicode/JoliNotif/releases/latest/download/jolinotif.phar && sudo mv jolinotif.phar /usr/local/bin/jolinotif
```

### PHAR resource cache

When running from a PHAR, JoliNotif extracts embedded binaries and icons into a
per-user cache:

* Linux, macOS, and other Unix systems: `$XDG_CACHE_HOME/jolinotif`, which
defaults to `$HOME/.cache/jolinotif`. If it can not be used, JoliNotif falls
back to a `jolinotif-<uid>` directory inside the system temporary directory.
* Windows: a `jolinotif` directory inside the user temporary directory.

On Unix systems, the cache directory must be owned by the current user with
permissions `0700`. Directories left by other versions of the PHAR are removed
when they have not been used for 30 days.

## Usage

```bash
Expand Down
14 changes: 10 additions & 4 deletions src/Driver/AbstractCliBasedDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace Joli\JoliNotif\Driver;

use Joli\JoliNotif\Exception\DriverFailureException;
use Joli\JoliNotif\Exception\InvalidNotificationException;
use Joli\JoliNotif\Exception\PharExtractionException;
use Joli\JoliNotif\Notification;
use Joli\JoliNotif\Util\PharExtractor;
use Psr\Log\LoggerInterface;
Expand Down Expand Up @@ -74,10 +76,14 @@ public function send(Notification $notification): bool
$embeddedBinary = $dir . $this->getEmbeddedBinary();

if (PharExtractor::isLocatedInsideAPhar($embeddedBinary)) {
$embeddedBinary = PharExtractor::extractFile($embeddedBinary);

foreach ($this->getExtraFiles() as $file) {
PharExtractor::extractFile($dir . $file);
try {
$embeddedBinary = PharExtractor::extractFile($embeddedBinary);

foreach ($this->getExtraFiles() as $file) {
PharExtractor::extractFile($dir . $file);
}
} catch (PharExtractionException $e) {
throw new DriverFailureException($notification, 'Unable to extract the embedded binary: ' . $e->getMessage(), 0, $e);
}
}

Expand Down
16 changes: 16 additions & 0 deletions src/Exception/PharExtractionException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

/*
* This file is part of the JoliNotif project.
*
* (c) Loïck Piera <pyrech@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Joli\JoliNotif\Exception;

class PharExtractionException extends \RuntimeException implements ExceptionInterface
{
}
8 changes: 7 additions & 1 deletion src/Notification.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Joli\JoliNotif;

use Joli\JoliNotif\Exception\PharExtractionException;
use Joli\JoliNotif\Util\PharExtractor;
use JoliCode\PhpOsHelper\OsHelper;

Expand Down Expand Up @@ -55,7 +56,12 @@ public function setIcon(string $icon): self
{
// This makes the icon accessible for native commands when it's embedded inside a phar
if (PharExtractor::isLocatedInsideAPhar($icon)) {
$icon = PharExtractor::extractFile($icon);
try {
$icon = PharExtractor::extractFile($icon);
} catch (PharExtractionException) {
// A notification without icon is better than no notification
$icon = null;
}
} else {
// Makes the icon path absolute (expanding all symbolic links and resolving references like "/../")
$icon = OsHelper::isWindowsSubsystemForLinux()
Expand Down
169 changes: 164 additions & 5 deletions src/Util/PharExtractor.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@

namespace Joli\JoliNotif\Util;

use Joli\JoliNotif\Exception\PharExtractionException;
use Symfony\Component\Filesystem\Filesystem;

/**
* @internal
*/
class PharExtractor
{
private const STALE_AFTER = 30 * 24 * 3600;

/**
* Return whether the file path is located inside a phar.
*/
Expand Down Expand Up @@ -45,14 +50,168 @@ public static function extractFile(string $filePath, bool $overwrite = false): s
}

$relativeFilePath = substr($filePath, $pharPosition + \strlen($pharPath) + 1);
$tmpDir = sys_get_temp_dir() . '/jolinotif';
$extractedFilePath = $tmpDir . '/' . $relativeFilePath;
$extractionDir = self::getExtractionDirectory($pharPath);
$extractedFilePath = $extractionDir . '/' . $relativeFilePath;
$lockPath = $extractionDir . '/.lock';
$lock = fopen($lockPath, 'c');

if (!file_exists($extractedFilePath) || $overwrite) {
$phar = new \Phar($pharPath);
$phar->extractTo($tmpDir, $relativeFilePath, $overwrite);
if (false === $lock) {
throw new PharExtractionException('Unable to open the PHAR extraction lock.');
}

try {
if (!flock($lock, \LOCK_EX)) {
throw new PharExtractionException('Unable to lock the PHAR extraction directory.');
}

// Mark the directory as still in use, so it does not get pruned.
touch($lockPath);

// Check after acquiring the lock: another process may have extracted the file.
clearstatcache(true, $extractedFilePath);

if (!file_exists($extractedFilePath) || $overwrite) {
$phar = new \Phar($pharPath);
$phar->extractTo($extractionDir, $relativeFilePath, $overwrite);
}
} finally {
fclose($lock);
}

return $extractedFilePath;
}

private static function getExtractionDirectory(string $pharPath): string
{
$cacheDir = self::getCacheDirectory();
$extractionDir = $cacheDir . '/' . self::getPharHash($pharPath);

if (!is_dir($extractionDir)) {
self::pruneStaleDirectories($cacheDir);
}

self::createPrivateDirectory($extractionDir);

return $extractionDir;
}

private static function getPharHash(string $pharPath): string
{
// The signature is already computed, no need to hash the whole archive again.
return strtolower((new \Phar($pharPath))->getSignature()['hash']);
}

private static function getCacheDirectory(): string
{
$exception = null;

foreach (self::getCacheDirectoryCandidates() as $directory) {
try {
self::createPrivateDirectory($directory);

return $directory;
} catch (PharExtractionException $exception) {
}
}

throw $exception ?? new PharExtractionException('Unable to locate a cache directory.');
}

/**
* @return list<string>
*/
private static function getCacheDirectoryCandidates(): array
{
// The temporary directory is already private to the user on Windows.
if ('Windows' === \PHP_OS_FAMILY) {
return [sys_get_temp_dir() . '/jolinotif'];
}

$candidates = [];
$cacheHome = getenv('XDG_CACHE_HOME');

if (!$cacheHome || !str_starts_with($cacheHome, '/')) {
$homeDir = getenv('HOME');
$cacheHome = $homeDir && str_starts_with($homeDir, '/') && is_dir($homeDir) ? rtrim($homeDir, '/') . '/.cache' : null;
}

if ($cacheHome) {
$candidates[] = rtrim($cacheHome, '/') . '/jolinotif';
}

// The home directory is not always available (cron, containers, system users, etc).
$candidates[] = sys_get_temp_dir() . '/jolinotif-' . self::getCurrentUserId();

return $candidates;
}

/**
* Remove the directories left by other versions of the PHAR and not used for a while.
*/
private static function pruneStaleDirectories(string $cacheDir): void
{
$limit = time() - self::STALE_AFTER;

try {
foreach (scandir($cacheDir) ?: [] as $name) {
$directory = $cacheDir . '/' . $name;

if ('.' === $name || '..' === $name || is_link($directory) || !is_dir($directory)) {
continue;
}

if (max((int) @filemtime($directory), (int) @filemtime($directory . '/.lock')) >= $limit) {
continue;
}

(new Filesystem())->remove($directory);
}
} catch (\Throwable) {
// Pruning is only housekeeping, it should never prevent the extraction.
}
}

private static function createPrivateDirectory(string $directory): void
{
// A concurrent creator is fine; validate the resulting directory in either case.
@mkdir($directory, 0o700, true);
clearstatcache(true, $directory);
$stat = @lstat($directory);

if (false === $stat || ($stat['mode'] & 0o170000) !== 0o040000) {
throw new PharExtractionException(\sprintf('The cache path "%s" is not a real directory.', $directory));
}

// Windows uses inherited profile ACLs, not POSIX ownership or permission bits.
if ('Windows' === \PHP_OS_FAMILY) {
return;
}

if (($stat['mode'] & 0o777) !== 0o700 || $stat['uid'] !== self::getCurrentUserId()) {
throw new PharExtractionException(\sprintf('The cache directory "%s" must be owned by the current user with permissions 0700.', $directory));
}
}

private static function getCurrentUserId(): int
{
if (\function_exists('posix_geteuid')) {
return posix_geteuid();
}

// POSIX is optional. A newly created file also identifies the effective owner.
$file = tmpfile();

if (false === $file) {
throw new PharExtractionException('Unable to determine the current user ID.');
}

$stat = fstat($file);
fclose($file);

if (false === $stat) {
throw new PharExtractionException('Unable to determine the current user ID.');
}

return $stat['uid'];
}
}
60 changes: 41 additions & 19 deletions tests/NotificationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@

use Joli\JoliNotif\Notification;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Process\Process;

class NotificationTest extends TestCase
{
public function testItExtractsIconFromPhar(): void
{
$key = (string) random_int(0, 10000);
$key = bin2hex(random_bytes(8));
$iconContent = $key;
$rootPackage = \dirname(__DIR__);
$iconRelativePath = 'Resources/notification/icon-' . $key . '.png';
$testDir = sys_get_temp_dir() . '/test-jolinotif';
$testDir = sys_get_temp_dir() . '/jolinotif-notification-' . $key;
$homeDir = $testDir . '/home';
$pharPath = $testDir . '/notification-extract-icon-' . $key . '.phar';
$extractedIconPath = sys_get_temp_dir() . '/jolinotif/' . $iconRelativePath;

if (!is_dir($testDir)) {
mkdir($testDir);
}
mkdir($homeDir, 0o700, true);

$bootstrap = <<<'PHAR_BOOTSTRAP'
<?php
Expand All @@ -40,6 +40,8 @@ public function testItExtractsIconFromPhar(): void
$notification = new \Joli\JoliNotif\Notification();
$notification->setBody('My notification');
$notification->setIcon(__DIR__.$iconPath);

echo $notification->getIcon();
PHAR_BOOTSTRAP;

$files = (new Finder())
Expand All @@ -49,22 +51,42 @@ public function testItExtractsIconFromPhar(): void
->files()
;

$phar = new \Phar($pharPath);
$phar->buildFromIterator($files->getIterator(), $rootPackage);
$phar->addFromString('bootstrap.php', str_replace(
'{{ THE_ICON }}',
$iconRelativePath,
$bootstrap
));
$phar->addFromString($iconRelativePath, $iconContent);
$phar->setStub($phar->createDefaultStub('bootstrap.php'));
try {
$phar = new \Phar($pharPath);
$phar->buildFromIterator($files->getIterator(), $rootPackage);
$phar->addFromString('bootstrap.php', str_replace(
'{{ THE_ICON }}',
$iconRelativePath,
$bootstrap
));
$phar->addFromString($iconRelativePath, $iconContent);
$phar->setStub($phar->createDefaultStub('bootstrap.php'));

$this->assertFileExists($pharPath);

$this->assertFileExists($pharPath);
$process = new Process(
[\PHP_BINARY, $pharPath],
$testDir,
['HOME' => $homeDir, 'XDG_CACHE_HOME' => false, 'TMPDIR' => $homeDir, 'TMP' => $homeDir, 'TEMP' => $homeDir],
);
$process->mustRun();
$extractedIconPath = $process->getOutput();

exec('php ' . $pharPath);
$this->assertStringStartsWith(
str_replace('\\', '/', $homeDir) . '/',
str_replace('\\', '/', $extractedIconPath),
);
$this->assertFileExists($extractedIconPath);
$this->assertSame($iconContent, file_get_contents($extractedIconPath));
} finally {
unset($phar);

$this->assertFileExists($extractedIconPath);
$this->assertSame($iconContent, file_get_contents($extractedIconPath));
if (file_exists($pharPath)) {
\Phar::unlinkArchive($pharPath);
}

(new Filesystem())->remove($testDir);
}
}

public function testItResolvesRealPathToIcon(): void
Expand Down
Loading
Loading