Encryption.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. public function stream_write($data) {
  273. $length = 0;
  274. // loop over $data to fit it in 6126 sized unencrypted blocks
  275. while (isset($data[0])) {
  276. $remainingLength = strlen($data);
  277. // set the cache to the current 6126 block
  278. $this->readCache();
  279. // for seekable streams the pointer is moved back to the beginning of the encrypted block
  280. // flush will start writing there when the position moves to another block
  281. $positionInFile = (int)floor($this->position / $this->unencryptedBlockSize) *
  282. $this->util->getBlockSize() + $this->headerSize;
  283. $resultFseek = $this->parentStreamSeek($positionInFile);
  284. // only allow writes on seekable streams, or at the end of the encrypted stream
  285. if (!$this->readOnly && ($resultFseek || $positionInFile === $this->size)) {
  286. // switch the writeFlag so flush() will write the block
  287. $this->writeFlag = true;
  288. $this->fileUpdated = true;
  289. // determine the relative position in the current block
  290. $blockPosition = ($this->position % $this->unencryptedBlockSize);
  291. // check if $data fits in current block
  292. // if so, overwrite existing data (if any)
  293. // update position and liberate $data
  294. if ($remainingLength < ($this->unencryptedBlockSize - $blockPosition)) {
  295. $this->cache = substr($this->cache, 0, $blockPosition)
  296. . $data . substr($this->cache, $blockPosition + $remainingLength);
  297. $this->position += $remainingLength;
  298. $length += $remainingLength;
  299. $data = '';
  300. // if $data doesn't fit the current block, the fill the current block and reiterate
  301. // after the block is filled, it is flushed and $data is updatedxxx
  302. } else {
  303. $this->cache = substr($this->cache, 0, $blockPosition) .
  304. substr($data, 0, $this->unencryptedBlockSize - $blockPosition);
  305. $this->flush();
  306. $this->position += ($this->unencryptedBlockSize - $blockPosition);
  307. $length += ($this->unencryptedBlockSize - $blockPosition);
  308. $data = substr($data, $this->unencryptedBlockSize - $blockPosition);
  309. }
  310. } else {
  311. $data = '';
  312. }
  313. $this->unencryptedSize = max($this->unencryptedSize, $this->position);
  314. }
  315. return $length;
  316. }
  317. public function stream_tell() {
  318. return $this->position;
  319. }
  320. public function stream_seek($offset, $whence = SEEK_SET) {
  321. $return = false;
  322. switch ($whence) {
  323. case SEEK_SET:
  324. $newPosition = $offset;
  325. break;
  326. case SEEK_CUR:
  327. $newPosition = $this->position + $offset;
  328. break;
  329. case SEEK_END:
  330. $newPosition = $this->unencryptedSize + $offset;
  331. break;
  332. default:
  333. return $return;
  334. }
  335. if ($newPosition > $this->unencryptedSize || $newPosition < 0) {
  336. return $return;
  337. }
  338. $newFilePosition = floor($newPosition / $this->unencryptedBlockSize)
  339. * $this->util->getBlockSize() + $this->headerSize;
  340. $oldFilePosition = parent::stream_tell();
  341. if ($this->parentStreamSeek($newFilePosition)) {
  342. $this->parentStreamSeek($oldFilePosition);
  343. $this->flush();
  344. $this->parentStreamSeek($newFilePosition);
  345. $this->position = $newPosition;
  346. $return = true;
  347. }
  348. return $return;
  349. }
  350. public function stream_close() {
  351. $this->flush('end');
  352. $position = (int)floor($this->position/$this->unencryptedBlockSize);
  353. $remainingData = $this->encryptionModule->end($this->fullPath, $position . 'end');
  354. if ($this->readOnly === false) {
  355. if(!empty($remainingData)) {
  356. parent::stream_write($remainingData);
  357. }
  358. $this->encryptionStorage->updateUnencryptedSize($this->fullPath, $this->unencryptedSize);
  359. }
  360. $result = parent::stream_close();
  361. if ($this->fileUpdated) {
  362. $cache = $this->storage->getCache();
  363. $cacheEntry = $cache->get($this->internalPath);
  364. if ($cacheEntry) {
  365. $version = $cacheEntry['encryptedVersion'] + 1;
  366. $cache->update($cacheEntry->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
  367. }
  368. }
  369. return $result;
  370. }
  371. /**
  372. * write block to file
  373. * @param string $positionPrefix
  374. */
  375. protected function flush($positionPrefix = '') {
  376. // write to disk only when writeFlag was set to 1
  377. if ($this->writeFlag) {
  378. // Disable the file proxies so that encryption is not
  379. // automatically attempted when the file is written to disk -
  380. // we are handling that separately here and we don't want to
  381. // get into an infinite loop
  382. $position = (int)floor($this->position/$this->unencryptedBlockSize);
  383. $encrypted = $this->encryptionModule->encrypt($this->cache, $position . $positionPrefix);
  384. $bytesWritten = parent::stream_write($encrypted);
  385. $this->writeFlag = false;
  386. // Check whether the write concerns the last block
  387. // If so then update the encrypted filesize
  388. // Note that the unencrypted pointer and filesize are NOT yet updated when flush() is called
  389. // We recalculate the encrypted filesize as we do not know the context of calling flush()
  390. $completeBlocksInFile=(int)floor($this->unencryptedSize/$this->unencryptedBlockSize);
  391. if ($completeBlocksInFile === (int)floor($this->position/$this->unencryptedBlockSize)) {
  392. $this->size = $this->util->getBlockSize() * $completeBlocksInFile;
  393. $this->size += $bytesWritten;
  394. $this->size += $this->headerSize;
  395. }
  396. }
  397. // always empty the cache (otherwise readCache() will not fill it with the new block)
  398. $this->cache = '';
  399. }
  400. /**
  401. * read block to file
  402. */
  403. protected function readCache() {
  404. // cache should always be empty string when this function is called
  405. // don't try to fill the cache when trying to write at the end of the unencrypted file when it coincides with new block
  406. if ($this->cache === '' && !($this->position === $this->unencryptedSize && ($this->position % $this->unencryptedBlockSize) === 0)) {
  407. // Get the data from the file handle
  408. $data = parent::stream_read($this->util->getBlockSize());
  409. $position = (int)floor($this->position/$this->unencryptedBlockSize);
  410. $numberOfChunks = (int)($this->unencryptedSize / $this->unencryptedBlockSize);
  411. if($numberOfChunks === $position) {
  412. $position .= 'end';
  413. }
  414. $this->cache = $this->encryptionModule->decrypt($data, $position);
  415. }
  416. }
  417. /**
  418. * write header at beginning of encrypted file
  419. *
  420. * @return integer
  421. * @throws EncryptionHeaderKeyExistsException if header key is already in use
  422. */
  423. protected function writeHeader() {
  424. $header = $this->util->createHeader($this->newHeader, $this->encryptionModule);
  425. return parent::stream_write($header);
  426. }
  427. /**
  428. * read first block to skip the header
  429. */
  430. protected function skipHeader() {
  431. parent::stream_read($this->headerSize);
  432. }
  433. /**
  434. * call stream_seek() from parent class
  435. *
  436. * @param integer $position
  437. * @return bool
  438. */
  439. protected function parentStreamSeek($position) {
  440. return parent::stream_seek($position);
  441. }
  442. /**
  443. * @param string $path
  444. * @param array $options
  445. * @return bool
  446. */
  447. public function dir_opendir($path, $options) {
  448. return false;
  449. }
  450. }