EncryptAll.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Kenneth Newwood <kenneth@newwood.name>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Encryption\Crypto;
  29. use OC\Encryption\Exceptions\DecryptionFailedException;
  30. use OC\Files\View;
  31. use OCA\Encryption\KeyManager;
  32. use OCA\Encryption\Users\Setup;
  33. use OCA\Encryption\Util;
  34. use OCP\IConfig;
  35. use OCP\IL10N;
  36. use OCP\IUserManager;
  37. use OCP\Mail\IMailer;
  38. use OCP\Security\ISecureRandom;
  39. use Symfony\Component\Console\Helper\ProgressBar;
  40. use Symfony\Component\Console\Helper\QuestionHelper;
  41. use Symfony\Component\Console\Helper\Table;
  42. use Symfony\Component\Console\Input\InputInterface;
  43. use Symfony\Component\Console\Output\OutputInterface;
  44. use Symfony\Component\Console\Question\ConfirmationQuestion;
  45. class EncryptAll {
  46. /** @var Setup */
  47. protected $userSetup;
  48. /** @var IUserManager */
  49. protected $userManager;
  50. /** @var View */
  51. protected $rootView;
  52. /** @var KeyManager */
  53. protected $keyManager;
  54. /** @var Util */
  55. protected $util;
  56. /** @var array */
  57. protected $userPasswords;
  58. /** @var IConfig */
  59. protected $config;
  60. /** @var IMailer */
  61. protected $mailer;
  62. /** @var IL10N */
  63. protected $l;
  64. /** @var QuestionHelper */
  65. protected $questionHelper;
  66. /** @var OutputInterface */
  67. protected $output;
  68. /** @var InputInterface */
  69. protected $input;
  70. /** @var ISecureRandom */
  71. protected $secureRandom;
  72. /**
  73. * @param Setup $userSetup
  74. * @param IUserManager $userManager
  75. * @param View $rootView
  76. * @param KeyManager $keyManager
  77. * @param Util $util
  78. * @param IConfig $config
  79. * @param IMailer $mailer
  80. * @param IL10N $l
  81. * @param QuestionHelper $questionHelper
  82. * @param ISecureRandom $secureRandom
  83. */
  84. public function __construct(
  85. Setup $userSetup,
  86. IUserManager $userManager,
  87. View $rootView,
  88. KeyManager $keyManager,
  89. Util $util,
  90. IConfig $config,
  91. IMailer $mailer,
  92. IL10N $l,
  93. QuestionHelper $questionHelper,
  94. ISecureRandom $secureRandom
  95. ) {
  96. $this->userSetup = $userSetup;
  97. $this->userManager = $userManager;
  98. $this->rootView = $rootView;
  99. $this->keyManager = $keyManager;
  100. $this->util = $util;
  101. $this->config = $config;
  102. $this->mailer = $mailer;
  103. $this->l = $l;
  104. $this->questionHelper = $questionHelper;
  105. $this->secureRandom = $secureRandom;
  106. // store one time passwords for the users
  107. $this->userPasswords = [];
  108. }
  109. /**
  110. * start to encrypt all files
  111. *
  112. * @param InputInterface $input
  113. * @param OutputInterface $output
  114. */
  115. public function encryptAll(InputInterface $input, OutputInterface $output) {
  116. $this->input = $input;
  117. $this->output = $output;
  118. $headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
  119. $this->output->writeln("\n");
  120. $this->output->writeln($headline);
  121. $this->output->writeln(str_pad('', strlen($headline), '='));
  122. $this->output->writeln("\n");
  123. if ($this->util->isMasterKeyEnabled()) {
  124. $this->output->writeln('Use master key to encrypt all files.');
  125. $this->keyManager->validateMasterKey();
  126. } else {
  127. //create private/public keys for each user and store the private key password
  128. $this->output->writeln('Create key-pair for every user');
  129. $this->output->writeln('------------------------------');
  130. $this->output->writeln('');
  131. $this->output->writeln('This module will encrypt all files in the users files folder initially.');
  132. $this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
  133. $this->output->writeln('');
  134. $this->createKeyPairs();
  135. }
  136. // output generated encryption key passwords
  137. if ($this->util->isMasterKeyEnabled() === false) {
  138. //send-out or display password list and write it to a file
  139. $this->output->writeln("\n");
  140. $this->output->writeln('Generated encryption key passwords');
  141. $this->output->writeln('----------------------------------');
  142. $this->output->writeln('');
  143. $this->outputPasswords();
  144. }
  145. //setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
  146. $this->output->writeln("\n");
  147. $this->output->writeln('Start to encrypt users files');
  148. $this->output->writeln('----------------------------');
  149. $this->output->writeln('');
  150. $this->encryptAllUsersFiles();
  151. $this->output->writeln("\n");
  152. }
  153. /**
  154. * create key-pair for every user
  155. */
  156. protected function createKeyPairs() {
  157. $this->output->writeln("\n");
  158. $progress = new ProgressBar($this->output);
  159. $progress->setFormat(" %message% \n [%bar%]");
  160. $progress->start();
  161. foreach ($this->userManager->getBackends() as $backend) {
  162. $limit = 500;
  163. $offset = 0;
  164. do {
  165. $users = $backend->getUsers('', $limit, $offset);
  166. foreach ($users as $user) {
  167. if ($this->keyManager->userHasKeys($user) === false) {
  168. $progress->setMessage('Create key-pair for ' . $user);
  169. $progress->advance();
  170. $this->setupUserFS($user);
  171. $password = $this->generateOneTimePassword($user);
  172. $this->userSetup->setupUser($user, $password);
  173. } else {
  174. // users which already have a key-pair will be stored with a
  175. // empty password and filtered out later
  176. $this->userPasswords[$user] = '';
  177. }
  178. }
  179. $offset += $limit;
  180. } while (count($users) >= $limit);
  181. }
  182. $progress->setMessage('Key-pair created for all users');
  183. $progress->finish();
  184. }
  185. /**
  186. * iterate over all user and encrypt their files
  187. */
  188. protected function encryptAllUsersFiles() {
  189. $this->output->writeln("\n");
  190. $progress = new ProgressBar($this->output);
  191. $progress->setFormat(" %message% \n [%bar%]");
  192. $progress->start();
  193. $numberOfUsers = count($this->userPasswords);
  194. $userNo = 1;
  195. if ($this->util->isMasterKeyEnabled()) {
  196. $this->encryptAllUserFilesWithMasterKey($progress);
  197. } else {
  198. foreach ($this->userPasswords as $uid => $password) {
  199. $userCount = "$uid ($userNo of $numberOfUsers)";
  200. $this->encryptUsersFiles($uid, $progress, $userCount);
  201. $userNo++;
  202. }
  203. }
  204. $progress->setMessage("all files encrypted");
  205. $progress->finish();
  206. }
  207. /**
  208. * encrypt all user files with the master key
  209. *
  210. * @param ProgressBar $progress
  211. */
  212. protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
  213. $userNo = 1;
  214. foreach ($this->userManager->getBackends() as $backend) {
  215. $limit = 500;
  216. $offset = 0;
  217. do {
  218. $users = $backend->getUsers('', $limit, $offset);
  219. foreach ($users as $user) {
  220. $userCount = "$user ($userNo)";
  221. $this->encryptUsersFiles($user, $progress, $userCount);
  222. $userNo++;
  223. }
  224. $offset += $limit;
  225. } while (count($users) >= $limit);
  226. }
  227. }
  228. /**
  229. * encrypt files from the given user
  230. *
  231. * @param string $uid
  232. * @param ProgressBar $progress
  233. * @param string $userCount
  234. */
  235. protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
  236. $this->setupUserFS($uid);
  237. $directories = [];
  238. $directories[] = '/' . $uid . '/files';
  239. while ($root = array_pop($directories)) {
  240. $content = $this->rootView->getDirectoryContent($root);
  241. foreach ($content as $file) {
  242. $path = $root . '/' . $file['name'];
  243. if ($this->rootView->is_dir($path)) {
  244. $directories[] = $path;
  245. continue;
  246. } else {
  247. $progress->setMessage("encrypt files for user $userCount: $path");
  248. $progress->advance();
  249. if ($this->encryptFile($path) === false) {
  250. $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
  251. $progress->advance();
  252. }
  253. }
  254. }
  255. }
  256. }
  257. /**
  258. * encrypt file
  259. *
  260. * @param string $path
  261. * @return bool
  262. */
  263. protected function encryptFile($path) {
  264. // skip already encrypted files
  265. $fileInfo = $this->rootView->getFileInfo($path);
  266. if ($fileInfo !== false && $fileInfo->isEncrypted()) {
  267. return true;
  268. }
  269. $source = $path;
  270. $target = $path . '.encrypted.' . time();
  271. try {
  272. $this->rootView->copy($source, $target);
  273. $this->rootView->rename($target, $source);
  274. } catch (DecryptionFailedException $e) {
  275. if ($this->rootView->file_exists($target)) {
  276. $this->rootView->unlink($target);
  277. }
  278. return false;
  279. }
  280. return true;
  281. }
  282. /**
  283. * output one-time encryption passwords
  284. */
  285. protected function outputPasswords() {
  286. $table = new Table($this->output);
  287. $table->setHeaders(['Username', 'Private key password']);
  288. //create rows
  289. $newPasswords = [];
  290. $unchangedPasswords = [];
  291. foreach ($this->userPasswords as $uid => $password) {
  292. if (empty($password)) {
  293. $unchangedPasswords[] = $uid;
  294. } else {
  295. $newPasswords[] = [$uid, $password];
  296. }
  297. }
  298. if (empty($newPasswords)) {
  299. $this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
  300. return;
  301. }
  302. $table->setRows($newPasswords);
  303. $table->render();
  304. if (!empty($unchangedPasswords)) {
  305. $this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
  306. foreach ($unchangedPasswords as $uid) {
  307. $this->output->writeln(" $uid");
  308. }
  309. }
  310. $this->writePasswordsToFile($newPasswords);
  311. $this->output->writeln('');
  312. $question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
  313. if ($this->questionHelper->ask($this->input, $this->output, $question)) {
  314. $this->sendPasswordsByMail();
  315. }
  316. }
  317. /**
  318. * write one-time encryption passwords to a csv file
  319. *
  320. * @param array $passwords
  321. */
  322. protected function writePasswordsToFile(array $passwords) {
  323. $fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
  324. foreach ($passwords as $pwd) {
  325. fputcsv($fp, $pwd);
  326. }
  327. fclose($fp);
  328. $this->output->writeln("\n");
  329. $this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
  330. $this->output->writeln('');
  331. $this->output->writeln('Each of these users need to login to the web interface, go to the');
  332. $this->output->writeln('personal settings section "basic encryption module" and');
  333. $this->output->writeln('update the private key password to match the login password again by');
  334. $this->output->writeln('entering the one-time password into the "old log-in password" field');
  335. $this->output->writeln('and their current login password');
  336. }
  337. /**
  338. * setup user file system
  339. *
  340. * @param string $uid
  341. */
  342. protected function setupUserFS($uid) {
  343. \OC_Util::tearDownFS();
  344. \OC_Util::setupFS($uid);
  345. }
  346. /**
  347. * generate one time password for the user and store it in a array
  348. *
  349. * @param string $uid
  350. * @return string password
  351. */
  352. protected function generateOneTimePassword($uid) {
  353. $password = $this->secureRandom->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
  354. $this->userPasswords[$uid] = $password;
  355. return $password;
  356. }
  357. /**
  358. * send encryption key passwords to the users by mail
  359. */
  360. protected function sendPasswordsByMail() {
  361. $noMail = [];
  362. $this->output->writeln('');
  363. $progress = new ProgressBar($this->output, count($this->userPasswords));
  364. $progress->start();
  365. foreach ($this->userPasswords as $uid => $password) {
  366. $progress->advance();
  367. if (!empty($password)) {
  368. $recipient = $this->userManager->get($uid);
  369. $recipientDisplayName = $recipient->getDisplayName();
  370. $to = $recipient->getEMailAddress();
  371. if ($to === '' || $to === null) {
  372. $noMail[] = $uid;
  373. continue;
  374. }
  375. $subject = $this->l->t('one-time password for server-side-encryption');
  376. [$htmlBody, $textBody] = $this->createMailBody($password);
  377. // send it out now
  378. try {
  379. $message = $this->mailer->createMessage();
  380. $message->setSubject($subject);
  381. $message->setTo([$to => $recipientDisplayName]);
  382. $message->setHtmlBody($htmlBody);
  383. $message->setPlainBody($textBody);
  384. $message->setFrom([
  385. \OCP\Util::getDefaultEmailAddress('admin-noreply')
  386. ]);
  387. $this->mailer->send($message);
  388. } catch (\Exception $e) {
  389. $noMail[] = $uid;
  390. }
  391. }
  392. }
  393. $progress->finish();
  394. if (empty($noMail)) {
  395. $this->output->writeln("\n\nPassword successfully send to all users");
  396. } else {
  397. $table = new Table($this->output);
  398. $table->setHeaders(['Username', 'Private key password']);
  399. $this->output->writeln("\n\nCould not send password to following users:\n");
  400. $rows = [];
  401. foreach ($noMail as $uid) {
  402. $rows[] = [$uid, $this->userPasswords[$uid]];
  403. }
  404. $table->setRows($rows);
  405. $table->render();
  406. }
  407. }
  408. /**
  409. * create mail body for plain text and html mail
  410. *
  411. * @param string $password one-time encryption password
  412. * @return array an array of the html mail body and the plain text mail body
  413. */
  414. protected function createMailBody($password) {
  415. $html = new \OC_Template("encryption", "mail", "");
  416. $html->assign('password', $password);
  417. $htmlMail = $html->fetchPage();
  418. $plainText = new \OC_Template("encryption", "altmail", "");
  419. $plainText->assign('password', $password);
  420. $plainTextMail = $plainText->fetchPage();
  421. return [$htmlMail, $plainTextMail];
  422. }
  423. }