1
0

FixEncryptedVersion.php 12 KB

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