1
0

FixKeyLocation.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2022 Robin Appelman <robin@icewind.nl>
  5. *
  6. * @license GNU AGPL version 3 or any later version
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. namespace OCA\Encryption\Command;
  23. use OC\Encryption\Util;
  24. use OC\Files\View;
  25. use OCP\Files\Config\ICachedMountInfo;
  26. use OCP\Files\Config\IUserMountCache;
  27. use OCP\Files\Folder;
  28. use OCP\Files\File;
  29. use OCP\Files\IRootFolder;
  30. use OCP\Files\Node;
  31. use OCP\IUser;
  32. use OCP\IUserManager;
  33. use Symfony\Component\Console\Command\Command;
  34. use Symfony\Component\Console\Input\InputArgument;
  35. use Symfony\Component\Console\Input\InputInterface;
  36. use Symfony\Component\Console\Input\InputOption;
  37. use Symfony\Component\Console\Output\OutputInterface;
  38. class FixKeyLocation extends Command {
  39. private IUserManager $userManager;
  40. private IUserMountCache $userMountCache;
  41. private Util $encryptionUtil;
  42. private IRootFolder $rootFolder;
  43. private string $keyRootDirectory;
  44. private View $rootView;
  45. public function __construct(IUserManager $userManager, IUserMountCache $userMountCache, Util $encryptionUtil, IRootFolder $rootFolder) {
  46. $this->userManager = $userManager;
  47. $this->userMountCache = $userMountCache;
  48. $this->encryptionUtil = $encryptionUtil;
  49. $this->rootFolder = $rootFolder;
  50. $this->keyRootDirectory = rtrim($this->encryptionUtil->getKeyStorageRoot(), '/');
  51. $this->rootView = new View();
  52. parent::__construct();
  53. }
  54. protected function configure(): void {
  55. parent::configure();
  56. $this
  57. ->setName('encryption:fix-key-location')
  58. ->setDescription('Fix the location of encryption keys for external storage')
  59. ->addOption('dry-run', null, InputOption::VALUE_NONE, "Only list files that require key migration, don't try to perform any migration")
  60. ->addArgument('user', InputArgument::REQUIRED, "User id to fix the key locations for");
  61. }
  62. protected function execute(InputInterface $input, OutputInterface $output): int {
  63. $dryRun = $input->getOption('dry-run');
  64. $userId = $input->getArgument('user');
  65. $user = $this->userManager->get($userId);
  66. if (!$user) {
  67. $output->writeln("<error>User $userId not found</error>");
  68. return 1;
  69. }
  70. \OC_Util::setupFS($user->getUID());
  71. $mounts = $this->getSystemMountsForUser($user);
  72. foreach ($mounts as $mount) {
  73. $mountRootFolder = $this->rootFolder->get($mount->getMountPoint());
  74. if (!$mountRootFolder instanceof Folder) {
  75. $output->writeln("<error>System wide mount point is not a directory, skipping: " . $mount->getMountPoint() . "</error>");
  76. continue;
  77. }
  78. $files = $this->getAllFiles($mountRootFolder);
  79. foreach ($files as $file) {
  80. if ($this->isKeyStoredForUser($user, $file)) {
  81. if ($dryRun) {
  82. $output->writeln("<info>" . $file->getPath() . "</info> needs migration");
  83. } else {
  84. $output->write("Migrating key for <info>" . $file->getPath() . "</info> ");
  85. if ($this->copyKeyAndValidate($user, $file)) {
  86. $output->writeln("<info>✓</info>");
  87. } else {
  88. $output->writeln("<fg=red>❌</>");
  89. $output->writeln(" Failed to validate key for <error>" . $file->getPath() . "</error>, key will not be migrated");
  90. }
  91. }
  92. }
  93. }
  94. }
  95. return 0;
  96. }
  97. /**
  98. * @param IUser $user
  99. * @return ICachedMountInfo[]
  100. */
  101. private function getSystemMountsForUser(IUser $user): array {
  102. return array_filter($this->userMountCache->getMountsForUser($user), function(ICachedMountInfo $mount) use ($user) {
  103. $mountPoint = substr($mount->getMountPoint(), strlen($user->getUID() . '/'));
  104. return $this->encryptionUtil->isSystemWideMountPoint($mountPoint, $user->getUID());
  105. });
  106. }
  107. /**
  108. * @param Folder $folder
  109. * @return \Generator<File>
  110. */
  111. private function getAllFiles(Folder $folder) {
  112. foreach ($folder->getDirectoryListing() as $child) {
  113. if ($child instanceof Folder) {
  114. yield from $this->getAllFiles($child);
  115. } else {
  116. yield $child;
  117. }
  118. }
  119. }
  120. /**
  121. * Check if the key for a file is stored in the user's keystore and not the system one
  122. *
  123. * @param IUser $user
  124. * @param Node $node
  125. * @return bool
  126. */
  127. private function isKeyStoredForUser(IUser $user, Node $node): bool {
  128. $path = trim(substr($node->getPath(), strlen($user->getUID()) + 1), '/');
  129. $systemKeyPath = $this->keyRootDirectory . '/files_encryption/keys/' . $path . '/';
  130. $userKeyPath = $this->keyRootDirectory . '/' . $user->getUID() . '/files_encryption/keys/' . $path . '/';
  131. // this uses View instead of the RootFolder because the keys might not be in the cache
  132. $systemKeyExists = $this->rootView->file_exists($systemKeyPath);
  133. $userKeyExists = $this->rootView->file_exists($userKeyPath);
  134. return $userKeyExists && !$systemKeyExists;
  135. }
  136. /**
  137. * Check that the user key stored for a file can decrypt the file
  138. *
  139. * @param IUser $user
  140. * @param File $node
  141. * @return bool
  142. */
  143. private function copyKeyAndValidate(IUser $user, File $node): bool {
  144. $path = trim(substr($node->getPath(), strlen($user->getUID()) + 1), '/');
  145. $systemKeyPath = $this->keyRootDirectory . '/files_encryption/keys/' . $path . '/';
  146. $userKeyPath = $this->keyRootDirectory . '/' . $user->getUID() . '/files_encryption/keys/' . $path . '/';
  147. $this->rootView->copy($userKeyPath, $systemKeyPath);
  148. try {
  149. // check that the copied key is valid
  150. $fh = $node->fopen('r');
  151. // read a single chunk
  152. $data = fread($fh, 8192);
  153. if ($data === false) {
  154. throw new \Exception("Read failed");
  155. }
  156. // cleanup wrong key location
  157. $this->rootView->rmdir($userKeyPath);
  158. return true;
  159. } catch (\Exception $e) {
  160. // remove the copied key if we know it's invalid
  161. $this->rootView->rmdir($systemKeyPath);
  162. return false;
  163. }
  164. }
  165. }