aboutsummaryrefslogtreecommitdiffstats
path: root/apps/encryption/lib/Crypto/EncryptAll.php
blob: 310f37aba838a658d6b46f5812e330a07b856576 (plain)
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php

/**
 * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
 * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
 * SPDX-License-Identifier: AGPL-3.0-only
 */
namespace OCA\Encryption\Crypto;

use OC\Encryption\Exceptions\DecryptionFailedException;
use OC\Files\View;
use OCA\Encryption\KeyManager;
use OCA\Encryption\Users\Setup;
use OCA\Encryption\Util;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IUser;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Mail\Headers\AutoSubmitted;
use OCP\Mail\IMailer;
use OCP\Security\ISecureRandom;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class EncryptAll {

	/** @var Setup */
	protected $userSetup;

	/** @var IUserManager */
	protected $userManager;

	/** @var View */
	protected $rootView;

	/** @var KeyManager */
	protected $keyManager;

	/** @var Util */
	protected $util;

	/** @var array */
	protected $userPasswords;

	/** @var IConfig */
	protected $config;

	/** @var IMailer */
	protected $mailer;

	/** @var IL10N */
	protected $l;

	/** @var IFactory */
	protected $l10nFactory;

	/** @var QuestionHelper */
	protected $questionHelper;

	/** @var OutputInterface */
	protected $output;

	/** @var InputInterface */
	protected $input;

	/** @var ISecureRandom */
	protected $secureRandom;

	public function __construct(
		Setup $userSetup,
		IUserManager $userManager,
		View $rootView,
		KeyManager $keyManager,
		Util $util,
		IConfig $config,
		IMailer $mailer,
		IL10N $l,
		IFactory $l10nFactory,
		QuestionHelper $questionHelper,
		ISecureRandom $secureRandom
	) {
		$this->userSetup = $userSetup;
		$this->userManager = $userManager;
		$this->rootView = $rootView;
		$this->keyManager = $keyManager;
		$this->util = $util;
		$this->config = $config;
		$this->mailer = $mailer;
		$this->l = $l;
		$this->l10nFactory = $l10nFactory;
		$this->questionHelper = $questionHelper;
		$this->secureRandom = $secureRandom;
		// store one time passwords for the users
		$this->userPasswords = [];
	}

	/**
	 * start to encrypt all files
	 *
	 * @param InputInterface $input
	 * @param OutputInterface $output
	 */
	public function encryptAll(InputInterface $input, OutputInterface $output) {
		$this->input = $input;
		$this->output = $output;

		$headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
		$this->output->writeln("\n");
		$this->output->writeln($headline);
		$this->output->writeln(str_pad('', strlen($headline), '='));
		$this->output->writeln("\n");

		if ($this->util->isMasterKeyEnabled()) {
			$this->output->writeln('Use master key to encrypt all files.');
			$this->keyManager->validateMasterKey();
		} else {
			//create private/public keys for each user and store the private key password
			$this->output->writeln('Create key-pair for every user');
			$this->output->writeln('------------------------------');
			$this->output->writeln('');
			$this->output->writeln('This module will encrypt all files in the users files folder initially.');
			$this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
			$this->output->writeln('');
			$this->createKeyPairs();
		}


		// output generated encryption key passwords
		if ($this->util->isMasterKeyEnabled() === false) {
			//send-out or display password list and write it to a file
			$this->output->writeln("\n");
			$this->output->writeln('Generated encryption key passwords');
			$this->output->writeln('----------------------------------');
			$this->output->writeln('');
			$this->outputPasswords();
		}

		//setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
		$this->output->writeln("\n");
		$this->output->writeln('Start to encrypt users files');
		$this->output->writeln('----------------------------');
		$this->output->writeln('');
		$this->encryptAllUsersFiles();
		$this->output->writeln("\n");
	}

	/**
	 * create key-pair for every user
	 */
	protected function createKeyPairs() {
		$this->output->writeln("\n");
		$progress = new ProgressBar($this->output);
		$progress->setFormat(" %message% \n [%bar%]");
		$progress->start();

		foreach ($this->userManager->getBackends() as $backend) {
			$limit = 500;
			$offset = 0;
			do {
				$users = $backend->getUsers('', $limit, $offset);
				foreach ($users as $user) {
					if ($this->keyManager->userHasKeys($user) === false) {
						$progress->setMessage('Create key-pair for ' . $user);
						$progress->advance();
						$this->setupUserFS($user);
						$password = $this->generateOneTimePassword($user);
						$this->userSetup->setupUser($user, $password);
					} else {
						// users which already have a key-pair will be stored with a
						// empty password and filtered out later
						$this->userPasswords[$user] = '';
					}
				}
				$offset += $limit;
			} while (count($users) >= $limit);
		}

		$progress->setMessage('Key-pair created for all users');
		$progress->finish();
	}

	/**
	 * iterate over all user and encrypt their files
	 */
	protected function encryptAllUsersFiles() {
		$this->output->writeln("\n");
		$progress = new ProgressBar($this->output);
		$progress->setFormat(" %message% \n [%bar%]");
		$progress->start();
		$numberOfUsers = count($this->userPasswords);
		$userNo = 1;
		if ($this->util->isMasterKeyEnabled()) {
			$this->encryptAllUserFilesWithMasterKey($progress);
		} else {
			foreach ($this->userPasswords as $uid => $password) {
				$userCount = "$uid ($userNo of $numberOfUsers)";
				$this->encryptUsersFiles($uid, $progress, $userCount);
				$userNo++;
			}
		}
		$progress->setMessage('all files encrypted');
		$progress->finish();
	}

	/**
	 * encrypt all user files with the master key
	 *
	 * @param ProgressBar $progress
	 */
	protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
		$userNo = 1;
		foreach ($this->userManager->getBackends() as $backend) {
			$limit = 500;
			$offset = 0;
			do {
				$users = $backend->getUsers('', $limit, $offset);
				foreach ($users as $user) {
					$userCount = "$user ($userNo)";
					$this->encryptUsersFiles($user, $progress, $userCount);
					$userNo++;
				}
				$offset += $limit;
			} while (count($users) >= $limit);
		}
	}

	/**
	 * encrypt files from the given user
	 *
	 * @param string $uid
	 * @param ProgressBar $progress
	 * @param string $userCount
	 */
	protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
		$this->setupUserFS($uid);
		$directories = [];
		$directories[] = '/' . $uid . '/files';

		while ($root = array_pop($directories)) {
			$content = $this->rootView->getDirectoryContent($root);
			foreach ($content as $file) {
				$path = $root . '/' . $file['name'];
				if ($this->rootView->is_dir($path)) {
					$directories[] = $path;
					continue;
				} else {
					$progress->setMessage("encrypt files for user $userCount: $path");
					$progress->advance();
					if ($this->encryptFile($path) === false) {
						$progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
						$progress->advance();
					}
				}
			}
		}
	}

	/**
	 * encrypt file
	 *
	 * @param string $path
	 * @return bool
	 */
	protected function encryptFile($path) {

		// skip already encrypted files
		$fileInfo = $this->rootView->getFileInfo($path);
		if ($fileInfo !== false && $fileInfo->isEncrypted()) {
			return true;
		}

		$source = $path;
		$target = $path . '.encrypted.' . time();

		try {
			$this->rootView->copy($source, $target);
			$this->rootView->rename($target, $source);
		} catch (DecryptionFailedException $e) {
			if ($this->rootView->file_exists($target)) {
				$this->rootView->unlink($target);
			}
			return false;
		}

		return true;
	}

	/**
	 * output one-time encryption passwords
	 */
	protected function outputPasswords() {
		$table = new Table($this->output);
		$table->setHeaders(['Username', 'Private key password']);

		//create rows
		$newPasswords = [];
		$unchangedPasswords = [];
		foreach ($this->userPasswords as $uid => $password) {
			if (empty($password)) {
				$unchangedPasswords[] = $uid;
			} else {
				$newPasswords[] = [$uid, $password];
			}
		}

		if (empty($newPasswords)) {
			$this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
			return;
		}

		$table->setRows($newPasswords);
		$table->render();

		if (!empty($unchangedPasswords)) {
			$this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
			foreach ($unchangedPasswords as $uid) {
				$this->output->writeln("    $uid");
			}
		}

		$this->writePasswordsToFile($newPasswords);

		$this->output->writeln('');
		$question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
		if ($this->questionHelper->ask($this->input, $this->output, $question)) {
			$this->sendPasswordsByMail();
		}
	}

	/**
	 * write one-time encryption passwords to a csv file
	 *
	 * @param array $passwords
	 */
	protected function writePasswordsToFile(array $passwords) {
		$fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
		foreach ($passwords as $pwd) {
			fputcsv($fp, $pwd);
		}
		fclose($fp);
		$this->output->writeln("\n");
		$this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
		$this->output->writeln('');
		$this->output->writeln('Each of these users need to login to the web interface, go to the');
		$this->output->writeln('personal settings section "basic encryption module" and');
		$this->output->writeln('update the private key password to match the login password again by');
		$this->output->writeln('entering the one-time password into the "old log-in password" field');
		$this->output->writeln('and their current login password');
	}

	/**
	 * setup user file system
	 *
	 * @param string $uid
	 */
	protected function setupUserFS($uid) {
		\OC_Util::tearDownFS();
		\OC_Util::setupFS($uid);
	}

	/**
	 * generate one time password for the user and store it in a array
	 *
	 * @param string $uid
	 * @return string password
	 */
	protected function generateOneTimePassword($uid) {
		$password = $this->secureRandom->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
		$this->userPasswords[$uid] = $password;
		return $password;
	}

	/**
	 * send encryption key passwords to the users by mail
	 */
	protected function sendPasswordsByMail() {
		$noMail = [];

		$this->output->writeln('');
		$progress = new ProgressBar($this->output, count($this->userPasswords));
		$progress->start();

		foreach ($this->userPasswords as $uid => $password) {
			$progress->advance();
			if (!empty($password)) {
				$recipient = $this->userManager->get($uid);
				if (!$recipient instanceof IUser) {
					continue;
				}

				$recipientDisplayName = $recipient->getDisplayName();
				$to = $recipient->getEMailAddress();

				if ($to === '' || $to === null) {
					$noMail[] = $uid;
					continue;
				}

				$l = $this->l10nFactory->get('encryption', $this->l10nFactory->getUserLanguage($recipient));

				$template = $this->mailer->createEMailTemplate('encryption.encryptAllPassword', [
					'user' => $recipient->getUID(),
					'password' => $password,
				]);

				$template->setSubject($l->t('one-time password for server-side-encryption'));
				// 'Hey there,<br><br>The administration enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>
				// Please login to the web interface, go to the section "Basic encryption module" of your personal settings and update your encryption password by entering this password into the "Old log-in password" field and your current login-password.<br><br>'
				$template->addHeader();
				$template->addHeading($l->t('Encryption password'));
				$template->addBodyText(
					$l->t('The administration enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.', [htmlspecialchars($password)]),
					$l->t('The administration enabled server-side-encryption. Your files were encrypted using the password "%s".', $password)
				);
				$template->addBodyText(
					$l->t('Please login to the web interface, go to the "Security" section of your personal settings and update your encryption password by entering this password into the "Old login password" field and your current login password.')
				);
				$template->addFooter();

				// send it out now
				try {
					$message = $this->mailer->createMessage();
					$message->setTo([$to => $recipientDisplayName]);
					$message->useTemplate($template);
					$message->setAutoSubmitted(AutoSubmitted::VALUE_AUTO_GENERATED);
					$this->mailer->send($message);
				} catch (\Exception $e) {
					$noMail[] = $uid;
				}
			}
		}

		$progress->finish();

		if (empty($noMail)) {
			$this->output->writeln("\n\nPassword successfully send to all users");
		} else {
			$table = new Table($this->output);
			$table->setHeaders(['Username', 'Private key password']);
			$this->output->writeln("\n\nCould not send password to following users:\n");
			$rows = [];
			foreach ($noMail as $uid) {
				$rows[] = [$uid, $this->userPasswords[$uid]];
			}
			$table->setRows($rows);
			$table->render();
		}
	}
}