Encryption.php 33 KB

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