EncryptAll.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Encryption\Crypto;
  8. use OC\Encryption\Exceptions\DecryptionFailedException;
  9. use OC\Files\View;
  10. use OCA\Encryption\KeyManager;
  11. use OCA\Encryption\Users\Setup;
  12. use OCA\Encryption\Util;
  13. use OCP\IConfig;
  14. use OCP\IL10N;
  15. use OCP\IUser;
  16. use OCP\IUserManager;
  17. use OCP\L10N\IFactory;
  18. use OCP\Mail\Headers\AutoSubmitted;
  19. use OCP\Mail\IMailer;
  20. use OCP\Security\ISecureRandom;
  21. use Symfony\Component\Console\Helper\ProgressBar;
  22. use Symfony\Component\Console\Helper\QuestionHelper;
  23. use Symfony\Component\Console\Helper\Table;
  24. use Symfony\Component\Console\Input\InputInterface;
  25. use Symfony\Component\Console\Output\OutputInterface;
  26. use Symfony\Component\Console\Question\ConfirmationQuestion;
  27. class EncryptAll {
  28. /** @var Setup */
  29. protected $userSetup;
  30. /** @var IUserManager */
  31. protected $userManager;
  32. /** @var View */
  33. protected $rootView;
  34. /** @var KeyManager */
  35. protected $keyManager;
  36. /** @var Util */
  37. protected $util;
  38. /** @var array */
  39. protected $userPasswords;
  40. /** @var IConfig */
  41. protected $config;
  42. /** @var IMailer */
  43. protected $mailer;
  44. /** @var IL10N */
  45. protected $l;
  46. /** @var IFactory */
  47. protected $l10nFactory;
  48. /** @var QuestionHelper */
  49. protected $questionHelper;
  50. /** @var OutputInterface */
  51. protected $output;
  52. /** @var InputInterface */
  53. protected $input;
  54. /** @var ISecureRandom */
  55. protected $secureRandom;
  56. public function __construct(
  57. Setup $userSetup,
  58. IUserManager $userManager,
  59. View $rootView,
  60. KeyManager $keyManager,
  61. Util $util,
  62. IConfig $config,
  63. IMailer $mailer,
  64. IL10N $l,
  65. IFactory $l10nFactory,
  66. QuestionHelper $questionHelper,
  67. ISecureRandom $secureRandom,
  68. ) {
  69. $this->userSetup = $userSetup;
  70. $this->userManager = $userManager;
  71. $this->rootView = $rootView;
  72. $this->keyManager = $keyManager;
  73. $this->util = $util;
  74. $this->config = $config;
  75. $this->mailer = $mailer;
  76. $this->l = $l;
  77. $this->l10nFactory = $l10nFactory;
  78. $this->questionHelper = $questionHelper;
  79. $this->secureRandom = $secureRandom;
  80. // store one time passwords for the users
  81. $this->userPasswords = [];
  82. }
  83. /**
  84. * start to encrypt all files
  85. *
  86. * @param InputInterface $input
  87. * @param OutputInterface $output
  88. */
  89. public function encryptAll(InputInterface $input, OutputInterface $output) {
  90. $this->input = $input;
  91. $this->output = $output;
  92. $headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
  93. $this->output->writeln("\n");
  94. $this->output->writeln($headline);
  95. $this->output->writeln(str_pad('', strlen($headline), '='));
  96. $this->output->writeln("\n");
  97. if ($this->util->isMasterKeyEnabled()) {
  98. $this->output->writeln('Use master key to encrypt all files.');
  99. $this->keyManager->validateMasterKey();
  100. } else {
  101. //create private/public keys for each user and store the private key password
  102. $this->output->writeln('Create key-pair for every user');
  103. $this->output->writeln('------------------------------');
  104. $this->output->writeln('');
  105. $this->output->writeln('This module will encrypt all files in the users files folder initially.');
  106. $this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
  107. $this->output->writeln('');
  108. $this->createKeyPairs();
  109. }
  110. // output generated encryption key passwords
  111. if ($this->util->isMasterKeyEnabled() === false) {
  112. //send-out or display password list and write it to a file
  113. $this->output->writeln("\n");
  114. $this->output->writeln('Generated encryption key passwords');
  115. $this->output->writeln('----------------------------------');
  116. $this->output->writeln('');
  117. $this->outputPasswords();
  118. }
  119. //setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
  120. $this->output->writeln("\n");
  121. $this->output->writeln('Start to encrypt users files');
  122. $this->output->writeln('----------------------------');
  123. $this->output->writeln('');
  124. $this->encryptAllUsersFiles();
  125. $this->output->writeln("\n");
  126. }
  127. /**
  128. * create key-pair for every user
  129. */
  130. protected function createKeyPairs() {
  131. $this->output->writeln("\n");
  132. $progress = new ProgressBar($this->output);
  133. $progress->setFormat(" %message% \n [%bar%]");
  134. $progress->start();
  135. foreach ($this->userManager->getBackends() as $backend) {
  136. $limit = 500;
  137. $offset = 0;
  138. do {
  139. $users = $backend->getUsers('', $limit, $offset);
  140. foreach ($users as $user) {
  141. if ($this->keyManager->userHasKeys($user) === false) {
  142. $progress->setMessage('Create key-pair for ' . $user);
  143. $progress->advance();
  144. $this->setupUserFS($user);
  145. $password = $this->generateOneTimePassword($user);
  146. $this->userSetup->setupUser($user, $password);
  147. } else {
  148. // users which already have a key-pair will be stored with a
  149. // empty password and filtered out later
  150. $this->userPasswords[$user] = '';
  151. }
  152. }
  153. $offset += $limit;
  154. } while (count($users) >= $limit);
  155. }
  156. $progress->setMessage('Key-pair created for all users');
  157. $progress->finish();
  158. }
  159. /**
  160. * iterate over all user and encrypt their files
  161. */
  162. protected function encryptAllUsersFiles() {
  163. $this->output->writeln("\n");
  164. $progress = new ProgressBar($this->output);
  165. $progress->setFormat(" %message% \n [%bar%]");
  166. $progress->start();
  167. $numberOfUsers = count($this->userPasswords);
  168. $userNo = 1;
  169. if ($this->util->isMasterKeyEnabled()) {
  170. $this->encryptAllUserFilesWithMasterKey($progress);
  171. } else {
  172. foreach ($this->userPasswords as $uid => $password) {
  173. $userCount = "$uid ($userNo of $numberOfUsers)";
  174. $this->encryptUsersFiles($uid, $progress, $userCount);
  175. $userNo++;
  176. }
  177. }
  178. $progress->setMessage('all files encrypted');
  179. $progress->finish();
  180. }
  181. /**
  182. * encrypt all user files with the master key
  183. *
  184. * @param ProgressBar $progress
  185. */
  186. protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
  187. $userNo = 1;
  188. foreach ($this->userManager->getBackends() as $backend) {
  189. $limit = 500;
  190. $offset = 0;
  191. do {
  192. $users = $backend->getUsers('', $limit, $offset);
  193. foreach ($users as $user) {
  194. $userCount = "$user ($userNo)";
  195. $this->encryptUsersFiles($user, $progress, $userCount);
  196. $userNo++;
  197. }
  198. $offset += $limit;
  199. } while (count($users) >= $limit);
  200. }
  201. }
  202. /**
  203. * encrypt files from the given user
  204. *
  205. * @param string $uid
  206. * @param ProgressBar $progress
  207. * @param string $userCount
  208. */
  209. protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
  210. $this->setupUserFS($uid);
  211. $directories = [];
  212. $directories[] = '/' . $uid . '/files';
  213. while ($root = array_pop($directories)) {
  214. $content = $this->rootView->getDirectoryContent($root);
  215. foreach ($content as $file) {
  216. $path = $root . '/' . $file['name'];
  217. if ($this->rootView->is_dir($path)) {
  218. $directories[] = $path;
  219. continue;
  220. } else {
  221. $progress->setMessage("encrypt files for user $userCount: $path");
  222. $progress->advance();
  223. if ($this->encryptFile($path) === false) {
  224. $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
  225. $progress->advance();
  226. }
  227. }
  228. }
  229. }
  230. }
  231. /**
  232. * encrypt file
  233. *
  234. * @param string $path
  235. * @return bool
  236. */
  237. protected function encryptFile($path) {
  238. // skip already encrypted files
  239. $fileInfo = $this->rootView->getFileInfo($path);
  240. if ($fileInfo !== false && $fileInfo->isEncrypted()) {
  241. return true;
  242. }
  243. $source = $path;
  244. $target = $path . '.encrypted.' . time();
  245. try {
  246. $this->rootView->copy($source, $target);
  247. $this->rootView->rename($target, $source);
  248. } catch (DecryptionFailedException $e) {
  249. if ($this->rootView->file_exists($target)) {
  250. $this->rootView->unlink($target);
  251. }
  252. return false;
  253. }
  254. return true;
  255. }
  256. /**
  257. * output one-time encryption passwords
  258. */
  259. protected function outputPasswords() {
  260. $table = new Table($this->output);
  261. $table->setHeaders(['Username', 'Private key password']);
  262. //create rows
  263. $newPasswords = [];
  264. $unchangedPasswords = [];
  265. foreach ($this->userPasswords as $uid => $password) {
  266. if (empty($password)) {
  267. $unchangedPasswords[] = $uid;
  268. } else {
  269. $newPasswords[] = [$uid, $password];
  270. }
  271. }
  272. if (empty($newPasswords)) {
  273. $this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
  274. return;
  275. }
  276. $table->setRows($newPasswords);
  277. $table->render();
  278. if (!empty($unchangedPasswords)) {
  279. $this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
  280. foreach ($unchangedPasswords as $uid) {
  281. $this->output->writeln(" $uid");
  282. }
  283. }
  284. $this->writePasswordsToFile($newPasswords);
  285. $this->output->writeln('');
  286. $question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
  287. if ($this->questionHelper->ask($this->input, $this->output, $question)) {
  288. $this->sendPasswordsByMail();
  289. }
  290. }
  291. /**
  292. * write one-time encryption passwords to a csv file
  293. *
  294. * @param array $passwords
  295. */
  296. protected function writePasswordsToFile(array $passwords) {
  297. $fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
  298. foreach ($passwords as $pwd) {
  299. fputcsv($fp, $pwd);
  300. }
  301. fclose($fp);
  302. $this->output->writeln("\n");
  303. $this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
  304. $this->output->writeln('');
  305. $this->output->writeln('Each of these users need to login to the web interface, go to the');
  306. $this->output->writeln('personal settings section "basic encryption module" and');
  307. $this->output->writeln('update the private key password to match the login password again by');
  308. $this->output->writeln('entering the one-time password into the "old log-in password" field');
  309. $this->output->writeln('and their current login password');
  310. }
  311. /**
  312. * setup user file system
  313. *
  314. * @param string $uid
  315. */
  316. protected function setupUserFS($uid) {
  317. \OC_Util::tearDownFS();
  318. \OC_Util::setupFS($uid);
  319. }
  320. /**
  321. * generate one time password for the user and store it in a array
  322. *
  323. * @param string $uid
  324. * @return string password
  325. */
  326. protected function generateOneTimePassword($uid) {
  327. $password = $this->secureRandom->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
  328. $this->userPasswords[$uid] = $password;
  329. return $password;
  330. }
  331. /**
  332. * send encryption key passwords to the users by mail
  333. */
  334. protected function sendPasswordsByMail() {
  335. $noMail = [];
  336. $this->output->writeln('');
  337. $progress = new ProgressBar($this->output, count($this->userPasswords));
  338. $progress->start();
  339. foreach ($this->userPasswords as $uid => $password) {
  340. $progress->advance();
  341. if (!empty($password)) {
  342. $recipient = $this->userManager->get($uid);
  343. if (!$recipient instanceof IUser) {
  344. continue;
  345. }
  346. $recipientDisplayName = $recipient->getDisplayName();
  347. $to = $recipient->getEMailAddress();
  348. if ($to === '' || $to === null) {
  349. $noMail[] = $uid;
  350. continue;
  351. }
  352. $l = $this->l10nFactory->get('encryption', $this->l10nFactory->getUserLanguage($recipient));
  353. $template = $this->mailer->createEMailTemplate('encryption.encryptAllPassword', [
  354. 'user' => $recipient->getUID(),
  355. 'password' => $password,
  356. ]);
  357. $template->setSubject($l->t('one-time password for server-side-encryption'));
  358. // 'Hey there,<br><br>The administration enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>
  359. // 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>'
  360. $template->addHeader();
  361. $template->addHeading($l->t('Encryption password'));
  362. $template->addBodyText(
  363. $l->t('The administration enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.', [htmlspecialchars($password)]),
  364. $l->t('The administration enabled server-side-encryption. Your files were encrypted using the password "%s".', $password)
  365. );
  366. $template->addBodyText(
  367. $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.')
  368. );
  369. $template->addFooter();
  370. // send it out now
  371. try {
  372. $message = $this->mailer->createMessage();
  373. $message->setTo([$to => $recipientDisplayName]);
  374. $message->useTemplate($template);
  375. $message->setAutoSubmitted(AutoSubmitted::VALUE_AUTO_GENERATED);
  376. $this->mailer->send($message);
  377. } catch (\Exception $e) {
  378. $noMail[] = $uid;
  379. }
  380. }
  381. }
  382. $progress->finish();
  383. if (empty($noMail)) {
  384. $this->output->writeln("\n\nPassword successfully send to all users");
  385. } else {
  386. $table = new Table($this->output);
  387. $table->setHeaders(['Username', 'Private key password']);
  388. $this->output->writeln("\n\nCould not send password to following users:\n");
  389. $rows = [];
  390. foreach ($noMail as $uid) {
  391. $rows[] = [$uid, $this->userPasswords[$uid]];
  392. }
  393. $table->setRows($rows);
  394. $table->render();
  395. }
  396. }
  397. }