Encryption.php 17 KB

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