1
0

FixEncryptedVersion.php 10 KB

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