You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Encryption.php 17KB

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