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 15KB

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