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.

541 lines
16 KiB

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