選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

FixEncryptedVersion.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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\ServerNotAvailableException;
  25. use OCA\Encryption\Util;
  26. use OCP\Files\IRootFolder;
  27. use OCP\HintException;
  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. $pathOption = \trim(($input->getOption('path') ?? ''), '/');
  102. if ($pathOption !== "") {
  103. $pathToWalk = "$pathToWalk/$pathOption";
  104. }
  105. if ($user === null) {
  106. $output->writeln("<error>No user id provided.</error>\n");
  107. return 1;
  108. }
  109. if ($this->userManager->get($user) === null) {
  110. $output->writeln("<error>User id $user does not exist. Please provide a valid user id</error>");
  111. return 1;
  112. }
  113. return $this->walkPathOfUser($user, $pathToWalk, $output);
  114. }
  115. /**
  116. * @param string $user
  117. * @param string $path
  118. * @param OutputInterface $output
  119. * @return int 0 for success, 1 for error
  120. */
  121. private function walkPathOfUser($user, $path, OutputInterface $output): int {
  122. $this->setupUserFs($user);
  123. if (!$this->view->file_exists($path)) {
  124. $output->writeln("<error>Path \"$path\" does not exist. Please provide a valid path.</error>");
  125. return 1;
  126. }
  127. if ($this->view->is_file($path)) {
  128. $output->writeln("Verifying the content of file \"$path\"");
  129. $this->verifyFileContent($path, $output);
  130. return 0;
  131. }
  132. $directories = [];
  133. $directories[] = $path;
  134. while ($root = \array_pop($directories)) {
  135. $directoryContent = $this->view->getDirectoryContent($root);
  136. foreach ($directoryContent as $file) {
  137. $path = $root . '/' . $file['name'];
  138. if ($this->view->is_dir($path)) {
  139. $directories[] = $path;
  140. } else {
  141. $output->writeln("Verifying the content of file \"$path\"");
  142. $this->verifyFileContent($path, $output);
  143. }
  144. }
  145. }
  146. return 0;
  147. }
  148. /**
  149. * @param string $path
  150. * @param OutputInterface $output
  151. * @param bool $ignoreCorrectEncVersionCall, setting this variable to false avoids recursion
  152. */
  153. private function verifyFileContent($path, OutputInterface $output, $ignoreCorrectEncVersionCall = true): bool {
  154. try {
  155. /**
  156. * In encryption, the files are read in a block size of 8192 bytes
  157. * Read block size of 8192 and a bit more (808 bytes)
  158. * If there is any problem, the first block should throw the signature
  159. * mismatch error. Which as of now, is enough to proceed ahead to
  160. * correct the encrypted version.
  161. */
  162. $handle = $this->view->fopen($path, 'rb');
  163. if (\fread($handle, 9001) !== false) {
  164. $output->writeln("<info>The file \"$path\" is: OK</info>");
  165. }
  166. \fclose($handle);
  167. return true;
  168. } catch (ServerNotAvailableException $e) {
  169. // not a "bad signature" error and likely "legacy cipher" exception
  170. // this could mean that the file is maybe not encrypted but the encrypted version is set
  171. if (!$this->supportLegacy && $ignoreCorrectEncVersionCall === true) {
  172. $output->writeln("<info>Attempting to fix the path: \"$path\"</info>");
  173. return $this->correctEncryptedVersion($path, $output, true);
  174. }
  175. return false;
  176. } catch (HintException $e) {
  177. $this->logger->warning("Issue: " . $e->getMessage());
  178. //If allowOnce is set to false, this becomes recursive.
  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. }
  187. /**
  188. * @param string $path
  189. * @param OutputInterface $output
  190. * @param bool $includeZero whether to try zero version for unencrypted file
  191. * @return bool
  192. */
  193. private function correctEncryptedVersion($path, OutputInterface $output, bool $includeZero = false): bool {
  194. $fileInfo = $this->view->getFileInfo($path);
  195. if (!$fileInfo) {
  196. $output->writeln("<warning>File info not found for file: \"$path\"</warning>");
  197. return true;
  198. }
  199. $fileId = $fileInfo->getId();
  200. $encryptedVersion = $fileInfo->getEncryptedVersion();
  201. $wrongEncryptedVersion = $encryptedVersion;
  202. $storage = $fileInfo->getStorage();
  203. $cache = $storage->getCache();
  204. $fileCache = $cache->get($fileId);
  205. if (!$fileCache) {
  206. $output->writeln("<warning>File cache entry not found for file: \"$path\"</warning>");
  207. return true;
  208. }
  209. if ($storage->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
  210. $output->writeln("<info>The file: \"$path\" is a share. Please also run the script for the owner of the share</info>");
  211. return true;
  212. }
  213. // Save original encrypted version so we can restore it if decryption fails with all version
  214. $originalEncryptedVersion = $encryptedVersion;
  215. if ($encryptedVersion >= 0) {
  216. if ($includeZero) {
  217. // try with zero first
  218. $cacheInfo = ['encryptedVersion' => 0, 'encrypted' => 0];
  219. $cache->put($fileCache->getPath(), $cacheInfo);
  220. $output->writeln("<info>Set the encrypted version to 0 (unencrypted)</info>");
  221. if ($this->verifyFileContent($path, $output, false) === true) {
  222. $output->writeln("<info>Fixed the file: \"$path\" with version 0 (unencrypted)</info>");
  223. return true;
  224. }
  225. }
  226. //test by decrementing the value till 1 and if nothing works try incrementing
  227. $encryptedVersion--;
  228. while ($encryptedVersion > 0) {
  229. $cacheInfo = ['encryptedVersion' => $encryptedVersion, 'encrypted' => $encryptedVersion];
  230. $cache->put($fileCache->getPath(), $cacheInfo);
  231. $output->writeln("<info>Decrement the encrypted version to $encryptedVersion</info>");
  232. if ($this->verifyFileContent($path, $output, false) === true) {
  233. $output->writeln("<info>Fixed the file: \"$path\" with version " . $encryptedVersion . "</info>");
  234. return true;
  235. }
  236. $encryptedVersion--;
  237. }
  238. //So decrementing did not work. Now lets increment. Max increment is till 5
  239. $increment = 1;
  240. while ($increment <= 5) {
  241. /**
  242. * The wrongEncryptedVersion would not be incremented so nothing to worry about here.
  243. * Only the newEncryptedVersion is incremented.
  244. * For example if the wrong encrypted version is 4 then
  245. * cycle1 -> newEncryptedVersion = 5 ( 4 + 1)
  246. * cycle2 -> newEncryptedVersion = 6 ( 4 + 2)
  247. * cycle3 -> newEncryptedVersion = 7 ( 4 + 3)
  248. */
  249. $newEncryptedVersion = $wrongEncryptedVersion + $increment;
  250. $cacheInfo = ['encryptedVersion' => $newEncryptedVersion, 'encrypted' => $newEncryptedVersion];
  251. $cache->put($fileCache->getPath(), $cacheInfo);
  252. $output->writeln("<info>Increment the encrypted version to $newEncryptedVersion</info>");
  253. if ($this->verifyFileContent($path, $output, false) === true) {
  254. $output->writeln("<info>Fixed the file: \"$path\" with version " . $newEncryptedVersion . "</info>");
  255. return true;
  256. }
  257. $increment++;
  258. }
  259. }
  260. $cacheInfo = ['encryptedVersion' => $originalEncryptedVersion, 'encrypted' => $originalEncryptedVersion];
  261. $cache->put($fileCache->getPath(), $cacheInfo);
  262. $output->writeln("<info>No fix found for \"$path\", restored version to original: $originalEncryptedVersion</info>");
  263. return false;
  264. }
  265. /**
  266. * Setup user file system
  267. * @param string $uid
  268. */
  269. private function setupUserFs($uid): void {
  270. \OC_Util::tearDownFS();
  271. \OC_Util::setupFS($uid);
  272. }
  273. }