FixKeyLocation.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2022 Robin Appelman <robin@icewind.nl>
  5. *
  6. * @license GNU AGPL version 3 or any later version
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  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
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. namespace OCA\Encryption\Command;
  23. use OC\Encryption\Manager;
  24. use OC\Encryption\Util;
  25. use OC\Files\Storage\Wrapper\Encryption;
  26. use OC\Files\View;
  27. use OCP\Encryption\IManager;
  28. use OCP\Files\Config\ICachedMountInfo;
  29. use OCP\Files\Config\IUserMountCache;
  30. use OCP\Files\File;
  31. use OCP\Files\Folder;
  32. use OCP\Files\IRootFolder;
  33. use OCP\Files\Node;
  34. use OCP\IUser;
  35. use OCP\IUserManager;
  36. use Symfony\Component\Console\Command\Command;
  37. use Symfony\Component\Console\Input\InputArgument;
  38. use Symfony\Component\Console\Input\InputInterface;
  39. use Symfony\Component\Console\Input\InputOption;
  40. use Symfony\Component\Console\Output\OutputInterface;
  41. class FixKeyLocation extends Command {
  42. private IUserManager $userManager;
  43. private IUserMountCache $userMountCache;
  44. private Util $encryptionUtil;
  45. private IRootFolder $rootFolder;
  46. private string $keyRootDirectory;
  47. private View $rootView;
  48. private Manager $encryptionManager;
  49. public function __construct(
  50. IUserManager $userManager,
  51. IUserMountCache $userMountCache,
  52. Util $encryptionUtil,
  53. IRootFolder $rootFolder,
  54. IManager $encryptionManager
  55. ) {
  56. $this->userManager = $userManager;
  57. $this->userMountCache = $userMountCache;
  58. $this->encryptionUtil = $encryptionUtil;
  59. $this->rootFolder = $rootFolder;
  60. $this->keyRootDirectory = rtrim($this->encryptionUtil->getKeyStorageRoot(), '/');
  61. $this->rootView = new View();
  62. if (!$encryptionManager instanceof Manager) {
  63. throw new \Exception("Wrong encryption manager");
  64. }
  65. $this->encryptionManager = $encryptionManager;
  66. parent::__construct();
  67. }
  68. protected function configure(): void {
  69. parent::configure();
  70. $this
  71. ->setName('encryption:fix-key-location')
  72. ->setDescription('Fix the location of encryption keys for external storage')
  73. ->addOption('dry-run', null, InputOption::VALUE_NONE, "Only list files that require key migration, don't try to perform any migration")
  74. ->addArgument('user', InputArgument::REQUIRED, "User id to fix the key locations for");
  75. }
  76. protected function execute(InputInterface $input, OutputInterface $output): int {
  77. $dryRun = $input->getOption('dry-run');
  78. $userId = $input->getArgument('user');
  79. $user = $this->userManager->get($userId);
  80. if (!$user) {
  81. $output->writeln("<error>User $userId not found</error>");
  82. return 1;
  83. }
  84. \OC_Util::setupFS($user->getUID());
  85. $mounts = $this->getSystemMountsForUser($user);
  86. foreach ($mounts as $mount) {
  87. $mountRootFolder = $this->rootFolder->get($mount->getMountPoint());
  88. if (!$mountRootFolder instanceof Folder) {
  89. $output->writeln("<error>System wide mount point is not a directory, skipping: " . $mount->getMountPoint() . "</error>");
  90. continue;
  91. }
  92. $files = $this->getAllEncryptedFiles($mountRootFolder);
  93. foreach ($files as $file) {
  94. /** @var File $file */
  95. $hasSystemKey = $this->hasSystemKey($file);
  96. $hasUserKey = $this->hasUserKey($user, $file);
  97. if (!$hasSystemKey) {
  98. if ($hasUserKey) {
  99. // key was stored incorrectly as user key, migrate
  100. if ($dryRun) {
  101. $output->writeln("<info>" . $file->getPath() . "</info> needs migration");
  102. } else {
  103. $output->write("Migrating key for <info>" . $file->getPath() . "</info> ");
  104. if ($this->copyUserKeyToSystemAndValidate($user, $file)) {
  105. $output->writeln("<info>✓</info>");
  106. } else {
  107. $output->writeln("<fg=red>❌</>");
  108. $output->writeln(" Failed to validate key for <error>" . $file->getPath() . "</error>, key will not be migrated");
  109. }
  110. }
  111. } else {
  112. // no matching key, probably from a broken cross-storage move
  113. $shouldBeEncrypted = $file->getStorage()->instanceOfStorage(Encryption::class);
  114. $isActuallyEncrypted = $this->isDataEncrypted($file);
  115. if ($isActuallyEncrypted) {
  116. if ($dryRun) {
  117. if ($shouldBeEncrypted) {
  118. $output->write("<info>" . $file->getPath() . "</info> needs migration");
  119. } else {
  120. $output->write("<info>" . $file->getPath() . "</info> needs decryption");
  121. }
  122. $foundKey = $this->findUserKeyForSystemFile($user, $file);
  123. if ($foundKey) {
  124. $output->writeln(", valid key found at <info>" . $foundKey . "</info>");
  125. } else {
  126. $output->writeln(" <error>❌ No key found</error>");
  127. }
  128. } else {
  129. if ($shouldBeEncrypted) {
  130. $output->write("<info>Migrating key for " . $file->getPath() . "</info>");
  131. } else {
  132. $output->write("<info>Decrypting " . $file->getPath() . "</info>");
  133. }
  134. $foundKey = $this->findUserKeyForSystemFile($user, $file);
  135. if ($foundKey) {
  136. if ($shouldBeEncrypted) {
  137. $systemKeyPath = $this->getSystemKeyPath($file);
  138. $this->rootView->copy($foundKey, $systemKeyPath);
  139. $output->writeln(" Migrated key from <info>" . $foundKey . "</info>");
  140. } else {
  141. $this->decryptWithSystemKey($file, $foundKey);
  142. $output->writeln(" Decrypted with key from <info>" . $foundKey . "</info>");
  143. }
  144. } else {
  145. $output->writeln(" <error>❌ No key found</error>");
  146. }
  147. }
  148. } else {
  149. if ($dryRun) {
  150. $output->writeln("<info>" . $file->getPath() . " needs to be marked as not encrypted</info>");
  151. } else {
  152. $this->markAsUnEncrypted($file);
  153. $output->writeln("<info>" . $file->getPath() . " marked as not encrypted</info>");
  154. }
  155. }
  156. }
  157. }
  158. }
  159. }
  160. return 0;
  161. }
  162. private function getUserRelativePath(string $path): string {
  163. $parts = explode('/', $path, 3);
  164. if (count($parts) >= 3) {
  165. return '/' . $parts[2];
  166. } else {
  167. return '';
  168. }
  169. }
  170. /**
  171. * @param IUser $user
  172. * @return ICachedMountInfo[]
  173. */
  174. private function getSystemMountsForUser(IUser $user): array {
  175. return array_filter($this->userMountCache->getMountsForUser($user), function (ICachedMountInfo $mount) use (
  176. $user
  177. ) {
  178. $mountPoint = substr($mount->getMountPoint(), strlen($user->getUID() . '/'));
  179. return $this->encryptionUtil->isSystemWideMountPoint($mountPoint, $user->getUID());
  180. });
  181. }
  182. /**
  183. * Get all files in a folder which are marked as encrypted
  184. *
  185. * @param Folder $folder
  186. * @return \Generator<File>
  187. */
  188. private function getAllEncryptedFiles(Folder $folder) {
  189. foreach ($folder->getDirectoryListing() as $child) {
  190. if ($child instanceof Folder) {
  191. yield from $this->getAllEncryptedFiles($child);
  192. } else {
  193. if (substr($child->getName(), -4) !== '.bak' && $child->isEncrypted()) {
  194. yield $child;
  195. }
  196. }
  197. }
  198. }
  199. private function getSystemKeyPath(Node $node): string {
  200. $path = $this->getUserRelativePath($node->getPath());
  201. return $this->keyRootDirectory . '/files_encryption/keys/' . $path . '/';
  202. }
  203. private function getUserBaseKeyPath(IUser $user): string {
  204. return $this->keyRootDirectory . '/' . $user->getUID() . '/files_encryption/keys';
  205. }
  206. private function getUserKeyPath(IUser $user, Node $node): string {
  207. $path = $this->getUserRelativePath($node->getPath());
  208. return $this->getUserBaseKeyPath($user) . '/' . $path . '/';
  209. }
  210. private function hasSystemKey(Node $node): bool {
  211. // this uses View instead of the RootFolder because the keys might not be in the cache
  212. return $this->rootView->file_exists($this->getSystemKeyPath($node));
  213. }
  214. private function hasUserKey(IUser $user, Node $node): bool {
  215. // this uses View instead of the RootFolder because the keys might not be in the cache
  216. return $this->rootView->file_exists($this->getUserKeyPath($user, $node));
  217. }
  218. /**
  219. * Check that the user key stored for a file can decrypt the file
  220. *
  221. * @param IUser $user
  222. * @param File $node
  223. * @return bool
  224. */
  225. private function copyUserKeyToSystemAndValidate(IUser $user, File $node): bool {
  226. $path = trim(substr($node->getPath(), strlen($user->getUID()) + 1), '/');
  227. $systemKeyPath = $this->keyRootDirectory . '/files_encryption/keys/' . $path . '/';
  228. $userKeyPath = $this->keyRootDirectory . '/' . $user->getUID() . '/files_encryption/keys/' . $path . '/';
  229. $this->rootView->copy($userKeyPath, $systemKeyPath);
  230. if ($this->tryReadFile($node)) {
  231. // cleanup wrong key location
  232. $this->rootView->rmdir($userKeyPath);
  233. return true;
  234. } else {
  235. // remove the copied key if we know it's invalid
  236. $this->rootView->rmdir($systemKeyPath);
  237. return false;
  238. }
  239. }
  240. private function tryReadFile(File $node): bool {
  241. try {
  242. $fh = $node->fopen('r');
  243. // read a single chunk
  244. $data = fread($fh, 8192);
  245. if ($data === false) {
  246. return false;
  247. } else {
  248. return true;
  249. }
  250. } catch (\Exception $e) {
  251. return false;
  252. }
  253. }
  254. /**
  255. * Get the contents of a file without decrypting it
  256. *
  257. * @param File $node
  258. * @return resource
  259. */
  260. private function openWithoutDecryption(File $node, string $mode) {
  261. $storage = $node->getStorage();
  262. $internalPath = $node->getInternalPath();
  263. if ($storage->instanceOfStorage(Encryption::class)) {
  264. /** @var Encryption $storage */
  265. try {
  266. $storage->setEnabled(false);
  267. $handle = $storage->fopen($internalPath, 'r');
  268. $storage->setEnabled(true);
  269. } catch (\Exception $e) {
  270. $storage->setEnabled(true);
  271. throw $e;
  272. }
  273. } else {
  274. $handle = $storage->fopen($internalPath, $mode);
  275. }
  276. /** @var resource|false $handle */
  277. if ($handle === false) {
  278. throw new \Exception("Failed to open " . $node->getPath());
  279. }
  280. return $handle;
  281. }
  282. /**
  283. * Check if the data stored for a file is encrypted, regardless of it's metadata
  284. *
  285. * @param File $node
  286. * @return bool
  287. */
  288. private function isDataEncrypted(File $node): bool {
  289. $handle = $this->openWithoutDecryption($node, 'r');
  290. $firstBlock = fread($handle, $this->encryptionUtil->getHeaderSize());
  291. fclose($handle);
  292. $header = $this->encryptionUtil->parseRawHeader($firstBlock);
  293. return isset($header['oc_encryption_module']);
  294. }
  295. /**
  296. * Attempt to find a key (stored for user) for a file (that needs a system key) even when it's not stored in the expected location
  297. *
  298. * @param File $node
  299. * @return string
  300. */
  301. private function findUserKeyForSystemFile(IUser $user, File $node): ?string {
  302. $userKeyPath = $this->getUserBaseKeyPath($user);
  303. $possibleKeys = $this->findKeysByFileName($userKeyPath, $node->getName());
  304. foreach ($possibleKeys as $possibleKey) {
  305. if ($this->testSystemKey($user, $possibleKey, $node)) {
  306. return $possibleKey;
  307. }
  308. }
  309. return null;
  310. }
  311. /**
  312. * Attempt to find a key for a file even when it's not stored in the expected location
  313. *
  314. * @param string $basePath
  315. * @param string $name
  316. * @return \Generator<string>
  317. */
  318. private function findKeysByFileName(string $basePath, string $name) {
  319. if ($this->rootView->is_dir($basePath . '/' . $name . '/OC_DEFAULT_MODULE')) {
  320. yield $basePath . '/' . $name;
  321. } else {
  322. /** @var false|resource $dh */
  323. $dh = $this->rootView->opendir($basePath);
  324. if (!$dh) {
  325. throw new \Exception("Invalid base path " . $basePath);
  326. }
  327. while ($child = readdir($dh)) {
  328. if ($child != '..' && $child != '.') {
  329. $childPath = $basePath . '/' . $child;
  330. // recurse if the child is not a key folder
  331. if ($this->rootView->is_dir($childPath) && !is_dir($childPath . '/OC_DEFAULT_MODULE')) {
  332. yield from $this->findKeysByFileName($childPath, $name);
  333. }
  334. }
  335. }
  336. }
  337. }
  338. /**
  339. * Test if the provided key is valid as a system key for the file
  340. *
  341. * @param IUser $user
  342. * @param string $key
  343. * @param File $node
  344. * @return bool
  345. */
  346. private function testSystemKey(IUser $user, string $key, File $node): bool {
  347. $systemKeyPath = $this->getSystemKeyPath($node);
  348. if ($this->rootView->file_exists($systemKeyPath)) {
  349. // already has a key, reject new key
  350. return false;
  351. }
  352. $this->rootView->copy($key, $systemKeyPath);
  353. $isValid = $this->tryReadFile($node);
  354. $this->rootView->rmdir($systemKeyPath);
  355. return $isValid;
  356. }
  357. /**
  358. * Decrypt a file with the specified system key and mark the key as not-encrypted
  359. *
  360. * @param File $node
  361. * @param string $key
  362. * @return void
  363. */
  364. private function decryptWithSystemKey(File $node, string $key): void {
  365. $storage = $node->getStorage();
  366. $name = $node->getName();
  367. $node->move($node->getPath() . '.bak');
  368. $systemKeyPath = $this->getSystemKeyPath($node);
  369. $this->rootView->copy($key, $systemKeyPath);
  370. try {
  371. if (!$storage->instanceOfStorage(Encryption::class)) {
  372. $storage = $this->encryptionManager->forceWrapStorage($node->getMountPoint(), $storage);
  373. }
  374. /** @var false|resource $source */
  375. $source = $storage->fopen($node->getInternalPath(), 'r');
  376. if (!$source) {
  377. throw new \Exception("Failed to open " . $node->getPath() . " with " . $key);
  378. }
  379. $decryptedNode = $node->getParent()->newFile($name);
  380. $target = $this->openWithoutDecryption($decryptedNode, 'w');
  381. stream_copy_to_stream($source, $target);
  382. fclose($target);
  383. fclose($source);
  384. $decryptedNode->getStorage()->getScanner()->scan($decryptedNode->getInternalPath());
  385. } catch (\Exception $e) {
  386. $this->rootView->rmdir($systemKeyPath);
  387. // remove the .bak
  388. $node->move(substr($node->getPath(), 0, -4));
  389. throw $e;
  390. }
  391. if ($this->isDataEncrypted($decryptedNode)) {
  392. throw new \Exception($node->getPath() . " still encrypted after attempting to decrypt with " . $key);
  393. }
  394. $this->markAsUnEncrypted($decryptedNode);
  395. $this->rootView->rmdir($systemKeyPath);
  396. }
  397. private function markAsUnEncrypted(Node $node): void {
  398. $node->getStorage()->getCache()->update($node->getId(), ['encrypted' => 0]);
  399. }
  400. }