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.

597 lines
17 KiB

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