PharExtensionInterceptor.php 2.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<?php

namespace Drupal\Core\Security;

use TYPO3\PharStreamWrapper\Assertable;
use TYPO3\PharStreamWrapper\Helper;
use TYPO3\PharStreamWrapper\Exception;

/**
 * An alternate PharExtensionInterceptor to support phar-based CLI tools.
 *
 * @see \TYPO3\PharStreamWrapper\Interceptor\PharExtensionInterceptor
 */
class PharExtensionInterceptor implements Assertable {

  /**
   * Determines whether phar file is allowed to execute.
   *
   * The phar file is allowed to execute if:
   * - the base file name has a ".phar" suffix.
   * - it is the CLI tool that has invoked the interceptor.
   *
   * @param string $path
   *   The path of the phar file to check.
   * @param string $command
   *   The command being carried out.
   *
   * @return bool
   *   TRUE if the phar file is allowed to execute.
   *
31
   * @throws \TYPO3\PharStreamWrapper\Exception
32 33
   *   Thrown when the file is not allowed to execute.
   */
34
  public function assert(string $path, string $command): bool {
35 36 37 38 39 40 41 42 43 44 45 46 47
    if ($this->baseFileContainsPharExtension($path)) {
      return TRUE;
    }
    throw new Exception(
      sprintf(
        'Unexpected file extension in "%s"',
        $path
      ),
      1535198703
    );
  }

  /**
48 49
   * Determines if a path has a .phar extension or invoked execution.
   *
50 51 52 53 54 55 56 57 58 59 60 61 62
   * @param string $path
   *   The path of the phar file to check.
   *
   * @return bool
   *   TRUE if the file has a .phar extension or if the execution has been
   *   invoked by the phar file.
   */
  private function baseFileContainsPharExtension($path) {
    $baseFile = Helper::determineBaseFile($path);
    if ($baseFile === NULL) {
      return FALSE;
    }
    // If the stream wrapper is registered by invoking a phar file that does
63 64
    // not have .phar extension then this should be allowed. For example, some
    // CLI tools recommend removing the extension.
65
    $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
66 67 68 69 70 71 72
    // Find the last entry in the backtrace containing a 'file' key as
    // sometimes the last caller is executed outside the scope of a file. For
    // example, this occurs with shutdown functions.
    do {
      $caller = array_pop($backtrace);
    } while (empty($caller['file']) && !empty($backtrace));
    if (isset($caller['file']) && $baseFile === Helper::determineBaseFile($caller['file'])) {
73 74 75 76 77 78 79
      return TRUE;
    }
    $fileExtension = pathinfo($baseFile, PATHINFO_EXTENSION);
    return strtolower($fileExtension) === 'phar';
  }

}