1
0

FixEncryptedVersion.php 12 KB

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