1
0

FixEncryptedVersion.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2019 ownCloud GmbH
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Encryption\Command;
  8. use OC\Files\Storage\Wrapper\Encryption;
  9. use OC\Files\View;
  10. use OC\ServerNotAvailableException;
  11. use OCA\Encryption\Util;
  12. use OCP\Files\IRootFolder;
  13. use OCP\HintException;
  14. use OCP\IConfig;
  15. use OCP\IUser;
  16. use OCP\IUserManager;
  17. use Psr\Log\LoggerInterface;
  18. use Symfony\Component\Console\Command\Command;
  19. use Symfony\Component\Console\Input\InputArgument;
  20. use Symfony\Component\Console\Input\InputInterface;
  21. use Symfony\Component\Console\Input\InputOption;
  22. use Symfony\Component\Console\Output\OutputInterface;
  23. class FixEncryptedVersion extends Command {
  24. private bool $supportLegacy = false;
  25. public function __construct(
  26. private IConfig $config,
  27. private LoggerInterface $logger,
  28. private IRootFolder $rootFolder,
  29. private IUserManager $userManager,
  30. private Util $util,
  31. private View $view,
  32. ) {
  33. parent::__construct();
  34. }
  35. protected function configure(): void {
  36. parent::configure();
  37. $this
  38. ->setName('encryption:fix-encrypted-version')
  39. ->setDescription('Fix the encrypted version if the encrypted file(s) are not downloadable.')
  40. ->addArgument(
  41. 'user',
  42. InputArgument::OPTIONAL,
  43. 'The id of the user whose files need fixing'
  44. )->addOption(
  45. 'path',
  46. 'p',
  47. InputOption::VALUE_REQUIRED,
  48. 'Limit files to fix with path, e.g., --path="/Music/Artist". If path indicates a directory, all the files inside directory will be fixed.'
  49. )->addOption(
  50. 'all',
  51. null,
  52. InputOption::VALUE_NONE,
  53. 'Run the fix for all users on the system, mutually exclusive with specifying a user id.'
  54. );
  55. }
  56. protected function execute(InputInterface $input, OutputInterface $output): int {
  57. $skipSignatureCheck = $this->config->getSystemValueBool('encryption_skip_signature_check', false);
  58. $this->supportLegacy = $this->config->getSystemValueBool('encryption.legacy_format_support', false);
  59. if ($skipSignatureCheck) {
  60. $output->writeln("<error>Repairing is not possible when \"encryption_skip_signature_check\" is set. Please disable this flag in the configuration.</error>\n");
  61. return self::FAILURE;
  62. }
  63. if (!$this->util->isMasterKeyEnabled()) {
  64. $output->writeln("<error>Repairing only works with master key encryption.</error>\n");
  65. return self::FAILURE;
  66. }
  67. $user = $input->getArgument('user');
  68. $all = $input->getOption('all');
  69. $pathOption = \trim(($input->getOption('path') ?? ''), '/');
  70. if (!$user && !$all) {
  71. $output->writeln('Either a user id or --all needs to be provided');
  72. return self::FAILURE;
  73. }
  74. if ($user) {
  75. if ($all) {
  76. $output->writeln('Specifying a user id and --all are mutually exclusive');
  77. return self::FAILURE;
  78. }
  79. if ($this->userManager->get($user) === null) {
  80. $output->writeln("<error>User id $user does not exist. Please provide a valid user id</error>");
  81. return self::FAILURE;
  82. }
  83. return $this->runForUser($user, $pathOption, $output);
  84. }
  85. $result = 0;
  86. $this->userManager->callForSeenUsers(function (IUser $user) use ($pathOption, $output, &$result) {
  87. $output->writeln('Processing files for ' . $user->getUID());
  88. $result = $this->runForUser($user->getUID(), $pathOption, $output);
  89. return $result === 0;
  90. });
  91. return $result;
  92. }
  93. private function runForUser(string $user, string $pathOption, OutputInterface $output): int {
  94. $pathToWalk = "/$user/files";
  95. if ($pathOption !== '') {
  96. $pathToWalk = "$pathToWalk/$pathOption";
  97. }
  98. return $this->walkPathOfUser($user, $pathToWalk, $output);
  99. }
  100. /**
  101. * @return int 0 for success, 1 for error
  102. */
  103. private function walkPathOfUser(string $user, string $path, OutputInterface $output): int {
  104. $this->setupUserFs($user);
  105. if (!$this->view->file_exists($path)) {
  106. $output->writeln("<error>Path \"$path\" does not exist. Please provide a valid path.</error>");
  107. return self::FAILURE;
  108. }
  109. if ($this->view->is_file($path)) {
  110. $output->writeln("Verifying the content of file \"$path\"");
  111. $this->verifyFileContent($path, $output);
  112. return self::SUCCESS;
  113. }
  114. $directories = [];
  115. $directories[] = $path;
  116. while ($root = \array_pop($directories)) {
  117. $directoryContent = $this->view->getDirectoryContent($root);
  118. foreach ($directoryContent as $file) {
  119. $path = $root . '/' . $file['name'];
  120. if ($this->view->is_dir($path)) {
  121. $directories[] = $path;
  122. } else {
  123. $output->writeln("Verifying the content of file \"$path\"");
  124. $this->verifyFileContent($path, $output);
  125. }
  126. }
  127. }
  128. return self::SUCCESS;
  129. }
  130. /**
  131. * @param bool $ignoreCorrectEncVersionCall, setting this variable to false avoids recursion
  132. */
  133. private function verifyFileContent(string $path, OutputInterface $output, bool $ignoreCorrectEncVersionCall = true): bool {
  134. try {
  135. // since we're manually poking around the encrypted state we need to ensure that this isn't cached in the encryption wrapper
  136. $mount = $this->view->getMount($path);
  137. $storage = $mount->getStorage();
  138. if ($storage && $storage->instanceOfStorage(Encryption::class)) {
  139. $storage->clearIsEncryptedCache();
  140. }
  141. /**
  142. * In encryption, the files are read in a block size of 8192 bytes
  143. * Read block size of 8192 and a bit more (808 bytes)
  144. * If there is any problem, the first block should throw the signature
  145. * mismatch error. Which as of now, is enough to proceed ahead to
  146. * correct the encrypted version.
  147. */
  148. $handle = $this->view->fopen($path, 'rb');
  149. if ($handle === false) {
  150. $output->writeln("<warning>Failed to open file: \"$path\" skipping</warning>");
  151. return true;
  152. }
  153. if (\fread($handle, 9001) !== false) {
  154. $fileInfo = $this->view->getFileInfo($path);
  155. if (!$fileInfo) {
  156. $output->writeln("<warning>File info not found for file: \"$path\"</warning>");
  157. return true;
  158. }
  159. $encryptedVersion = $fileInfo->getEncryptedVersion();
  160. $stat = $this->view->stat($path);
  161. if (($encryptedVersion == 0) && isset($stat['hasHeader']) && ($stat['hasHeader'] == true)) {
  162. // The file has encrypted to false but has an encryption header
  163. if ($ignoreCorrectEncVersionCall === true) {
  164. // Lets rectify the file by correcting encrypted version
  165. $output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
  166. return $this->correctEncryptedVersion($path, $output);
  167. }
  168. return false;
  169. }
  170. $output->writeln("<info>The file \"$path\" is: OK</info>");
  171. }
  172. \fclose($handle);
  173. return true;
  174. } catch (ServerNotAvailableException $e) {
  175. // not a "bad signature" error and likely "legacy cipher" exception
  176. // this could mean that the file is maybe not encrypted but the encrypted version is set
  177. if (!$this->supportLegacy && $ignoreCorrectEncVersionCall === true) {
  178. $output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
  179. return $this->correctEncryptedVersion($path, $output, true);
  180. }
  181. return false;
  182. } catch (HintException $e) {
  183. $this->logger->warning('Issue: ' . $e->getMessage());
  184. // If allowOnce is set to false, this becomes recursive.
  185. if ($ignoreCorrectEncVersionCall === true) {
  186. // Lets rectify the file by correcting encrypted version
  187. $output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
  188. return $this->correctEncryptedVersion($path, $output);
  189. }
  190. return false;
  191. }
  192. }
  193. /**
  194. * @param bool $includeZero whether to try zero version for unencrypted file
  195. */
  196. private function correctEncryptedVersion(string $path, OutputInterface $output, bool $includeZero = false): bool {
  197. $fileInfo = $this->view->getFileInfo($path);
  198. if (!$fileInfo) {
  199. $output->writeln("<warning>File info not found for file: \"$path\"</warning>");
  200. return true;
  201. }
  202. $fileId = $fileInfo->getId();
  203. if ($fileId === null) {
  204. $output->writeln("<warning>File info contains no id for file: \"$path\"</warning>");
  205. return true;
  206. }
  207. $encryptedVersion = $fileInfo->getEncryptedVersion();
  208. $wrongEncryptedVersion = $encryptedVersion;
  209. $storage = $fileInfo->getStorage();
  210. $cache = $storage->getCache();
  211. $fileCache = $cache->get($fileId);
  212. if (!$fileCache) {
  213. $output->writeln("<warning>File cache entry not found for file: \"$path\"</warning>");
  214. return true;
  215. }
  216. if ($storage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
  217. $output->writeln("<info>The file: \"$path\" is a share. Please also run the script for the owner of the share</info>");
  218. return true;
  219. }
  220. // Save original encrypted version so we can restore it if decryption fails with all version
  221. $originalEncryptedVersion = $encryptedVersion;
  222. if ($encryptedVersion >= 0) {
  223. if ($includeZero) {
  224. // try with zero first
  225. $cacheInfo = ['encryptedVersion' => 0, 'encrypted' => 0];
  226. $cache->put($fileCache->getPath(), $cacheInfo);
  227. $output->writeln('<info>Set the encrypted version to 0 (unencrypted)</info>');
  228. if ($this->verifyFileContent($path, $output, false) === true) {
  229. $output->writeln("<info>Fixed the file: \"$path\" with version 0 (unencrypted)</info>");
  230. return true;
  231. }
  232. }
  233. // Test by decrementing the value till 1 and if nothing works try incrementing
  234. $encryptedVersion--;
  235. while ($encryptedVersion > 0) {
  236. $cacheInfo = ['encryptedVersion' => $encryptedVersion, 'encrypted' => $encryptedVersion];
  237. $cache->put($fileCache->getPath(), $cacheInfo);
  238. $output->writeln("<info>Decrement the encrypted version to $encryptedVersion</info>");
  239. if ($this->verifyFileContent($path, $output, false) === true) {
  240. $output->writeln("<info>Fixed the file: \"$path\" with version " . $encryptedVersion . '</info>');
  241. return true;
  242. }
  243. $encryptedVersion--;
  244. }
  245. // So decrementing did not work. Now lets increment. Max increment is till 5
  246. $increment = 1;
  247. while ($increment <= 5) {
  248. /**
  249. * The wrongEncryptedVersion would not be incremented so nothing to worry about here.
  250. * Only the newEncryptedVersion is incremented.
  251. * For example if the wrong encrypted version is 4 then
  252. * cycle1 -> newEncryptedVersion = 5 ( 4 + 1)
  253. * cycle2 -> newEncryptedVersion = 6 ( 4 + 2)
  254. * cycle3 -> newEncryptedVersion = 7 ( 4 + 3)
  255. */
  256. $newEncryptedVersion = $wrongEncryptedVersion + $increment;
  257. $cacheInfo = ['encryptedVersion' => $newEncryptedVersion, 'encrypted' => $newEncryptedVersion];
  258. $cache->put($fileCache->getPath(), $cacheInfo);
  259. $output->writeln("<info>Increment the encrypted version to $newEncryptedVersion</info>");
  260. if ($this->verifyFileContent($path, $output, false) === true) {
  261. $output->writeln("<info>Fixed the file: \"$path\" with version " . $newEncryptedVersion . '</info>');
  262. return true;
  263. }
  264. $increment++;
  265. }
  266. }
  267. $cacheInfo = ['encryptedVersion' => $originalEncryptedVersion, 'encrypted' => $originalEncryptedVersion];
  268. $cache->put($fileCache->getPath(), $cacheInfo);
  269. $output->writeln("<info>No fix found for \"$path\", restored version to original: $originalEncryptedVersion</info>");
  270. return false;
  271. }
  272. /**
  273. * Setup user file system
  274. */
  275. private function setupUserFs(string $uid): void {
  276. \OC_Util::tearDownFS();
  277. \OC_Util::setupFS($uid);
  278. }
  279. }