EncryptAll.php 12 KB

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