Encryption.php 15 KB

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