1
0

Encryption.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 jknockaert <jasper@knockaert.nl>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author martink-p <47943787+martink-p@users.noreply.github.com>
  11. * @author Morris Jobke <hey@morrisjobke.de>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Thomas Müller <thomas.mueller@tmit.eu>
  15. * @author Vincent Petry <vincent@nextcloud.com>
  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 OC\Files\Stream;
  33. use Icewind\Streams\Wrapper;
  34. use OC\Encryption\Exceptions\EncryptionHeaderKeyExistsException;
  35. use function is_array;
  36. use function stream_context_create;
  37. class Encryption extends Wrapper {
  38. /** @var \OC\Encryption\Util */
  39. protected $util;
  40. /** @var \OC\Encryption\File */
  41. protected $file;
  42. /** @var \OCP\Encryption\IEncryptionModule */
  43. protected $encryptionModule;
  44. /** @var \OC\Files\Storage\Storage */
  45. protected $storage;
  46. /** @var \OC\Files\Storage\Wrapper\Encryption */
  47. protected $encryptionStorage;
  48. /** @var string */
  49. protected $internalPath;
  50. /** @var string */
  51. protected $cache;
  52. /** @var integer */
  53. protected $size;
  54. /** @var integer */
  55. protected $position;
  56. /** @var integer */
  57. protected $unencryptedSize;
  58. /** @var integer */
  59. protected $headerSize;
  60. /** @var integer */
  61. protected $unencryptedBlockSize;
  62. /** @var array */
  63. protected $header;
  64. /** @var string */
  65. protected $fullPath;
  66. /** @var bool */
  67. protected $signed;
  68. /**
  69. * header data returned by the encryption module, will be written to the file
  70. * in case of a write operation
  71. *
  72. * @var array
  73. */
  74. protected $newHeader;
  75. /**
  76. * user who perform the read/write operation null for public access
  77. *
  78. * @var string
  79. */
  80. protected $uid;
  81. /** @var bool */
  82. protected $readOnly;
  83. /** @var bool */
  84. protected $writeFlag;
  85. /** @var array */
  86. protected $expectedContextProperties;
  87. /** @var bool */
  88. protected $fileUpdated;
  89. public function __construct() {
  90. $this->expectedContextProperties = [
  91. 'source',
  92. 'storage',
  93. 'internalPath',
  94. 'fullPath',
  95. 'encryptionModule',
  96. 'header',
  97. 'uid',
  98. 'file',
  99. 'util',
  100. 'size',
  101. 'unencryptedSize',
  102. 'encryptionStorage',
  103. 'headerSize',
  104. 'signed'
  105. ];
  106. }
  107. /**
  108. * Wraps a stream with the provided callbacks
  109. *
  110. * @param resource $source
  111. * @param string $internalPath relative to mount point
  112. * @param string $fullPath relative to data/
  113. * @param array $header
  114. * @param string $uid
  115. * @param \OCP\Encryption\IEncryptionModule $encryptionModule
  116. * @param \OC\Files\Storage\Storage $storage
  117. * @param \OC\Files\Storage\Wrapper\Encryption $encStorage
  118. * @param \OC\Encryption\Util $util
  119. * @param \OC\Encryption\File $file
  120. * @param string $mode
  121. * @param int|float $size
  122. * @param int|float $unencryptedSize
  123. * @param int $headerSize
  124. * @param bool $signed
  125. * @param string $wrapper stream wrapper class
  126. * @return resource
  127. *
  128. * @throws \BadMethodCallException
  129. */
  130. public static function wrap($source, $internalPath, $fullPath, array $header,
  131. $uid,
  132. \OCP\Encryption\IEncryptionModule $encryptionModule,
  133. \OC\Files\Storage\Storage $storage,
  134. \OC\Files\Storage\Wrapper\Encryption $encStorage,
  135. \OC\Encryption\Util $util,
  136. \OC\Encryption\File $file,
  137. $mode,
  138. $size,
  139. $unencryptedSize,
  140. $headerSize,
  141. $signed,
  142. $wrapper = Encryption::class) {
  143. $context = stream_context_create([
  144. 'ocencryption' => [
  145. 'source' => $source,
  146. 'storage' => $storage,
  147. 'internalPath' => $internalPath,
  148. 'fullPath' => $fullPath,
  149. 'encryptionModule' => $encryptionModule,
  150. 'header' => $header,
  151. 'uid' => $uid,
  152. 'util' => $util,
  153. 'file' => $file,
  154. 'size' => $size,
  155. 'unencryptedSize' => $unencryptedSize,
  156. 'encryptionStorage' => $encStorage,
  157. 'headerSize' => $headerSize,
  158. 'signed' => $signed
  159. ]
  160. ]);
  161. return self::wrapSource($source, $context, 'ocencryption', $wrapper, $mode);
  162. }
  163. /**
  164. * add stream wrapper
  165. *
  166. * @param resource|int $source
  167. * @param resource|array $context
  168. * @param string|null $protocol
  169. * @param string|null $class
  170. * @param string $mode
  171. * @return resource
  172. * @throws \BadMethodCallException
  173. */
  174. protected static function wrapSource($source, $context = [], $protocol = null, $class = null, $mode = 'r+') {
  175. try {
  176. if ($protocol === null) {
  177. $protocol = self::getProtocol($class);
  178. }
  179. stream_wrapper_register($protocol, $class);
  180. $context = self::buildContext($protocol, $context, $source);
  181. if (self::isDirectoryHandle($source)) {
  182. $wrapped = opendir($protocol . '://', $context);
  183. } else {
  184. $wrapped = fopen($protocol . '://', $mode, false, $context);
  185. }
  186. } catch (\Exception $e) {
  187. stream_wrapper_unregister($protocol);
  188. throw $e;
  189. }
  190. stream_wrapper_unregister($protocol);
  191. return $wrapped;
  192. }
  193. /**
  194. * @todo this is a copy of \Icewind\Streams\WrapperHandler::buildContext -> combine to one shared method?
  195. */
  196. private static function buildContext($protocol, $context, $source) {
  197. if (is_array($context)) {
  198. $context['source'] = $source;
  199. return stream_context_create([$protocol => $context]);
  200. }
  201. return $context;
  202. }
  203. /**
  204. * Load the source from the stream context and return the context options
  205. *
  206. * @param string|null $name
  207. * @return array
  208. * @throws \BadMethodCallException
  209. */
  210. protected function loadContext($name = null) {
  211. $context = parent::loadContext($name);
  212. foreach ($this->expectedContextProperties as $property) {
  213. if (array_key_exists($property, $context)) {
  214. $this->{$property} = $context[$property];
  215. } else {
  216. throw new \BadMethodCallException('Invalid context, "' . $property . '" options not set');
  217. }
  218. }
  219. return $context;
  220. }
  221. public function stream_open($path, $mode, $options, &$opened_path) {
  222. $this->loadContext('ocencryption');
  223. $this->position = 0;
  224. $this->cache = '';
  225. $this->writeFlag = false;
  226. $this->fileUpdated = false;
  227. if (
  228. $mode === 'w'
  229. || $mode === 'w+'
  230. || $mode === 'wb'
  231. || $mode === 'wb+'
  232. || $mode === 'r+'
  233. || $mode === 'rb+'
  234. ) {
  235. $this->readOnly = false;
  236. } else {
  237. $this->readOnly = true;
  238. }
  239. $sharePath = $this->fullPath;
  240. if (!$this->storage->file_exists($this->internalPath)) {
  241. $sharePath = dirname($sharePath);
  242. }
  243. $accessList = [];
  244. if ($this->encryptionModule->needDetailedAccessList()) {
  245. $accessList = $this->file->getAccessList($sharePath);
  246. }
  247. $this->newHeader = $this->encryptionModule->begin($this->fullPath, $this->uid, $mode, $this->header, $accessList);
  248. $this->unencryptedBlockSize = $this->encryptionModule->getUnencryptedBlockSize($this->signed);
  249. if (
  250. $mode === 'w'
  251. || $mode === 'w+'
  252. || $mode === 'wb'
  253. || $mode === 'wb+'
  254. ) {
  255. // We're writing a new file so start write counter with 0 bytes
  256. $this->unencryptedSize = 0;
  257. $this->writeHeader();
  258. $this->headerSize = $this->util->getHeaderSize();
  259. $this->size = $this->headerSize;
  260. } else {
  261. $this->skipHeader();
  262. }
  263. return true;
  264. }
  265. public function stream_eof() {
  266. return $this->position >= $this->unencryptedSize;
  267. }
  268. public function stream_read($count) {
  269. $result = '';
  270. $count = min($count, $this->unencryptedSize - $this->position);
  271. while ($count > 0) {
  272. $remainingLength = $count;
  273. // update the cache of the current block
  274. $this->readCache();
  275. // determine the relative position in the current block
  276. $blockPosition = ($this->position % $this->unencryptedBlockSize);
  277. // if entire read inside current block then only position needs to be updated
  278. if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
  279. $result .= substr($this->cache, $blockPosition, $remainingLength);
  280. $this->position += $remainingLength;
  281. $count = 0;
  282. // otherwise remainder of current block is fetched, the block is flushed and the position updated
  283. } else {
  284. $result .= substr($this->cache, $blockPosition);
  285. $this->flush();
  286. $this->position += ($this->unencryptedBlockSize - $blockPosition);
  287. $count -= ($this->unencryptedBlockSize - $blockPosition);
  288. }
  289. }
  290. return $result;
  291. }
  292. /**
  293. * stream_read_block
  294. *
  295. * This function is a wrapper for function stream_read.
  296. * It calls stream read until the requested $blockSize was received or no remaining data is present.
  297. * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
  298. * remote storage over the internet and it does not care about the given $blockSize.
  299. *
  300. * @param int $blockSize Length of requested data block in bytes
  301. * @return string Data fetched from stream.
  302. */
  303. private function stream_read_block(int $blockSize): string {
  304. $remaining = $blockSize;
  305. $data = '';
  306. do {
  307. $chunk = parent::stream_read($remaining);
  308. $chunk_len = strlen($chunk);
  309. $data .= $chunk;
  310. $remaining -= $chunk_len;
  311. } while (($remaining > 0) && ($chunk_len > 0));
  312. return $data;
  313. }
  314. public function stream_write($data) {
  315. $length = 0;
  316. // loop over $data to fit it in 6126 sized unencrypted blocks
  317. while (isset($data[0])) {
  318. $remainingLength = strlen($data);
  319. // set the cache to the current 6126 block
  320. $this->readCache();
  321. // for seekable streams the pointer is moved back to the beginning of the encrypted block
  322. // flush will start writing there when the position moves to another block
  323. $positionInFile = (int)floor($this->position / $this->unencryptedBlockSize) *
  324. $this->util->getBlockSize() + $this->headerSize;
  325. $resultFseek = $this->parentStreamSeek($positionInFile);
  326. // only allow writes on seekable streams, or at the end of the encrypted stream
  327. if (!$this->readOnly && ($resultFseek || $positionInFile === $this->size)) {
  328. // switch the writeFlag so flush() will write the block
  329. $this->writeFlag = true;
  330. $this->fileUpdated = true;
  331. // determine the relative position in the current block
  332. $blockPosition = ($this->position % $this->unencryptedBlockSize);
  333. // check if $data fits in current block
  334. // if so, overwrite existing data (if any)
  335. // update position and liberate $data
  336. if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
  337. $this->cache = substr($this->cache, 0, $blockPosition)
  338. . $data . substr($this->cache, $blockPosition + $remainingLength);
  339. $this->position += $remainingLength;
  340. $length += $remainingLength;
  341. $data = '';
  342. // if $data doesn't fit the current block, the fill the current block and reiterate
  343. // after the block is filled, it is flushed and $data is updatedxxx
  344. } else {
  345. $this->cache = substr($this->cache, 0, $blockPosition) .
  346. substr($data, 0, $this->unencryptedBlockSize - $blockPosition);
  347. $this->flush();
  348. $this->position += ($this->unencryptedBlockSize - $blockPosition);
  349. $length += ($this->unencryptedBlockSize - $blockPosition);
  350. $data = substr($data, $this->unencryptedBlockSize - $blockPosition);
  351. }
  352. } else {
  353. $data = '';
  354. }
  355. $this->unencryptedSize = max($this->unencryptedSize, $this->position);
  356. }
  357. return $length;
  358. }
  359. public function stream_tell() {
  360. return $this->position;
  361. }
  362. public function stream_seek($offset, $whence = SEEK_SET) {
  363. $return = false;
  364. switch ($whence) {
  365. case SEEK_SET:
  366. $newPosition = $offset;
  367. break;
  368. case SEEK_CUR:
  369. $newPosition = $this->position + $offset;
  370. break;
  371. case SEEK_END:
  372. $newPosition = $this->unencryptedSize + $offset;
  373. break;
  374. default:
  375. return $return;
  376. }
  377. if ($newPosition > $this->unencryptedSize || $newPosition < 0) {
  378. return $return;
  379. }
  380. $newFilePosition = (int)floor($newPosition / $this->unencryptedBlockSize)
  381. * $this->util->getBlockSize() + $this->headerSize;
  382. $oldFilePosition = parent::stream_tell();
  383. if ($this->parentStreamSeek($newFilePosition)) {
  384. $this->parentStreamSeek($oldFilePosition);
  385. $this->flush();
  386. $this->parentStreamSeek($newFilePosition);
  387. $this->position = $newPosition;
  388. $return = true;
  389. }
  390. return $return;
  391. }
  392. public function stream_close() {
  393. $this->flush('end');
  394. $position = (int)floor($this->position / $this->unencryptedBlockSize);
  395. $remainingData = $this->encryptionModule->end($this->fullPath, $position . 'end');
  396. if ($this->readOnly === false) {
  397. if (!empty($remainingData)) {
  398. parent::stream_write($remainingData);
  399. }
  400. $this->encryptionStorage->updateUnencryptedSize($this->fullPath, $this->unencryptedSize);
  401. }
  402. $result = parent::stream_close();
  403. if ($this->fileUpdated) {
  404. $cache = $this->storage->getCache();
  405. $cacheEntry = $cache->get($this->internalPath);
  406. if ($cacheEntry) {
  407. $version = $cacheEntry['encryptedVersion'] + 1;
  408. $cache->update($cacheEntry->getId(), ['encrypted' => $version, 'encryptedVersion' => $version, 'unencrypted_size' => $this->unencryptedSize]);
  409. }
  410. }
  411. return $result;
  412. }
  413. /**
  414. * write block to file
  415. * @param string $positionPrefix
  416. */
  417. protected function flush($positionPrefix = '') {
  418. // write to disk only when writeFlag was set to 1
  419. if ($this->writeFlag) {
  420. // Disable the file proxies so that encryption is not
  421. // automatically attempted when the file is written to disk -
  422. // we are handling that separately here and we don't want to
  423. // get into an infinite loop
  424. $position = (int)floor($this->position / $this->unencryptedBlockSize);
  425. $encrypted = $this->encryptionModule->encrypt($this->cache, $position . $positionPrefix);
  426. $bytesWritten = parent::stream_write($encrypted);
  427. $this->writeFlag = false;
  428. // Check whether the write concerns the last block
  429. // If so then update the encrypted filesize
  430. // Note that the unencrypted pointer and filesize are NOT yet updated when flush() is called
  431. // We recalculate the encrypted filesize as we do not know the context of calling flush()
  432. $completeBlocksInFile = (int)floor($this->unencryptedSize / $this->unencryptedBlockSize);
  433. if ($completeBlocksInFile === (int)floor($this->position / $this->unencryptedBlockSize)) {
  434. $this->size = $this->util->getBlockSize() * $completeBlocksInFile;
  435. $this->size += $bytesWritten;
  436. $this->size += $this->headerSize;
  437. }
  438. }
  439. // always empty the cache (otherwise readCache() will not fill it with the new block)
  440. $this->cache = '';
  441. }
  442. /**
  443. * read block to file
  444. */
  445. protected function readCache() {
  446. // cache should always be empty string when this function is called
  447. // don't try to fill the cache when trying to write at the end of the unencrypted file when it coincides with new block
  448. if ($this->cache === '' && !($this->position === $this->unencryptedSize && ($this->position % $this->unencryptedBlockSize) === 0)) {
  449. // Get the data from the file handle
  450. $data = $this->stream_read_block($this->util->getBlockSize());
  451. $position = (int)floor($this->position / $this->unencryptedBlockSize);
  452. $numberOfChunks = (int)($this->unencryptedSize / $this->unencryptedBlockSize);
  453. if ($numberOfChunks === $position) {
  454. $position .= 'end';
  455. }
  456. $this->cache = $this->encryptionModule->decrypt($data, $position);
  457. }
  458. }
  459. /**
  460. * write header at beginning of encrypted file
  461. *
  462. * @return int|false
  463. * @throws EncryptionHeaderKeyExistsException if header key is already in use
  464. */
  465. protected function writeHeader() {
  466. $header = $this->util->createHeader($this->newHeader, $this->encryptionModule);
  467. $this->fileUpdated = true;
  468. return parent::stream_write($header);
  469. }
  470. /**
  471. * read first block to skip the header
  472. */
  473. protected function skipHeader() {
  474. $this->stream_read_block($this->headerSize);
  475. }
  476. /**
  477. * call stream_seek() from parent class
  478. *
  479. * @param integer $position
  480. * @return bool
  481. */
  482. protected function parentStreamSeek($position) {
  483. return parent::stream_seek($position);
  484. }
  485. /**
  486. * @param string $path
  487. * @param array $options
  488. * @return bool
  489. */
  490. public function dir_opendir($path, $options) {
  491. return false;
  492. }
  493. }