Skip to content

Commit 4fced6d

Browse files
authored
Merge pull request #35826 from nextcloud/backport/35107/stable22
[stable22] add migration for encryption keys in wrong location
2 parents dfc6cf1 + ce73967 commit 4fced6d

File tree

4 files changed

+195
-0
lines changed

4 files changed

+195
-0
lines changed

apps/encryption/appinfo/info.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
<command>OCA\Encryption\Command\RecoverUser</command>
4747
<command>OCA\Encryption\Command\ScanLegacyFormat</command>
4848
<command>OCA\Encryption\Command\FixEncryptedVersion</command>
49+
<command>OCA\Encryption\Command\FixKeyLocation</command>
4950
</commands>
5051

5152
<settings>

apps/encryption/composer/composer/autoload_classmap.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
'OCA\\Encryption\\Command\\DisableMasterKey' => $baseDir . '/../lib/Command/DisableMasterKey.php',
1212
'OCA\\Encryption\\Command\\EnableMasterKey' => $baseDir . '/../lib/Command/EnableMasterKey.php',
1313
'OCA\\Encryption\\Command\\FixEncryptedVersion' => $baseDir . '/../lib/Command/FixEncryptedVersion.php',
14+
'OCA\\Encryption\\Command\\FixKeyLocation' => $baseDir . '/../lib/Command/FixKeyLocation.php',
1415
'OCA\\Encryption\\Command\\RecoverUser' => $baseDir . '/../lib/Command/RecoverUser.php',
1516
'OCA\\Encryption\\Command\\ScanLegacyFormat' => $baseDir . '/../lib/Command/ScanLegacyFormat.php',
1617
'OCA\\Encryption\\Controller\\RecoveryController' => $baseDir . '/../lib/Controller/RecoveryController.php',

