vendor/symfony/framework-bundle/Secrets/SodiumVault.php line 35

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\FrameworkBundle\Secrets;
  11. use Symfony\Component\DependencyInjection\EnvVarLoaderInterface;
  12. use Symfony\Component\VarExporter\VarExporter;
  13. /**
  14.  * @author Tobias Schultze <http://tobion.de>
  15.  * @author Jérémy Derussé <jeremy@derusse.com>
  16.  * @author Nicolas Grekas <p@tchwork.com>
  17.  *
  18.  * @internal
  19.  */
  20. class SodiumVault extends AbstractVault implements EnvVarLoaderInterface
  21. {
  22.     private ?string $encryptionKey = null;
  23.     private string|\Stringable|null $decryptionKey = null;
  24.     private string $pathPrefix;
  25.     private ?string $secretsDir;
  26.     /**
  27.      * @param $decryptionKey A string or a stringable object that defines the private key to use to decrypt the vault
  28.      *                       or null to store generated keys in the provided $secretsDir
  29.      */
  30.     public function __construct(string $secretsDir, string|\Stringable $decryptionKey = null)
  31.     {
  32.         $this->pathPrefix = rtrim(strtr($secretsDir, '/', \DIRECTORY_SEPARATOR), \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR.basename($secretsDir).'.';
  33.         $this->decryptionKey = $decryptionKey;
  34.         $this->secretsDir = $secretsDir;
  35.     }
  36.     public function generateKeys(bool $override = false): bool
  37.     {
  38.         $this->lastMessage = null;
  39.         if (null === $this->encryptionKey && '' !== $this->decryptionKey = (string) $this->decryptionKey) {
  40.             $this->lastMessage = 'Cannot generate keys when a decryption key has been provided while instantiating the vault.';
  41.             return false;
  42.         }
  43.         try {
  44.             $this->loadKeys();
  45.         } catch (\RuntimeException $e) {
  46.             // ignore failures to load keys
  47.         }
  48.         if ('' !== $this->decryptionKey && !is_file($this->pathPrefix.'encrypt.public.php')) {
  49.             $this->export('encrypt.public', $this->encryptionKey);
  50.         }
  51.         if (!$override && null !== $this->encryptionKey) {
  52.             $this->lastMessage = sprintf('Sodium keys already exist at "%s*.{public,private}" and won\'t be overridden.', $this->getPrettyPath($this->pathPrefix));
  53.             return false;
  54.         }
  55.         $this->decryptionKey = sodium_crypto_box_keypair();
  56.         $this->encryptionKey = sodium_crypto_box_publickey($this->decryptionKey);
  57.         $this->export('encrypt.public', $this->encryptionKey);
  58.         $this->export('decrypt.private', $this->decryptionKey);
  59.         $this->lastMessage = sprintf('Sodium keys have been generated at "%s*.public/private.php".', $this->getPrettyPath($this->pathPrefix));
  60.         return true;
  61.     }
  62.     public function seal(string $name, string $value): void
  63.     {
  64.         $this->lastMessage = null;
  65.         $this->validateName($name);
  66.         $this->loadKeys();
  67.         $filename = $this->getFilename($name);
  68.         $this->export($filename, sodium_crypto_box_seal($value, $this->encryptionKey ?? sodium_crypto_box_publickey($this->decryptionKey)));
  69.         $list = $this->list();
  70.         $list[$name] = null;
  71.         uksort($list, 'strnatcmp');
  72.         file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", VarExporter::export($list)), \LOCK_EX);
  73.         $this->lastMessage = sprintf('Secret "%s" encrypted in "%s"; you can commit it.', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
  74.     }
  75.     public function reveal(string $name): ?string
  76.     {
  77.         $this->lastMessage = null;
  78.         $this->validateName($name);
  79.         $filename = $this->getFilename($name);
  80.         if (!is_file($file = $this->pathPrefix.$filename.'.php')) {
  81.             $this->lastMessage = sprintf('Secret "%s" not found in "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
  82.             return null;
  83.         }
  84.         if (!\function_exists('sodium_crypto_box_seal')) {
  85.             $this->lastMessage = sprintf('Secret "%s" cannot be revealed as the "sodium" PHP extension missing. Try running "composer require paragonie/sodium_compat" if you cannot enable the extension."', $name);
  86.             return null;
  87.         }
  88.         $this->loadKeys();
  89.         if ('' === $this->decryptionKey) {
  90.             $this->lastMessage = sprintf('Secret "%s" cannot be revealed as no decryption key was found in "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
  91.             return null;
  92.         }
  93.         if (false === $value = sodium_crypto_box_seal_open(include $file, $this->decryptionKey)) {
  94.             $this->lastMessage = sprintf('Secret "%s" cannot be revealed as the wrong decryption key was provided for "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
  95.             return null;
  96.         }
  97.         return $value;
  98.     }
  99.     public function remove(string $name): bool
  100.     {
  101.         $this->lastMessage = null;
  102.         $this->validateName($name);
  103.         $filename = $this->getFilename($name);
  104.         if (!is_file($file = $this->pathPrefix.$filename.'.php')) {
  105.             $this->lastMessage = sprintf('Secret "%s" not found in "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
  106.             return false;
  107.         }
  108.         $list = $this->list();
  109.         unset($list[$name]);
  110.         file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", VarExporter::export($list)), \LOCK_EX);
  111.         $this->lastMessage = sprintf('Secret "%s" removed from "%s".', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
  112.         return @unlink($file) || !file_exists($file);
  113.     }
  114.     public function list(bool $reveal = false): array
  115.     {
  116.         $this->lastMessage = null;
  117.         if (!is_file($file = $this->pathPrefix.'list.php')) {
  118.             return [];
  119.         }
  120.         $secrets = include $file;
  121.         if (!$reveal) {
  122.             return $secrets;
  123.         }
  124.         foreach ($secrets as $name => $value) {
  125.             $secrets[$name] = $this->reveal($name);
  126.         }
  127.         return $secrets;
  128.     }
  129.     public function loadEnvVars(): array
  130.     {
  131.         return $this->list(true);
  132.     }
  133.     private function loadKeys(): void
  134.     {
  135.         if (!\function_exists('sodium_crypto_box_seal')) {
  136.             throw new \LogicException('The "sodium" PHP extension is required to deal with secrets. Alternatively, try running "composer require paragonie/sodium_compat" if you cannot enable the extension.".');
  137.         }
  138.         if (null !== $this->encryptionKey || '' !== $this->decryptionKey = (string) $this->decryptionKey) {
  139.             return;
  140.         }
  141.         if (is_file($this->pathPrefix.'decrypt.private.php')) {
  142.             $this->decryptionKey = (string) include $this->pathPrefix.'decrypt.private.php';
  143.         }
  144.         if (is_file($this->pathPrefix.'encrypt.public.php')) {
  145.             $this->encryptionKey = (string) include $this->pathPrefix.'encrypt.public.php';
  146.         } elseif ('' !== $this->decryptionKey) {
  147.             $this->encryptionKey = sodium_crypto_box_publickey($this->decryptionKey);
  148.         } else {
  149.             throw new \RuntimeException(sprintf('Encryption key not found in "%s".', \dirname($this->pathPrefix)));
  150.         }
  151.     }
  152.     private function export(string $filename, string $data): void
  153.     {
  154.         $b64 = 'decrypt.private' === $filename ? '// SYMFONY_DECRYPTION_SECRET='.base64_encode($data)."\n" : '';
  155.         $name = basename($this->pathPrefix.$filename);
  156.         $data = str_replace('%', '\x', rawurlencode($data));
  157.         $data = sprintf("<?php // %s on %s\n\n%sreturn \"%s\";\n", $name, date('r'), $b64, $data);
  158.         $this->createSecretsDir();
  159.         if (false === file_put_contents($this->pathPrefix.$filename.'.php', $data, \LOCK_EX)) {
  160.             $e = error_get_last();
  161.             throw new \ErrorException($e['message'] ?? 'Failed to write secrets data.', 0, $e['type'] ?? \E_USER_WARNING);
  162.         }
  163.     }
  164.     private function createSecretsDir(): void
  165.     {
  166.         if ($this->secretsDir && !is_dir($this->secretsDir) && !@mkdir($this->secretsDir, 0777, true) && !is_dir($this->secretsDir)) {
  167.             throw new \RuntimeException(sprintf('Unable to create the secrets directory (%s).', $this->secretsDir));
  168.         }
  169.         $this->secretsDir = null;
  170.     }
  171.     private function getFilename(string $name): string
  172.     {
  173.         // The MD5 hash allows making secrets case-sensitive. The filename is not enough on Windows.
  174.         return $name.'.'.substr(md5($name), 0, 6);
  175.     }
  176. }