-
-
Notifications
You must be signed in to change notification settings - Fork 5k
Expand file tree
/
Copy pathCleanOrphanedKeys.php
More file actions
223 lines (205 loc) · 7.3 KB
/
Copy pathCleanOrphanedKeys.php
File metadata and controls
223 lines (205 loc) · 7.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Encryption\Command;
use OC\Encryption\Util;
use OCA\Encryption\Crypto\Encryption;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\Files\IRootFolder;
use OCP\Files\ISetupManager;
use OCP\Files\NotFoundException;
use OCP\IConfig;
use OCP\IUser;
use OCP\IUserManager;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
class CleanOrphanedKeys extends Command {
public function __construct(
protected IConfig $config,
protected QuestionHelper $questionHelper,
private IUserManager $userManager,
private Util $encryptionUtil,
private ISetupManager $setupManager,
private IRootFolder $rootFolder,
private LoggerInterface $logger,
) {
parent::__construct();
}
#[\Override]
protected function configure(): void {
$this
->setName('encryption:clean-orphaned-keys')
->setDescription('Scan the keys storage for orphaned keys and remove them')
->addArgument(
'user',
InputArgument::OPTIONAL,
'The id of the user for whom the scan should be performed. If not provided, all users will be scanned.'
);
}
#[\Override]
protected function execute(InputInterface $input, OutputInterface $output): int {
$users = [];
$userId = $input->getArgument('user');
if ($userId !== null) {
$user = $this->userManager->get($userId);
if (!$user) {
$output->writeln("<error>User $userId not found</error>");
return self::FAILURE;
}
$users[] = $user;
} else {
$users = $this->userManager->getSeenUsers();
}
$orphanedKeys = [];
$headline = 'Scanning all keys for file parity';
$output->writeln($headline);
$output->writeln(str_pad('', strlen($headline), '='));
$output->writeln("\n");
$progress = new ProgressBar($output);
$progress->setFormat(" %message% \n [%bar%]");
foreach ($users as $user) {
$uid = $user->getUID();
$progress->setMessage('Scanning all keys for: ' . $uid);
$progress->advance();
$this->setupUserFileSystem($user);
$root = $this->encryptionUtil->getKeyStorageRoot() . '/' . $uid . '/files_encryption/keys';
$userOrphanedKeys = $this->scanFolder($output, $root, $uid);
$orphanedKeys = array_merge($orphanedKeys, $userOrphanedKeys);
$progress->setMessage('Scanned orphaned keys for user: ' . $uid);
}
$progress->finish();
$output->writeln("\n");
foreach ($orphanedKeys as $keyPath) {
$output->writeln('Orphaned key found: ' . $keyPath);
}
if (count($orphanedKeys) == 0) {
return self::SUCCESS;
}
$question = new ConfirmationQuestion('Do you want to delete all orphaned keys? (y/n) ', false);
if ($this->questionHelper->ask($input, $output, $question)) {
$this->deleteAll($orphanedKeys, $output);
} else {
$question = new ConfirmationQuestion('Do you want to delete specific keys? (y/n) ', false);
if ($this->questionHelper->ask($input, $output, $question)) {
$this->deleteSpecific($input, $output, $orphanedKeys);
}
}
return self::SUCCESS;
}
private function scanFolder(OutputInterface $output, string $folderPath, string $user) : array {
$orphanedKeys = [];
try {
$folder = $this->rootFolder->get($folderPath);
} catch (NotFoundException $e) {
// Happens when user doesn't have encrypted files
$this->logger->error('Error when accessing folder ' . $folderPath . ' for user ' . $user, ['exception' => $e]);
return [];
}
if (!($folder instanceof Folder)) {
$this->logger->error('Invalid folder');
return [];
}
foreach ($folder->getDirectoryListing() as $item) {
$path = $folderPath . '/' . $item->getName();
$stopValue = $this->stopCondition($path);
if ($stopValue === null) {
$this->logger->error('Reached unexpected state when scanning user\'s filesystem for orphaned encryption keys' . $path);
} elseif ($stopValue) {
$filePath = str_replace('files_encryption/keys/', '', $path);
try {
$this->rootFolder->get($filePath);
} catch (NotFoundException $e) {
// We found an orphaned key
$orphanedKeys[] = $path;
continue;
}
} else {
$orphanedKeys = array_merge($orphanedKeys, $this->scanFolder($output, $path, $user));
}
}
return $orphanedKeys;
}
/**
* Checks the stop considition for the recursion
* following the logic that keys are stored in files_encryption/keys/<user>/<path>/<fileName>/OC_DEFAULT_MODULE/<key>.sharekey
* @param string $path path of the current folder
* @return bool|null true if we should stop and found a key, false if we should continue, null if we shouldn't end up here
*/
private function stopCondition(string $path) : ?bool {
$folder = $this->rootFolder->get($path);
if ($folder instanceof Folder) {
$content = $folder->getDirectoryListing();
$subfolder = $content[0];
if (count($content) === 1 && $subfolder->getName() === Encryption::ID) {
if ($subfolder instanceof Folder) {
$content = $subfolder->getDirectoryListing();
if (count($content) === 1 && $content[0] instanceof File) {
return strtolower($content[0]->getExtension()) === 'sharekey' ;
}
}
}
return false;
}
// We shouldn't end up here, because we return true when reaching the folder named after the file containing OC_DEFAULT_MODULE
return null;
}
private function deleteAll(array $keys, OutputInterface $output) {
foreach ($keys as $key) {
$file = $this->rootFolder->get($key);
try {
$file->delete();
$output->writeln('Key deleted: ' . $key);
} catch (\Exception $e) {
$output->writeln('Failed to delete ' . $key);
$this->logger->error('Error when deleting orphaned key ' . $key . '. ' . $e->getMessage());
}
}
}
private function deleteSpecific(InputInterface $input, OutputInterface $output, array $orphanedKeys) {
$question = new Question('Please enter path for key to delete: ');
$path = $this->questionHelper->ask($input, $output, $question);
if (!in_array(trim($path), $orphanedKeys)) {
$output->writeln('Wrong key path');
} else {
try {
$this->rootFolder->get(trim($path))->delete();
$output->writeln('Key deleted: ' . $path);
} catch (\Exception $e) {
$output->writeln('Failed to delete ' . $path);
$this->logger->error('Error when deleting orphaned key ' . $path . '. ' . $e->getMessage());
}
$orphanedKeys = array_filter($orphanedKeys, function ($k) use ($path) {
return $k !== trim($path);
});
}
if (count($orphanedKeys) == 0) {
return;
}
$output->writeln('Remaining orphaned keys: ');
foreach ($orphanedKeys as $keyPath) {
$output->writeln($keyPath);
}
$question = new ConfirmationQuestion('Do you want to delete more orphaned keys? (y/n) ', false);
if ($this->questionHelper->ask($input, $output, $question)) {
$this->deleteSpecific($input, $output, $orphanedKeys);
}
}
/**
* setup user file system
*/
protected function setupUserFileSystem(IUser $user): void {
$this->setupManager->tearDown();
$this->setupManager->setupForUser($user);
}
}