apps/encryption/composer/composer/autoload_static.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class ComposerStaticInitEncryption
2626
'OCA\\Encryption\\Command\\DisableMasterKey' => __DIR__ . '/..' . '/../lib/Command/DisableMasterKey.php',
2727
'OCA\\Encryption\\Command\\EnableMasterKey' => __DIR__ . '/..' . '/../lib/Command/EnableMasterKey.php',
2828
'OCA\\Encryption\\Command\\FixEncryptedVersion' => __DIR__ . '/..' . '/../lib/Command/FixEncryptedVersion.php',
29+
'OCA\\Encryption\\Command\\FixKeyLocation' => __DIR__ . '/..' . '/../lib/Command/FixKeyLocation.php',
2930
'OCA\\Encryption\\Command\\RecoverUser' => __DIR__ . '/..' . '/../lib/Command/RecoverUser.php',
3031
'OCA\\Encryption\\Command\\ScanLegacyFormat' => __DIR__ . '/..' . '/../lib/Command/ScanLegacyFormat.php',
3132
'OCA\\Encryption\\Controller\\RecoveryController' => __DIR__ . '/..' . '/../lib/Controller/RecoveryController.php',
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
/**
5+
* @copyright Copyright (c) 2022 Robin Appelman <robin@icewind.nl>
6+
*
7+
* @license GNU AGPL version 3 or any later version
8+
*
9+
* This program is free software: you can redistribute it and/or modify
10+
* it under the terms of the GNU Affero General Public License as
11+
* published by the Free Software Foundation, either version 3 of the
12+
* License, or (at your option) any later version.
13+
*
14+
* This program is distributed in the hope that it will be useful,
15+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
16+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17+
* GNU Affero General Public License for more details.
18+
*
19+
* You should have received a copy of the GNU Affero General Public License
20+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
21+
*
22+
*/
23+
24+
namespace OCA\Encryption\Command;
25+
26+
use OC\Encryption\Util;
27+
use OC\Files\View;
28+
use OCP\Files\Config\ICachedMountInfo;
29+
use OCP\Files\Config\IUserMountCache;
30+
use OCP\Files\Folder;
31+
use OCP\Files\File;
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+
42+
class FixKeyLocation extends Command {
43+
/** @var IUserManager */
44+
private $userManager;
45+
/** @var IUserMountCache */
46+
private $userMountCache;
47+
/** @var Util */
48+
private $encryptionUtil;
49+
/** @var IRootFolder */
50+
private $rootFolder;
51+
/** @var string */
52+
private $keyRootDirectory;
53+
/** @var View */
54+
private $rootView;
55+
56+
public function __construct(IUserManager $userManager, IUserMountCache $userMountCache, Util $encryptionUtil, IRootFolder $rootFolder) {
57+
$this->userManager = $userManager;
58+
$this->userMountCache = $userMountCache;
59+
$this->encryptionUtil = $encryptionUtil;
60+
$this->rootFolder = $rootFolder;
61+
$this->keyRootDirectory = rtrim($this->encryptionUtil->getKeyStorageRoot(), '/');
62+
$this->rootView = new View();
63+
64+
parent::__construct();
65+
}
66+
67+
68+
protected function configure(): void {
69+
parent::configure();
70+
71+
$this
72+
->setName('encryption:fix-key-location')
73+
->setDescription('Fix the location of encryption keys for external storage')
74+
->addOption('dry-run', null, InputOption::VALUE_NONE, "Only list files that require key migration, don't try to perform any migration")
75+
->addArgument('user', InputArgument::REQUIRED, "User id to fix the key locations for");
76+
}
77+
78+
protected function execute(InputInterface $input, OutputInterface $output): int {
79+
$dryRun = $input->getOption('dry-run');
80+
$userId = $input->getArgument('user');
81+
$user = $this->userManager->get($userId);
82+
if (!$user) {
83+
$output->writeln("<error>User $userId not found</error>");
84+
return 1;
85+
}
86+
87+
\OC_Util::setupFS($user->getUID());
88+
89+
$mounts = $this->getSystemMountsForUser($user);
90+
foreach ($mounts as $mount) {
91+
$mountRootFolder = $this->rootFolder->get($mount->getMountPoint());
92+
if (!$mountRootFolder instanceof Folder) {
93+
$output->writeln("<error>System wide mount point is not a directory, skipping: " . $mount->getMountPoint() . "</error>");
94+
continue;
95+
}
96+
97+
$files = $this->getAllFiles($mountRootFolder);
98+
foreach ($files as $file) {
99+
if ($this->isKeyStoredForUser($user, $file)) {
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->copyKeyAndValidate($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+
}
112+
}
113+
}
114+
115+
return 0;
116+
}
117+
118+
/**
119+
* @param IUser $user
120+
* @return ICachedMountInfo[]
121+
*/
122+
private function getSystemMountsForUser(IUser $user): array {
123+
return array_filter($this->userMountCache->getMountsForUser($user), function(ICachedMountInfo $mount) use ($user) {
124+
$mountPoint = substr($mount->getMountPoint(), strlen($user->getUID() . '/'));
125+
return $this->encryptionUtil->isSystemWideMountPoint($mountPoint, $user->getUID());
126+
});
127+
}
128+
129+
/**
130+
* @param Folder $folder
131+
* @return \Generator<File>
132+
*/
133+
private function getAllFiles(Folder $folder) {
134+
foreach ($folder->getDirectoryListing() as $child) {
135+
if ($child instanceof Folder) {
136+
yield from $this->getAllFiles($child);
137+
} else {
138+
yield $child;
139+
}
140+
}
141+
}
142+
143+
/**
144+
* Check if the key for a file is stored in the user's keystore and not the system one
145+
*
146+
* @param IUser $user
147+
* @param Node $node
148+
* @return bool
149+
*/
150+
private function isKeyStoredForUser(IUser $user, Node $node): bool {
151+
$path = trim(substr($node->getPath(), strlen($user->getUID()) + 1), '/');
152+
$systemKeyPath = $this->keyRootDirectory . '/files_encryption/keys/' . $path . '/';
153+
$userKeyPath = $this->keyRootDirectory . '/' . $user->getUID() . '/files_encryption/keys/' . $path . '/';
154+
155+
// this uses View instead of the RootFolder because the keys might not be in the cache
156+
$systemKeyExists = $this->rootView->file_exists($systemKeyPath);
157+
$userKeyExists = $this->rootView->file_exists($userKeyPath);
158+
return $userKeyExists && !$systemKeyExists;
159+
}
160+
161+
/**
162+
* Check that the user key stored for a file can decrypt the file
163+
*
164+
* @param IUser $user
165+
* @param File $node
166+
* @return bool
167+
*/
168+
private function copyKeyAndValidate(IUser $user, File $node): bool {
169+
$path = trim(substr($node->getPath(), strlen($user->getUID()) + 1), '/');
170+
$systemKeyPath = $this->keyRootDirectory . '/files_encryption/keys/' . $path . '/';
171+
$userKeyPath = $this->keyRootDirectory . '/' . $user->getUID() . '/files_encryption/keys/' . $path . '/';
172+
173+
$this->rootView->copy($userKeyPath, $systemKeyPath);
174+
try {
175+
// check that the copied key is valid
176+
$fh = $node->fopen('r');
177+
// read a single chunk
178+
$data = fread($fh, 8192);
179+
if ($data === false) {
180+
throw new \Exception("Read failed");
181+
}
182+
183+
// cleanup wrong key location
184+
$this->rootView->rmdir($userKeyPath);
185+
return true;
186+
} catch (\Exception $e) {
187+
// remove the copied key if we know it's invalid
188+
$this->rootView->rmdir($systemKeyPath);
189+
return false;
190+
}
191+
}
192+
}

0 commit comments

Comments
 (0)