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