Encryption.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 Clark Tomlinson <fallen013@gmail.com>
  8. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OCA\Encryption\Crypto;
  31. use OC\Encryption\Exceptions\DecryptionFailedException;
  32. use OC\Files\Cache\Scanner;
  33. use OC\Files\View;
  34. use OCA\Encryption\Exceptions\PublicKeyMissingException;
  35. use OCA\Encryption\KeyManager;
  36. use OCA\Encryption\Session;
  37. use OCA\Encryption\Util;
  38. use OCP\Encryption\IEncryptionModule;
  39. use OCP\IL10N;
  40. use OCP\ILogger;
  41. use Symfony\Component\Console\Input\InputInterface;
  42. use Symfony\Component\Console\Output\OutputInterface;
  43. class Encryption implements IEncryptionModule {
  44. const ID = 'OC_DEFAULT_MODULE';
  45. const DISPLAY_NAME = 'Default encryption module';
  46. /**
  47. * @var Crypt
  48. */
  49. private $crypt;
  50. /** @var string */
  51. private $cipher;
  52. /** @var string */
  53. private $path;
  54. /** @var string */
  55. private $user;
  56. /** @var array */
  57. private $owner;
  58. /** @var string */
  59. private $fileKey;
  60. /** @var string */
  61. private $writeCache;
  62. /** @var KeyManager */
  63. private $keyManager;
  64. /** @var array */
  65. private $accessList;
  66. /** @var boolean */
  67. private $isWriteOperation;
  68. /** @var Util */
  69. private $util;
  70. /** @var Session */
  71. private $session;
  72. /** @var ILogger */
  73. private $logger;
  74. /** @var IL10N */
  75. private $l;
  76. /** @var EncryptAll */
  77. private $encryptAll;
  78. /** @var bool */
  79. private $useMasterPassword;
  80. /** @var DecryptAll */
  81. private $decryptAll;
  82. /** @var int unencrypted block size if block contains signature */
  83. private $unencryptedBlockSizeSigned = 6072;
  84. /** @var int unencrypted block size */
  85. private $unencryptedBlockSize = 6126;
  86. /** @var int Current version of the file */
  87. private $version = 0;
  88. /** @var array remember encryption signature version */
  89. private static $rememberVersion = [];
  90. /**
  91. *
  92. * @param Crypt $crypt
  93. * @param KeyManager $keyManager
  94. * @param Util $util
  95. * @param Session $session
  96. * @param EncryptAll $encryptAll
  97. * @param DecryptAll $decryptAll
  98. * @param ILogger $logger
  99. * @param IL10N $il10n
  100. */
  101. public function __construct(Crypt $crypt,
  102. KeyManager $keyManager,
  103. Util $util,
  104. Session $session,
  105. EncryptAll $encryptAll,
  106. DecryptAll $decryptAll,
  107. ILogger $logger,
  108. IL10N $il10n) {
  109. $this->crypt = $crypt;
  110. $this->keyManager = $keyManager;
  111. $this->util = $util;
  112. $this->session = $session;
  113. $this->encryptAll = $encryptAll;
  114. $this->decryptAll = $decryptAll;
  115. $this->logger = $logger;
  116. $this->l = $il10n;
  117. $this->owner = [];
  118. $this->useMasterPassword = $util->isMasterKeyEnabled();
  119. }
  120. /**
  121. * @return string defining the technical unique id
  122. */
  123. public function getId() {
  124. return self::ID;
  125. }
  126. /**
  127. * In comparison to getKey() this function returns a human readable (maybe translated) name
  128. *
  129. * @return string
  130. */
  131. public function getDisplayName() {
  132. return self::DISPLAY_NAME;
  133. }
  134. /**
  135. * start receiving chunks from a file. This is the place where you can
  136. * perform some initial step before starting encrypting/decrypting the
  137. * chunks
  138. *
  139. * @param string $path to the file
  140. * @param string $user who read/write the file
  141. * @param string $mode php stream open mode
  142. * @param array $header contains the header data read from the file
  143. * @param array $accessList who has access to the file contains the key 'users' and 'public'
  144. *
  145. * @return array $header contain data as key-value pairs which should be
  146. * written to the header, in case of a write operation
  147. * or if no additional data is needed return a empty array
  148. */
  149. public function begin($path, $user, $mode, array $header, array $accessList) {
  150. $this->path = $this->getPathToRealFile($path);
  151. $this->accessList = $accessList;
  152. $this->user = $user;
  153. $this->isWriteOperation = false;
  154. $this->writeCache = '';
  155. if($this->session->isReady() === false) {
  156. // if the master key is enabled we can initialize encryption
  157. // with a empty password and user name
  158. if ($this->util->isMasterKeyEnabled()) {
  159. $this->keyManager->init('', '');
  160. }
  161. }
  162. if ($this->session->decryptAllModeActivated()) {
  163. $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
  164. $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
  165. $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
  166. $shareKey,
  167. $this->session->getDecryptAllKey());
  168. } else {
  169. $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
  170. }
  171. // always use the version from the original file, also part files
  172. // need to have a correct version number if they get moved over to the
  173. // final location
  174. $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
  175. if (
  176. $mode === 'w'
  177. || $mode === 'w+'
  178. || $mode === 'wb'
  179. || $mode === 'wb+'
  180. ) {
  181. $this->isWriteOperation = true;
  182. if (empty($this->fileKey)) {
  183. $this->fileKey = $this->crypt->generateFileKey();
  184. }
  185. } else {
  186. // if we read a part file we need to increase the version by 1
  187. // because the version number was also increased by writing
  188. // the part file
  189. if(Scanner::isPartialFile($path)) {
  190. $this->version = $this->version + 1;
  191. }
  192. }
  193. if ($this->isWriteOperation) {
  194. $this->cipher = $this->crypt->getCipher();
  195. } elseif (isset($header['cipher'])) {
  196. $this->cipher = $header['cipher'];
  197. } else {
  198. // if we read a file without a header we fall-back to the legacy cipher
  199. // which was used in <=oC6
  200. $this->cipher = $this->crypt->getLegacyCipher();
  201. }
  202. return array('cipher' => $this->cipher, 'signed' => 'true');
  203. }
  204. /**
  205. * last chunk received. This is the place where you can perform some final
  206. * operation and return some remaining data if something is left in your
  207. * buffer.
  208. *
  209. * @param string $path to the file
  210. * @param int $position
  211. * @return string remained data which should be written to the file in case
  212. * of a write operation
  213. * @throws PublicKeyMissingException
  214. * @throws \Exception
  215. * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
  216. */
  217. public function end($path, $position = 0) {
  218. $result = '';
  219. if ($this->isWriteOperation) {
  220. // in case of a part file we remember the new signature versions
  221. // the version will be set later on update.
  222. // This way we make sure that other apps listening to the pre-hooks
  223. // still get the old version which should be the correct value for them
  224. if (Scanner::isPartialFile($path)) {
  225. self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
  226. }
  227. if (!empty($this->writeCache)) {
  228. $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
  229. $this->writeCache = '';
  230. }
  231. $publicKeys = array();
  232. if ($this->useMasterPassword === true) {
  233. $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
  234. } else {
  235. foreach ($this->accessList['users'] as $uid) {
  236. try {
  237. $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
  238. } catch (PublicKeyMissingException $e) {
  239. $this->logger->warning(
  240. 'no public key found for user "{uid}", user will not be able to read the file',
  241. ['app' => 'encryption', 'uid' => $uid]
  242. );
  243. // if the public key of the owner is missing we should fail
  244. if ($uid === $this->user) {
  245. throw $e;
  246. }
  247. }
  248. }
  249. }
  250. $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
  251. $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
  252. $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
  253. }
  254. return $result;
  255. }
  256. /**
  257. * encrypt data
  258. *
  259. * @param string $data you want to encrypt
  260. * @param int $position
  261. * @return string encrypted data
  262. */
  263. public function encrypt($data, $position = 0) {
  264. // If extra data is left over from the last round, make sure it
  265. // is integrated into the next block
  266. if ($this->writeCache) {
  267. // Concat writeCache to start of $data
  268. $data = $this->writeCache . $data;
  269. // Clear the write cache, ready for reuse - it has been
  270. // flushed and its old contents processed
  271. $this->writeCache = '';
  272. }
  273. $encrypted = '';
  274. // While there still remains some data to be processed & written
  275. while (strlen($data) > 0) {
  276. // Remaining length for this iteration, not of the
  277. // entire file (may be greater than 8192 bytes)
  278. $remainingLength = strlen($data);
  279. // If data remaining to be written is less than the
  280. // size of 1 6126 byte block
  281. if ($remainingLength < $this->unencryptedBlockSizeSigned) {
  282. // Set writeCache to contents of $data
  283. // The writeCache will be carried over to the
  284. // next write round, and added to the start of
  285. // $data to ensure that written blocks are
  286. // always the correct length. If there is still
  287. // data in writeCache after the writing round
  288. // has finished, then the data will be written
  289. // to disk by $this->flush().
  290. $this->writeCache = $data;
  291. // Clear $data ready for next round
  292. $data = '';
  293. } else {
  294. // Read the chunk from the start of $data
  295. $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
  296. $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
  297. // Remove the chunk we just processed from
  298. // $data, leaving only unprocessed data in $data
  299. // var, for handling on the next round
  300. $data = substr($data, $this->unencryptedBlockSizeSigned);
  301. }
  302. }
  303. return $encrypted;
  304. }
  305. /**
  306. * decrypt data
  307. *
  308. * @param string $data you want to decrypt
  309. * @param int $position
  310. * @return string decrypted data
  311. * @throws DecryptionFailedException
  312. */
  313. public function decrypt($data, $position = 0) {
  314. if (empty($this->fileKey)) {
  315. $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
  316. $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
  317. $this->logger->error($msg);
  318. throw new DecryptionFailedException($msg, $hint);
  319. }
  320. return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
  321. }
  322. /**
  323. * update encrypted file, e.g. give additional users access to the file
  324. *
  325. * @param string $path path to the file which should be updated
  326. * @param string $uid of the user who performs the operation
  327. * @param array $accessList who has access to the file contains the key 'users' and 'public'
  328. * @return boolean
  329. */
  330. public function update($path, $uid, array $accessList) {
  331. if (empty($accessList)) {
  332. if (isset(self::$rememberVersion[$path])) {
  333. $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
  334. unset(self::$rememberVersion[$path]);
  335. }
  336. return;
  337. }
  338. $fileKey = $this->keyManager->getFileKey($path, $uid);
  339. if (!empty($fileKey)) {
  340. $publicKeys = array();
  341. if ($this->useMasterPassword === true) {
  342. $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
  343. } else {
  344. foreach ($accessList['users'] as $user) {
  345. try {
  346. $publicKeys[$user] = $this->keyManager->getPublicKey($user);
  347. } catch (PublicKeyMissingException $e) {
  348. $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
  349. }
  350. }
  351. }
  352. $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
  353. $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
  354. $this->keyManager->deleteAllFileKeys($path);
  355. $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
  356. } else {
  357. $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
  358. array('file' => $path, 'app' => 'encryption'));
  359. return false;
  360. }
  361. return true;
  362. }
  363. /**
  364. * should the file be encrypted or not
  365. *
  366. * @param string $path
  367. * @return boolean
  368. */
  369. public function shouldEncrypt($path) {
  370. if ($this->util->shouldEncryptHomeStorage() === false) {
  371. $storage = $this->util->getStorage($path);
  372. if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
  373. return false;
  374. }
  375. }
  376. $parts = explode('/', $path);
  377. if (count($parts) < 4) {
  378. return false;
  379. }
  380. if ($parts[2] === 'files') {
  381. return true;
  382. }
  383. if ($parts[2] === 'files_versions') {
  384. return true;
  385. }
  386. if ($parts[2] === 'files_trashbin') {
  387. return true;
  388. }
  389. return false;
  390. }
  391. /**
  392. * get size of the unencrypted payload per block.
  393. * Nextcloud read/write files with a block size of 8192 byte
  394. *
  395. * @param bool $signed
  396. * @return int
  397. */
  398. public function getUnencryptedBlockSize($signed = false) {
  399. if ($signed === false) {
  400. return $this->unencryptedBlockSize;
  401. }
  402. return $this->unencryptedBlockSizeSigned;
  403. }
  404. /**
  405. * check if the encryption module is able to read the file,
  406. * e.g. if all encryption keys exists
  407. *
  408. * @param string $path
  409. * @param string $uid user for whom we want to check if he can read the file
  410. * @return bool
  411. * @throws DecryptionFailedException
  412. */
  413. public function isReadable($path, $uid) {
  414. $fileKey = $this->keyManager->getFileKey($path, $uid);
  415. if (empty($fileKey)) {
  416. $owner = $this->util->getOwner($path);
  417. if ($owner !== $uid) {
  418. // if it is a shared file we throw a exception with a useful
  419. // error message because in this case it means that the file was
  420. // shared with the user at a point where the user didn't had a
  421. // valid private/public key
  422. $msg = 'Encryption module "' . $this->getDisplayName() .
  423. '" is not able to read ' . $path;
  424. $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
  425. $this->logger->warning($msg);
  426. throw new DecryptionFailedException($msg, $hint);
  427. }
  428. return false;
  429. }
  430. return true;
  431. }
  432. /**
  433. * Initial encryption of all files
  434. *
  435. * @param InputInterface $input
  436. * @param OutputInterface $output write some status information to the terminal during encryption
  437. */
  438. public function encryptAll(InputInterface $input, OutputInterface $output) {
  439. $this->encryptAll->encryptAll($input, $output);
  440. }
  441. /**
  442. * prepare module to perform decrypt all operation
  443. *
  444. * @param InputInterface $input
  445. * @param OutputInterface $output
  446. * @param string $user
  447. * @return bool
  448. */
  449. public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
  450. return $this->decryptAll->prepare($input, $output, $user);
  451. }
  452. /**
  453. * @param string $path
  454. * @return string
  455. */
  456. protected function getPathToRealFile($path) {
  457. $realPath = $path;
  458. $parts = explode('/', $path);
  459. if ($parts[2] === 'files_versions') {
  460. $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
  461. $length = strrpos($realPath, '.');
  462. $realPath = substr($realPath, 0, $length);
  463. }
  464. return $realPath;
  465. }
  466. /**
  467. * remove .part file extension and the ocTransferId from the file to get the
  468. * original file name
  469. *
  470. * @param string $path
  471. * @return string
  472. */
  473. protected function stripPartFileExtension($path) {
  474. if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
  475. $pos = strrpos($path, '.', -6);
  476. $path = substr($path, 0, $pos);
  477. }
  478. return $path;
  479. }
  480. /**
  481. * get owner of a file
  482. *
  483. * @param string $path
  484. * @return string
  485. */
  486. protected function getOwner($path) {
  487. if (!isset($this->owner[$path])) {
  488. $this->owner[$path] = $this->util->getOwner($path);
  489. }
  490. return $this->owner[$path];
  491. }
  492. /**
  493. * Check if the module is ready to be used by that specific user.
  494. * In case a module is not ready - because e.g. key pairs have not been generated
  495. * upon login this method can return false before any operation starts and might
  496. * cause issues during operations.
  497. *
  498. * @param string $user
  499. * @return boolean
  500. * @since 9.1.0
  501. */
  502. public function isReadyForUser($user) {
  503. return $this->keyManager->userHasKeys($user);
  504. }
  505. /**
  506. * We only need a detailed access list if the master key is not enabled
  507. *
  508. * @return bool
  509. */
  510. public function needDetailedAccessList() {
  511. return !$this->util->isMasterKeyEnabled();
  512. }
  513. }