encryption.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. /**
  3. * @author Björn Schießle <schiessle@owncloud.com>
  4. * @author Clark Tomlinson <fallen013@gmail.com>
  5. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  6. * @author Joas Schilling <nickvergessen@owncloud.com>
  7. * @author Lukas Reschke <lukas@owncloud.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Thomas Müller <thomas.mueller@tmit.eu>
  10. *
  11. * @copyright Copyright (c) 2015, ownCloud, Inc.
  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 OCA\Encryption\Exceptions\PublicKeyMissingException;
  30. use OCA\Encryption\Util;
  31. use OCP\Encryption\IEncryptionModule;
  32. use OCA\Encryption\KeyManager;
  33. use OCP\IL10N;
  34. use OCP\ILogger;
  35. use Symfony\Component\Console\Input\InputInterface;
  36. use Symfony\Component\Console\Output\OutputInterface;
  37. class Encryption implements IEncryptionModule {
  38. const ID = 'OC_DEFAULT_MODULE';
  39. const DISPLAY_NAME = 'Default encryption module';
  40. /**
  41. * @var Crypt
  42. */
  43. private $crypt;
  44. /** @var string */
  45. private $cipher;
  46. /** @var string */
  47. private $path;
  48. /** @var string */
  49. private $user;
  50. /** @var string */
  51. private $fileKey;
  52. /** @var string */
  53. private $writeCache;
  54. /** @var KeyManager */
  55. private $keyManager;
  56. /** @var array */
  57. private $accessList;
  58. /** @var boolean */
  59. private $isWriteOperation;
  60. /** @var Util */
  61. private $util;
  62. /** @var ILogger */
  63. private $logger;
  64. /** @var IL10N */
  65. private $l;
  66. /** @var EncryptAll */
  67. private $encryptAll;
  68. /**
  69. *
  70. * @param Crypt $crypt
  71. * @param KeyManager $keyManager
  72. * @param Util $util
  73. * @param EncryptAll $encryptAll
  74. * @param ILogger $logger
  75. * @param IL10N $il10n
  76. */
  77. public function __construct(Crypt $crypt,
  78. KeyManager $keyManager,
  79. Util $util,
  80. EncryptAll $encryptAll,
  81. ILogger $logger,
  82. IL10N $il10n) {
  83. $this->crypt = $crypt;
  84. $this->keyManager = $keyManager;
  85. $this->util = $util;
  86. $this->encryptAll = $encryptAll;
  87. $this->logger = $logger;
  88. $this->l = $il10n;
  89. }
  90. /**
  91. * @return string defining the technical unique id
  92. */
  93. public function getId() {
  94. return self::ID;
  95. }
  96. /**
  97. * In comparison to getKey() this function returns a human readable (maybe translated) name
  98. *
  99. * @return string
  100. */
  101. public function getDisplayName() {
  102. return self::DISPLAY_NAME;
  103. }
  104. /**
  105. * start receiving chunks from a file. This is the place where you can
  106. * perform some initial step before starting encrypting/decrypting the
  107. * chunks
  108. *
  109. * @param string $path to the file
  110. * @param string $user who read/write the file
  111. * @param string $mode php stream open mode
  112. * @param array $header contains the header data read from the file
  113. * @param array $accessList who has access to the file contains the key 'users' and 'public'
  114. *
  115. * @return array $header contain data as key-value pairs which should be
  116. * written to the header, in case of a write operation
  117. * or if no additional data is needed return a empty array
  118. */
  119. public function begin($path, $user, $mode, array $header, array $accessList) {
  120. $this->path = $this->getPathToRealFile($path);
  121. $this->accessList = $accessList;
  122. $this->user = $user;
  123. $this->isWriteOperation = false;
  124. $this->writeCache = '';
  125. $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
  126. if (
  127. $mode === 'w'
  128. || $mode === 'w+'
  129. || $mode === 'wb'
  130. || $mode === 'wb+'
  131. ) {
  132. $this->isWriteOperation = true;
  133. if (empty($this->fileKey)) {
  134. $this->fileKey = $this->crypt->generateFileKey();
  135. }
  136. }
  137. if (isset($header['cipher'])) {
  138. $this->cipher = $header['cipher'];
  139. } elseif ($this->isWriteOperation) {
  140. $this->cipher = $this->crypt->getCipher();
  141. } else {
  142. // if we read a file without a header we fall-back to the legacy cipher
  143. // which was used in <=oC6
  144. $this->cipher = $this->crypt->getLegacyCipher();
  145. }
  146. return array('cipher' => $this->cipher);
  147. }
  148. /**
  149. * last chunk received. This is the place where you can perform some final
  150. * operation and return some remaining data if something is left in your
  151. * buffer.
  152. *
  153. * @param string $path to the file
  154. * @return string remained data which should be written to the file in case
  155. * of a write operation
  156. * @throws PublicKeyMissingException
  157. * @throws \Exception
  158. * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
  159. */
  160. public function end($path) {
  161. $result = '';
  162. if ($this->isWriteOperation) {
  163. if (!empty($this->writeCache)) {
  164. $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey);
  165. $this->writeCache = '';
  166. }
  167. $publicKeys = array();
  168. foreach ($this->accessList['users'] as $uid) {
  169. try {
  170. $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
  171. } catch (PublicKeyMissingException $e) {
  172. $this->logger->warning(
  173. 'no public key found for user "{uid}", user will not be able to read the file',
  174. ['app' => 'encryption', 'uid' => $uid]
  175. );
  176. // if the public key of the owner is missing we should fail
  177. if ($uid === $this->user) {
  178. throw $e;
  179. }
  180. }
  181. }
  182. $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->user);
  183. $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
  184. $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
  185. }
  186. return $result;
  187. }
  188. /**
  189. * encrypt data
  190. *
  191. * @param string $data you want to encrypt
  192. * @return mixed encrypted data
  193. */
  194. public function encrypt($data) {
  195. // If extra data is left over from the last round, make sure it
  196. // is integrated into the next 6126 / 8192 block
  197. if ($this->writeCache) {
  198. // Concat writeCache to start of $data
  199. $data = $this->writeCache . $data;
  200. // Clear the write cache, ready for reuse - it has been
  201. // flushed and its old contents processed
  202. $this->writeCache = '';
  203. }
  204. $encrypted = '';
  205. // While there still remains some data to be processed & written
  206. while (strlen($data) > 0) {
  207. // Remaining length for this iteration, not of the
  208. // entire file (may be greater than 8192 bytes)
  209. $remainingLength = strlen($data);
  210. // If data remaining to be written is less than the
  211. // size of 1 6126 byte block
  212. if ($remainingLength < 6126) {
  213. // Set writeCache to contents of $data
  214. // The writeCache will be carried over to the
  215. // next write round, and added to the start of
  216. // $data to ensure that written blocks are
  217. // always the correct length. If there is still
  218. // data in writeCache after the writing round
  219. // has finished, then the data will be written
  220. // to disk by $this->flush().
  221. $this->writeCache = $data;
  222. // Clear $data ready for next round
  223. $data = '';
  224. } else {
  225. // Read the chunk from the start of $data
  226. $chunk = substr($data, 0, 6126);
  227. $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey);
  228. // Remove the chunk we just processed from
  229. // $data, leaving only unprocessed data in $data
  230. // var, for handling on the next round
  231. $data = substr($data, 6126);
  232. }
  233. }
  234. return $encrypted;
  235. }
  236. /**
  237. * decrypt data
  238. *
  239. * @param string $data you want to decrypt
  240. * @return mixed decrypted data
  241. * @throws DecryptionFailedException
  242. */
  243. public function decrypt($data) {
  244. if (empty($this->fileKey)) {
  245. $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
  246. $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.');
  247. $this->logger->error($msg);
  248. throw new DecryptionFailedException($msg, $hint);
  249. }
  250. $result = '';
  251. if (!empty($data)) {
  252. $result = $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher);
  253. }
  254. return $result;
  255. }
  256. /**
  257. * update encrypted file, e.g. give additional users access to the file
  258. *
  259. * @param string $path path to the file which should be updated
  260. * @param string $uid of the user who performs the operation
  261. * @param array $accessList who has access to the file contains the key 'users' and 'public'
  262. * @return boolean
  263. */
  264. public function update($path, $uid, array $accessList) {
  265. $fileKey = $this->keyManager->getFileKey($path, $uid);
  266. if (!empty($fileKey)) {
  267. $publicKeys = array();
  268. foreach ($accessList['users'] as $user) {
  269. $publicKeys[$user] = $this->keyManager->getPublicKey($user);
  270. }
  271. $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $uid);
  272. $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
  273. $this->keyManager->deleteAllFileKeys($path);
  274. $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
  275. } else {
  276. $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
  277. array('file' => $path, 'app' => 'encryption'));
  278. return false;
  279. }
  280. return true;
  281. }
  282. /**
  283. * should the file be encrypted or not
  284. *
  285. * @param string $path
  286. * @return boolean
  287. */
  288. public function shouldEncrypt($path) {
  289. $parts = explode('/', $path);
  290. if (count($parts) < 4) {
  291. return false;
  292. }
  293. if ($parts[2] == 'files') {
  294. return true;
  295. }
  296. if ($parts[2] == 'files_versions') {
  297. return true;
  298. }
  299. if ($parts[2] == 'files_trashbin') {
  300. return true;
  301. }
  302. return false;
  303. }
  304. /**
  305. * get size of the unencrypted payload per block.
  306. * ownCloud read/write files with a block size of 8192 byte
  307. *
  308. * @return integer
  309. */
  310. public function getUnencryptedBlockSize() {
  311. return 6126;
  312. }
  313. /**
  314. * check if the encryption module is able to read the file,
  315. * e.g. if all encryption keys exists
  316. *
  317. * @param string $path
  318. * @param string $uid user for whom we want to check if he can read the file
  319. * @return bool
  320. * @throws DecryptionFailedException
  321. */
  322. public function isReadable($path, $uid) {
  323. $fileKey = $this->keyManager->getFileKey($path, $uid);
  324. if (empty($fileKey)) {
  325. $owner = $this->util->getOwner($path);
  326. if ($owner !== $uid) {
  327. // if it is a shared file we throw a exception with a useful
  328. // error message because in this case it means that the file was
  329. // shared with the user at a point where the user didn't had a
  330. // valid private/public key
  331. $msg = 'Encryption module "' . $this->getDisplayName() .
  332. '" is not able to read ' . $path;
  333. $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.');
  334. $this->logger->warning($msg);
  335. throw new DecryptionFailedException($msg, $hint);
  336. }
  337. return false;
  338. }
  339. return true;
  340. }
  341. /**
  342. * Initial encryption of all files
  343. *
  344. * @param InputInterface $input
  345. * @param OutputInterface $output write some status information to the terminal during encryption
  346. * @return bool
  347. */
  348. public function encryptAll(InputInterface $input, OutputInterface $output) {
  349. return $this->encryptAll->encryptAll($input, $output);
  350. }
  351. /**
  352. * @param string $path
  353. * @return string
  354. */
  355. protected function getPathToRealFile($path) {
  356. $realPath = $path;
  357. $parts = explode('/', $path);
  358. if ($parts[2] === 'files_versions') {
  359. $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
  360. $length = strrpos($realPath, '.');
  361. $realPath = substr($realPath, 0, $length);
  362. }
  363. return $realPath;
  364. }
  365. }