encryption.php 13 KB

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