Encryption.php 16 KB

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