Encryption.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author J0WI <J0WI@users.noreply.github.com>
  10. * @author jknockaert <jasper@knockaert.nl>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Piotr M <mrow4a@yahoo.com>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  19. * @author Vincent Petry <vincent@nextcloud.com>
  20. * @author Richard Steinmetz <richard@steinmetz.cloud>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Files\Storage\Wrapper;
  38. use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
  39. use OC\Encryption\Update;
  40. use OC\Encryption\Util;
  41. use OC\Files\Cache\CacheEntry;
  42. use OC\Files\Filesystem;
  43. use OC\Files\Mount\Manager;
  44. use OC\Files\ObjectStore\ObjectStoreStorage;
  45. use OC\Files\Storage\LocalTempFileTrait;
  46. use OC\Memcache\ArrayCache;
  47. use OCP\Cache\CappedMemoryCache;
  48. use OCP\Encryption\Exceptions\GenericEncryptionException;
  49. use OCP\Encryption\IFile;
  50. use OCP\Encryption\IManager;
  51. use OCP\Encryption\Keys\IStorage;
  52. use OCP\Files\Cache\ICacheEntry;
  53. use OCP\Files\Mount\IMountPoint;
  54. use OCP\Files\Storage;
  55. use Psr\Log\LoggerInterface;
  56. class Encryption extends Wrapper {
  57. use LocalTempFileTrait;
  58. /** @var string */
  59. private $mountPoint;
  60. /** @var \OC\Encryption\Util */
  61. private $util;
  62. /** @var \OCP\Encryption\IManager */
  63. private $encryptionManager;
  64. private LoggerInterface $logger;
  65. /** @var string */
  66. private $uid;
  67. /** @var array */
  68. protected $unencryptedSize;
  69. /** @var \OCP\Encryption\IFile */
  70. private $fileHelper;
  71. /** @var IMountPoint */
  72. private $mount;
  73. /** @var IStorage */
  74. private $keyStorage;
  75. /** @var Update */
  76. private $update;
  77. /** @var Manager */
  78. private $mountManager;
  79. /** @var array remember for which path we execute the repair step to avoid recursions */
  80. private $fixUnencryptedSizeOf = [];
  81. /** @var ArrayCache */
  82. private $arrayCache;
  83. /** @var CappedMemoryCache<bool> */
  84. private CappedMemoryCache $encryptedPaths;
  85. /**
  86. * @param array $parameters
  87. */
  88. public function __construct(
  89. $parameters,
  90. IManager $encryptionManager = null,
  91. Util $util = null,
  92. LoggerInterface $logger = null,
  93. IFile $fileHelper = null,
  94. $uid = null,
  95. IStorage $keyStorage = null,
  96. Update $update = null,
  97. Manager $mountManager = null,
  98. ArrayCache $arrayCache = null
  99. ) {
  100. $this->mountPoint = $parameters['mountPoint'];
  101. $this->mount = $parameters['mount'];
  102. $this->encryptionManager = $encryptionManager;
  103. $this->util = $util;
  104. $this->logger = $logger;
  105. $this->uid = $uid;
  106. $this->fileHelper = $fileHelper;
  107. $this->keyStorage = $keyStorage;
  108. $this->unencryptedSize = [];
  109. $this->update = $update;
  110. $this->mountManager = $mountManager;
  111. $this->arrayCache = $arrayCache;
  112. $this->encryptedPaths = new CappedMemoryCache();
  113. parent::__construct($parameters);
  114. }
  115. /**
  116. * see https://www.php.net/manual/en/function.filesize.php
  117. * The result for filesize when called on a folder is required to be 0
  118. */
  119. public function filesize($path): false|int|float {
  120. $fullPath = $this->getFullPath($path);
  121. /** @var CacheEntry $info */
  122. $info = $this->getCache()->get($path);
  123. if (isset($this->unencryptedSize[$fullPath])) {
  124. $size = $this->unencryptedSize[$fullPath];
  125. // Update file cache (only if file is already cached).
  126. // Certain files are not cached (e.g. *.part).
  127. if (isset($info['fileid'])) {
  128. if ($info instanceof ICacheEntry) {
  129. $info['encrypted'] = $info['encryptedVersion'];
  130. } else {
  131. /**
  132. * @psalm-suppress RedundantCondition
  133. */
  134. if (!is_array($info)) {
  135. $info = [];
  136. }
  137. $info['encrypted'] = true;
  138. $info = new CacheEntry($info);
  139. }
  140. if ($size !== $info->getUnencryptedSize()) {
  141. $this->getCache()->update($info->getId(), [
  142. 'unencrypted_size' => $size
  143. ]);
  144. }
  145. }
  146. return $size;
  147. }
  148. if (isset($info['fileid']) && $info['encrypted']) {
  149. return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
  150. }
  151. return $this->storage->filesize($path);
  152. }
  153. /**
  154. * @param string $path
  155. * @param array $data
  156. * @return array
  157. */
  158. private function modifyMetaData(string $path, array $data): array {
  159. $fullPath = $this->getFullPath($path);
  160. $info = $this->getCache()->get($path);
  161. if (isset($this->unencryptedSize[$fullPath])) {
  162. $data['encrypted'] = true;
  163. $data['size'] = $this->unencryptedSize[$fullPath];
  164. $data['unencrypted_size'] = $data['size'];
  165. } else {
  166. if (isset($info['fileid']) && $info['encrypted']) {
  167. $data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
  168. $data['encrypted'] = true;
  169. $data['unencrypted_size'] = $data['size'];
  170. }
  171. }
  172. if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
  173. $data['encryptedVersion'] = $info['encryptedVersion'];
  174. }
  175. return $data;
  176. }
  177. public function getMetaData($path) {
  178. $data = $this->storage->getMetaData($path);
  179. if (is_null($data)) {
  180. return null;
  181. }
  182. return $this->modifyMetaData($path, $data);
  183. }
  184. public function getDirectoryContent($directory): \Traversable {
  185. $parent = rtrim($directory, '/');
  186. foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
  187. yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
  188. }
  189. }
  190. /**
  191. * see https://www.php.net/manual/en/function.file_get_contents.php
  192. *
  193. * @param string $path
  194. * @return string
  195. */
  196. public function file_get_contents($path) {
  197. $encryptionModule = $this->getEncryptionModule($path);
  198. if ($encryptionModule) {
  199. $handle = $this->fopen($path, "r");
  200. if (!$handle) {
  201. return false;
  202. }
  203. $data = stream_get_contents($handle);
  204. fclose($handle);
  205. return $data;
  206. }
  207. return $this->storage->file_get_contents($path);
  208. }
  209. /**
  210. * see https://www.php.net/manual/en/function.file_put_contents.php
  211. *
  212. * @param string $path
  213. * @param mixed $data
  214. * @return int|false
  215. */
  216. public function file_put_contents($path, $data) {
  217. // file put content will always be translated to a stream write
  218. $handle = $this->fopen($path, 'w');
  219. if (is_resource($handle)) {
  220. $written = fwrite($handle, $data);
  221. fclose($handle);
  222. return $written;
  223. }
  224. return false;
  225. }
  226. /**
  227. * see https://www.php.net/manual/en/function.unlink.php
  228. *
  229. * @param string $path
  230. * @return bool
  231. */
  232. public function unlink($path) {
  233. $fullPath = $this->getFullPath($path);
  234. if ($this->util->isExcluded($fullPath)) {
  235. return $this->storage->unlink($path);
  236. }
  237. $encryptionModule = $this->getEncryptionModule($path);
  238. if ($encryptionModule) {
  239. $this->keyStorage->deleteAllFileKeys($fullPath);
  240. }
  241. return $this->storage->unlink($path);
  242. }
  243. /**
  244. * see https://www.php.net/manual/en/function.rename.php
  245. *
  246. * @param string $source
  247. * @param string $target
  248. * @return bool
  249. */
  250. public function rename($source, $target) {
  251. $result = $this->storage->rename($source, $target);
  252. if ($result &&
  253. // versions always use the keys from the original file, so we can skip
  254. // this step for versions
  255. $this->isVersion($target) === false &&
  256. $this->encryptionManager->isEnabled()) {
  257. $sourcePath = $this->getFullPath($source);
  258. if (!$this->util->isExcluded($sourcePath)) {
  259. $targetPath = $this->getFullPath($target);
  260. if (isset($this->unencryptedSize[$sourcePath])) {
  261. $this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
  262. }
  263. $this->keyStorage->renameKeys($sourcePath, $targetPath);
  264. $module = $this->getEncryptionModule($target);
  265. if ($module) {
  266. $module->update($targetPath, $this->uid, []);
  267. }
  268. }
  269. }
  270. return $result;
  271. }
  272. /**
  273. * see https://www.php.net/manual/en/function.rmdir.php
  274. *
  275. * @param string $path
  276. * @return bool
  277. */
  278. public function rmdir($path) {
  279. $result = $this->storage->rmdir($path);
  280. $fullPath = $this->getFullPath($path);
  281. if ($result &&
  282. $this->util->isExcluded($fullPath) === false &&
  283. $this->encryptionManager->isEnabled()
  284. ) {
  285. $this->keyStorage->deleteAllFileKeys($fullPath);
  286. }
  287. return $result;
  288. }
  289. /**
  290. * check if a file can be read
  291. *
  292. * @param string $path
  293. * @return bool
  294. */
  295. public function isReadable($path) {
  296. $isReadable = true;
  297. $metaData = $this->getMetaData($path);
  298. if (
  299. !$this->is_dir($path) &&
  300. isset($metaData['encrypted']) &&
  301. $metaData['encrypted'] === true
  302. ) {
  303. $fullPath = $this->getFullPath($path);
  304. $module = $this->getEncryptionModule($path);
  305. $isReadable = $module->isReadable($fullPath, $this->uid);
  306. }
  307. return $this->storage->isReadable($path) && $isReadable;
  308. }
  309. /**
  310. * see https://www.php.net/manual/en/function.copy.php
  311. *
  312. * @param string $source
  313. * @param string $target
  314. */
  315. public function copy($source, $target): bool {
  316. $sourcePath = $this->getFullPath($source);
  317. if ($this->util->isExcluded($sourcePath)) {
  318. return $this->storage->copy($source, $target);
  319. }
  320. // need to stream copy file by file in case we copy between a encrypted
  321. // and a unencrypted storage
  322. $this->unlink($target);
  323. return $this->copyFromStorage($this, $source, $target);
  324. }
  325. /**
  326. * see https://www.php.net/manual/en/function.fopen.php
  327. *
  328. * @param string $path
  329. * @param string $mode
  330. * @return resource|bool
  331. * @throws GenericEncryptionException
  332. * @throws ModuleDoesNotExistsException
  333. */
  334. public function fopen($path, $mode) {
  335. // check if the file is stored in the array cache, this means that we
  336. // copy a file over to the versions folder, in this case we don't want to
  337. // decrypt it
  338. if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
  339. $this->arrayCache->remove('encryption_copy_version_' . $path);
  340. return $this->storage->fopen($path, $mode);
  341. }
  342. $encryptionEnabled = $this->encryptionManager->isEnabled();
  343. $shouldEncrypt = false;
  344. $encryptionModule = null;
  345. $header = $this->getHeader($path);
  346. $signed = isset($header['signed']) && $header['signed'] === 'true';
  347. $fullPath = $this->getFullPath($path);
  348. $encryptionModuleId = $this->util->getEncryptionModuleId($header);
  349. if ($this->util->isExcluded($fullPath) === false) {
  350. $size = $unencryptedSize = 0;
  351. $realFile = $this->util->stripPartialFileExtension($path);
  352. $targetExists = $this->is_file($realFile) || $this->file_exists($path);
  353. $targetIsEncrypted = false;
  354. if ($targetExists) {
  355. // in case the file exists we require the explicit module as
  356. // specified in the file header - otherwise we need to fail hard to
  357. // prevent data loss on client side
  358. if (!empty($encryptionModuleId)) {
  359. $targetIsEncrypted = true;
  360. $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
  361. }
  362. if ($this->file_exists($path)) {
  363. $size = $this->storage->filesize($path);
  364. $unencryptedSize = $this->filesize($path);
  365. } else {
  366. $size = $unencryptedSize = 0;
  367. }
  368. }
  369. try {
  370. if (
  371. $mode === 'w'
  372. || $mode === 'w+'
  373. || $mode === 'wb'
  374. || $mode === 'wb+'
  375. ) {
  376. // if we update a encrypted file with a un-encrypted one we change the db flag
  377. if ($targetIsEncrypted && $encryptionEnabled === false) {
  378. $cache = $this->storage->getCache();
  379. if ($cache) {
  380. $entry = $cache->get($path);
  381. $cache->update($entry->getId(), ['encrypted' => 0]);
  382. }
  383. }
  384. if ($encryptionEnabled) {
  385. // if $encryptionModuleId is empty, the default module will be used
  386. $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
  387. $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
  388. $signed = true;
  389. }
  390. } else {
  391. $info = $this->getCache()->get($path);
  392. // only get encryption module if we found one in the header
  393. // or if file should be encrypted according to the file cache
  394. if (!empty($encryptionModuleId)) {
  395. $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
  396. $shouldEncrypt = true;
  397. } elseif (empty($encryptionModuleId) && $info['encrypted'] === true) {
  398. // we come from a old installation. No header and/or no module defined
  399. // but the file is encrypted. In this case we need to use the
  400. // OC_DEFAULT_MODULE to read the file
  401. $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
  402. $shouldEncrypt = true;
  403. $targetIsEncrypted = true;
  404. }
  405. }
  406. } catch (ModuleDoesNotExistsException $e) {
  407. $this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
  408. 'exception' => $e,
  409. 'app' => 'core',
  410. ]);
  411. }
  412. // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
  413. if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
  414. if (!$targetExists || !$targetIsEncrypted) {
  415. $shouldEncrypt = false;
  416. }
  417. }
  418. if ($shouldEncrypt === true && $encryptionModule !== null) {
  419. $this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
  420. $headerSize = $this->getHeaderSize($path);
  421. $source = $this->storage->fopen($path, $mode);
  422. if (!is_resource($source)) {
  423. return false;
  424. }
  425. $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
  426. $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
  427. $size, $unencryptedSize, $headerSize, $signed);
  428. return $handle;
  429. }
  430. }
  431. return $this->storage->fopen($path, $mode);
  432. }
  433. /**
  434. * perform some plausibility checks if the the unencrypted size is correct.
  435. * If not, we calculate the correct unencrypted size and return it
  436. *
  437. * @param string $path internal path relative to the storage root
  438. * @param int $unencryptedSize size of the unencrypted file
  439. *
  440. * @return int unencrypted size
  441. */
  442. protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
  443. $size = $this->storage->filesize($path);
  444. $result = $unencryptedSize;
  445. if ($unencryptedSize < 0 ||
  446. ($size > 0 && $unencryptedSize === $size) ||
  447. $unencryptedSize > $size
  448. ) {
  449. // check if we already calculate the unencrypted size for the
  450. // given path to avoid recursions
  451. if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
  452. $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
  453. try {
  454. $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
  455. } catch (\Exception $e) {
  456. $this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
  457. }
  458. unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
  459. }
  460. }
  461. return $result;
  462. }
  463. /**
  464. * calculate the unencrypted size
  465. *
  466. * @param string $path internal path relative to the storage root
  467. * @param int $size size of the physical file
  468. * @param int $unencryptedSize size of the unencrypted file
  469. *
  470. * @return int calculated unencrypted size
  471. */
  472. protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int {
  473. $headerSize = $this->getHeaderSize($path);
  474. $header = $this->getHeader($path);
  475. $encryptionModule = $this->getEncryptionModule($path);
  476. $stream = $this->storage->fopen($path, 'r');
  477. // if we couldn't open the file we return the old unencrypted size
  478. if (!is_resource($stream)) {
  479. $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
  480. return $unencryptedSize;
  481. }
  482. $newUnencryptedSize = 0;
  483. $size -= $headerSize;
  484. $blockSize = $this->util->getBlockSize();
  485. // if a header exists we skip it
  486. if ($headerSize > 0) {
  487. $this->fread_block($stream, $headerSize);
  488. }
  489. // fast path, else the calculation for $lastChunkNr is bogus
  490. if ($size === 0) {
  491. return 0;
  492. }
  493. $signed = isset($header['signed']) && $header['signed'] === 'true';
  494. $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
  495. // calculate last chunk nr
  496. // next highest is end of chunks, one subtracted is last one
  497. // we have to read the last chunk, we can't just calculate it (because of padding etc)
  498. $lastChunkNr = ceil($size / $blockSize) - 1;
  499. // calculate last chunk position
  500. $lastChunkPos = ($lastChunkNr * $blockSize);
  501. // try to fseek to the last chunk, if it fails we have to read the whole file
  502. if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
  503. $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
  504. }
  505. $lastChunkContentEncrypted = '';
  506. $count = $blockSize;
  507. while ($count > 0) {
  508. $data = $this->fread_block($stream, $blockSize);
  509. $count = strlen($data);
  510. $lastChunkContentEncrypted .= $data;
  511. if (strlen($lastChunkContentEncrypted) > $blockSize) {
  512. $newUnencryptedSize += $unencryptedBlockSize;
  513. $lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
  514. }
  515. }
  516. fclose($stream);
  517. // we have to decrypt the last chunk to get it actual size
  518. $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
  519. $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
  520. $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
  521. // calc the real file size with the size of the last chunk
  522. $newUnencryptedSize += strlen($decryptedLastChunk);
  523. $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
  524. // write to cache if applicable
  525. $cache = $this->storage->getCache();
  526. if ($cache) {
  527. $entry = $cache->get($path);
  528. $cache->update($entry['fileid'], [
  529. 'unencrypted_size' => $newUnencryptedSize
  530. ]);
  531. }
  532. return $newUnencryptedSize;
  533. }
  534. /**
  535. * fread_block
  536. *
  537. * This function is a wrapper around the fread function. It is based on the
  538. * stream_read_block function from lib/private/Files/Streams/Encryption.php
  539. * It calls stream read until the requested $blockSize was received or no remaining data is present.
  540. * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
  541. * remote storage over the internet and it does not care about the given $blockSize.
  542. *
  543. * @param handle the stream to read from
  544. * @param int $blockSize Length of requested data block in bytes
  545. * @return string Data fetched from stream.
  546. */
  547. private function fread_block($handle, int $blockSize): string {
  548. $remaining = $blockSize;
  549. $data = '';
  550. do {
  551. $chunk = fread($handle, $remaining);
  552. $chunk_len = strlen($chunk);
  553. $data .= $chunk;
  554. $remaining -= $chunk_len;
  555. } while (($remaining > 0) && ($chunk_len > 0));
  556. return $data;
  557. }
  558. /**
  559. * @param Storage\IStorage $sourceStorage
  560. * @param string $sourceInternalPath
  561. * @param string $targetInternalPath
  562. * @param bool $preserveMtime
  563. * @return bool
  564. */
  565. public function moveFromStorage(
  566. Storage\IStorage $sourceStorage,
  567. $sourceInternalPath,
  568. $targetInternalPath,
  569. $preserveMtime = true
  570. ) {
  571. if ($sourceStorage === $this) {
  572. return $this->rename($sourceInternalPath, $targetInternalPath);
  573. }
  574. // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
  575. // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
  576. // - copy the file cache update from $this->copyBetweenStorage to this method
  577. // - copy the copyKeys() call from $this->copyBetweenStorage to this method
  578. // - remove $this->copyBetweenStorage
  579. if (!$sourceStorage->isDeletable($sourceInternalPath)) {
  580. return false;
  581. }
  582. $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
  583. if ($result) {
  584. if ($sourceStorage->is_dir($sourceInternalPath)) {
  585. $result &= $sourceStorage->rmdir($sourceInternalPath);
  586. } else {
  587. $result &= $sourceStorage->unlink($sourceInternalPath);
  588. }
  589. }
  590. return $result;
  591. }
  592. /**
  593. * @param Storage\IStorage $sourceStorage
  594. * @param string $sourceInternalPath
  595. * @param string $targetInternalPath
  596. * @param bool $preserveMtime
  597. * @param bool $isRename
  598. * @return bool
  599. */
  600. public function copyFromStorage(
  601. Storage\IStorage $sourceStorage,
  602. $sourceInternalPath,
  603. $targetInternalPath,
  604. $preserveMtime = false,
  605. $isRename = false
  606. ) {
  607. // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
  608. // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
  609. // - copy the file cache update from $this->copyBetweenStorage to this method
  610. // - copy the copyKeys() call from $this->copyBetweenStorage to this method
  611. // - remove $this->copyBetweenStorage
  612. return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
  613. }
  614. /**
  615. * Update the encrypted cache version in the database
  616. *
  617. * @param Storage\IStorage $sourceStorage
  618. * @param string $sourceInternalPath
  619. * @param string $targetInternalPath
  620. * @param bool $isRename
  621. * @param bool $keepEncryptionVersion
  622. */
  623. private function updateEncryptedVersion(
  624. Storage\IStorage $sourceStorage,
  625. $sourceInternalPath,
  626. $targetInternalPath,
  627. $isRename,
  628. $keepEncryptionVersion
  629. ) {
  630. $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
  631. $cacheInformation = [
  632. 'encrypted' => $isEncrypted,
  633. ];
  634. if ($isEncrypted) {
  635. $sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
  636. $targetCacheEntry = $this->getCache()->get($targetInternalPath);
  637. // Rename of the cache already happened, so we do the cleanup on the target
  638. if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
  639. $encryptedVersion = $targetCacheEntry['encryptedVersion'];
  640. $isRename = false;
  641. } else {
  642. $encryptedVersion = $sourceCacheEntry['encryptedVersion'];
  643. }
  644. // In case of a move operation from an unencrypted to an encrypted
  645. // storage the old encrypted version would stay with "0" while the
  646. // correct value would be "1". Thus we manually set the value to "1"
  647. // for those cases.
  648. // See also https://github.com/owncloud/core/issues/23078
  649. if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
  650. $encryptedVersion = 1;
  651. }
  652. $cacheInformation['encryptedVersion'] = $encryptedVersion;
  653. }
  654. // in case of a rename we need to manipulate the source cache because
  655. // this information will be kept for the new target
  656. if ($isRename) {
  657. $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
  658. } else {
  659. $this->getCache()->put($targetInternalPath, $cacheInformation);
  660. }
  661. }
  662. /**
  663. * copy file between two storages
  664. *
  665. * @param Storage\IStorage $sourceStorage
  666. * @param string $sourceInternalPath
  667. * @param string $targetInternalPath
  668. * @param bool $preserveMtime
  669. * @param bool $isRename
  670. * @return bool
  671. * @throws \Exception
  672. */
  673. private function copyBetweenStorage(
  674. Storage\IStorage $sourceStorage,
  675. $sourceInternalPath,
  676. $targetInternalPath,
  677. $preserveMtime,
  678. $isRename
  679. ) {
  680. // for versions we have nothing to do, because versions should always use the
  681. // key from the original file. Just create a 1:1 copy and done
  682. if ($this->isVersion($targetInternalPath) ||
  683. $this->isVersion($sourceInternalPath)) {
  684. // remember that we try to create a version so that we can detect it during
  685. // fopen($sourceInternalPath) and by-pass the encryption in order to
  686. // create a 1:1 copy of the file
  687. $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
  688. $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  689. $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
  690. if ($result) {
  691. $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
  692. // make sure that we update the unencrypted size for the version
  693. if (isset($info['encrypted']) && $info['encrypted'] === true) {
  694. $this->updateUnencryptedSize(
  695. $this->getFullPath($targetInternalPath),
  696. $info->getUnencryptedSize()
  697. );
  698. }
  699. $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
  700. }
  701. return $result;
  702. }
  703. // first copy the keys that we reuse the existing file key on the target location
  704. // and don't create a new one which would break versions for example.
  705. $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
  706. if (count($mount) === 1) {
  707. $mountPoint = $mount[0]->getMountPoint();
  708. $source = $mountPoint . '/' . $sourceInternalPath;
  709. $target = $this->getFullPath($targetInternalPath);
  710. $this->copyKeys($source, $target);
  711. } else {
  712. $this->logger->error('Could not find mount point, can\'t keep encryption keys');
  713. }
  714. if ($sourceStorage->is_dir($sourceInternalPath)) {
  715. $dh = $sourceStorage->opendir($sourceInternalPath);
  716. if (!$this->is_dir($targetInternalPath)) {
  717. $result = $this->mkdir($targetInternalPath);
  718. } else {
  719. $result = true;
  720. }
  721. if (is_resource($dh)) {
  722. while ($result and ($file = readdir($dh)) !== false) {
  723. if (!Filesystem::isIgnoredDir($file)) {
  724. $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
  725. }
  726. }
  727. }
  728. } else {
  729. try {
  730. $source = $sourceStorage->fopen($sourceInternalPath, 'r');
  731. $target = $this->fopen($targetInternalPath, 'w');
  732. [, $result] = \OC_Helper::streamCopy($source, $target);
  733. } finally {
  734. if (is_resource($source)) {
  735. fclose($source);
  736. }
  737. if (is_resource($target)) {
  738. fclose($target);
  739. }
  740. }
  741. if ($result) {
  742. if ($preserveMtime) {
  743. $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
  744. }
  745. $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
  746. } else {
  747. // delete partially written target file
  748. $this->unlink($targetInternalPath);
  749. // delete cache entry that was created by fopen
  750. $this->getCache()->remove($targetInternalPath);
  751. }
  752. }
  753. return (bool)$result;
  754. }
  755. public function getLocalFile($path) {
  756. if ($this->encryptionManager->isEnabled()) {
  757. $cachedFile = $this->getCachedFile($path);
  758. if (is_string($cachedFile)) {
  759. return $cachedFile;
  760. }
  761. }
  762. return $this->storage->getLocalFile($path);
  763. }
  764. public function isLocal() {
  765. if ($this->encryptionManager->isEnabled()) {
  766. return false;
  767. }
  768. return $this->storage->isLocal();
  769. }
  770. public function stat($path) {
  771. $stat = $this->storage->stat($path);
  772. if (!$stat) {
  773. return false;
  774. }
  775. $fileSize = $this->filesize($path);
  776. $stat['size'] = $fileSize;
  777. $stat[7] = $fileSize;
  778. $stat['hasHeader'] = $this->getHeaderSize($path) > 0;
  779. return $stat;
  780. }
  781. public function hash($type, $path, $raw = false) {
  782. $fh = $this->fopen($path, 'rb');
  783. $ctx = hash_init($type);
  784. hash_update_stream($ctx, $fh);
  785. fclose($fh);
  786. return hash_final($ctx, $raw);
  787. }
  788. /**
  789. * return full path, including mount point
  790. *
  791. * @param string $path relative to mount point
  792. * @return string full path including mount point
  793. */
  794. protected function getFullPath($path) {
  795. return Filesystem::normalizePath($this->mountPoint . '/' . $path);
  796. }
  797. /**
  798. * read first block of encrypted file, typically this will contain the
  799. * encryption header
  800. *
  801. * @param string $path
  802. * @return string
  803. */
  804. protected function readFirstBlock($path) {
  805. $firstBlock = '';
  806. if ($this->storage->is_file($path)) {
  807. $handle = $this->storage->fopen($path, 'r');
  808. $firstBlock = fread($handle, $this->util->getHeaderSize());
  809. fclose($handle);
  810. }
  811. return $firstBlock;
  812. }
  813. /**
  814. * return header size of given file
  815. *
  816. * @param string $path
  817. * @return int
  818. */
  819. protected function getHeaderSize($path) {
  820. $headerSize = 0;
  821. $realFile = $this->util->stripPartialFileExtension($path);
  822. if ($this->storage->is_file($realFile)) {
  823. $path = $realFile;
  824. }
  825. $firstBlock = $this->readFirstBlock($path);
  826. if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
  827. $headerSize = $this->util->getHeaderSize();
  828. }
  829. return $headerSize;
  830. }
  831. /**
  832. * parse raw header to array
  833. *
  834. * @param string $rawHeader
  835. * @return array
  836. */
  837. protected function parseRawHeader($rawHeader) {
  838. $result = [];
  839. if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
  840. $header = $rawHeader;
  841. $endAt = strpos($header, Util::HEADER_END);
  842. if ($endAt !== false) {
  843. $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
  844. // +1 to not start with an ':' which would result in empty element at the beginning
  845. $exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
  846. $element = array_shift($exploded);
  847. while ($element !== Util::HEADER_END) {
  848. $result[$element] = array_shift($exploded);
  849. $element = array_shift($exploded);
  850. }
  851. }
  852. }
  853. return $result;
  854. }
  855. /**
  856. * read header from file
  857. *
  858. * @param string $path
  859. * @return array
  860. */
  861. protected function getHeader($path) {
  862. $realFile = $this->util->stripPartialFileExtension($path);
  863. $exists = $this->storage->is_file($realFile);
  864. if ($exists) {
  865. $path = $realFile;
  866. }
  867. $result = [];
  868. $isEncrypted = $this->encryptedPaths->get($realFile);
  869. if (is_null($isEncrypted)) {
  870. $info = $this->getCache()->get($path);
  871. $isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
  872. }
  873. if ($isEncrypted) {
  874. $firstBlock = $this->readFirstBlock($path);
  875. $result = $this->parseRawHeader($firstBlock);
  876. // if the header doesn't contain a encryption module we check if it is a
  877. // legacy file. If true, we add the default encryption module
  878. if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
  879. $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
  880. }
  881. }
  882. return $result;
  883. }
  884. /**
  885. * read encryption module needed to read/write the file located at $path
  886. *
  887. * @param string $path
  888. * @return null|\OCP\Encryption\IEncryptionModule
  889. * @throws ModuleDoesNotExistsException
  890. * @throws \Exception
  891. */
  892. protected function getEncryptionModule($path) {
  893. $encryptionModule = null;
  894. $header = $this->getHeader($path);
  895. $encryptionModuleId = $this->util->getEncryptionModuleId($header);
  896. if (!empty($encryptionModuleId)) {
  897. try {
  898. $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
  899. } catch (ModuleDoesNotExistsException $e) {
  900. $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
  901. throw $e;
  902. }
  903. }
  904. return $encryptionModule;
  905. }
  906. /**
  907. * @param string $path
  908. * @param int $unencryptedSize
  909. */
  910. public function updateUnencryptedSize($path, $unencryptedSize) {
  911. $this->unencryptedSize[$path] = $unencryptedSize;
  912. }
  913. /**
  914. * copy keys to new location
  915. *
  916. * @param string $source path relative to data/
  917. * @param string $target path relative to data/
  918. * @return bool
  919. */
  920. protected function copyKeys($source, $target) {
  921. if (!$this->util->isExcluded($source)) {
  922. return $this->keyStorage->copyKeys($source, $target);
  923. }
  924. return false;
  925. }
  926. /**
  927. * check if path points to a files version
  928. *
  929. * @param $path
  930. * @return bool
  931. */
  932. protected function isVersion($path) {
  933. $normalized = Filesystem::normalizePath($path);
  934. return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
  935. }
  936. /**
  937. * check if the given storage should be encrypted or not
  938. *
  939. * @param $path
  940. * @return bool
  941. */
  942. protected function shouldEncrypt($path) {
  943. $fullPath = $this->getFullPath($path);
  944. $mountPointConfig = $this->mount->getOption('encrypt', true);
  945. if ($mountPointConfig === false) {
  946. return false;
  947. }
  948. try {
  949. $encryptionModule = $this->getEncryptionModule($fullPath);
  950. } catch (ModuleDoesNotExistsException $e) {
  951. return false;
  952. }
  953. if ($encryptionModule === null) {
  954. $encryptionModule = $this->encryptionManager->getEncryptionModule();
  955. }
  956. return $encryptionModule->shouldEncrypt($fullPath);
  957. }
  958. public function writeStream(string $path, $stream, int $size = null): int {
  959. // always fall back to fopen
  960. $target = $this->fopen($path, 'w');
  961. [$count, $result] = \OC_Helper::streamCopy($stream, $target);
  962. fclose($stream);
  963. fclose($target);
  964. // object store, stores the size after write and doesn't update this during scan
  965. // manually store the unencrypted size
  966. if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class) && $this->shouldEncrypt($path)) {
  967. $this->getCache()->put($path, ['unencrypted_size' => $count]);
  968. }
  969. return $count;
  970. }
  971. public function clearIsEncryptedCache(): void {
  972. $this->encryptedPaths->clear();
  973. }
  974. }