EncryptAll.php 13 KB

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