3 namespace Civi\Core\Security
;
5 use TYPO3\PharStreamWrapper\Assertable
;
6 use TYPO3\PharStreamWrapper\Helper
;
7 use TYPO3\PharStreamWrapper\Exception
;
10 * An alternate PharExtensionInterceptor to support phar-based CLI tools.
12 * This is largely based on Drupal\Core\Security\PharExtensionInterceptor,
13 * originally licensed under GPL2+
15 * @see \TYPO3\PharStreamWrapper\Interceptor\PharExtensionInterceptor
17 class PharExtensionInterceptor
implements Assertable
{
20 * Determines whether phar file is allowed to execute.
22 * The phar file is allowed to execute if:
23 * - the base file name has a ".phar" suffix.
24 * - it is the CLI tool that has invoked the interceptor.
27 * The path of the phar file to check.
28 * @param string $command
29 * The command being carried out.
32 * TRUE if the phar file is allowed to execute.
35 * Thrown when the file is not allowed to execute.
37 public function assert(string $path, string $command): bool {
38 if ($this->baseFileContainsPharExtension($path)) {
43 'Unexpected file extension in "%s"',
51 * Determines if a path has a .phar extension or invoked execution.
54 * The path of the phar file to check.
57 * TRUE if the file has a .phar extension or if the execution has been
58 * invoked by the phar file.
60 private function baseFileContainsPharExtension($path) {
61 $baseFile = Helper
::determineBaseFile($path);
62 if ($baseFile === NULL) {
65 // If the stream wrapper is registered by invoking a phar file that does
66 // not not have .phar extension then this should be allowed. For
67 // example, some CLI tools recommend removing the extension.
68 $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS
);
69 // Find the last entry in the backtrace containing a 'file' key as
70 // sometimes the last caller is executed outside the scope of a file. For
71 // example, this occurs with shutdown functions.
73 $caller = array_pop($backtrace);
74 } while (empty($caller['file']) && !empty($backtrace));
75 if (isset($caller['file']) && $baseFile === Helper
::determineBaseFile($caller['file'])) {
78 $fileExtension = pathinfo($baseFile, PATHINFO_EXTENSION
);
79 return strtolower($fileExtension) === 'phar';