EncryptAll.php 13 KB

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