You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Encryption.php 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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 Joas Schilling <coding@schilljs.com>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Piotr M <mrow4a@yahoo.com>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  18. * @author Vincent Petry <vincent@nextcloud.com>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OC\Files\Storage\Wrapper;
  36. use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
  37. use OC\Encryption\Update;
  38. use OC\Encryption\Util;
  39. use OC\Files\Cache\CacheEntry;
  40. use OC\Files\Filesystem;
  41. use OC\Files\Mount\Manager;
  42. use OC\Files\Storage\LocalTempFileTrait;
  43. use OC\Memcache\ArrayCache;
  44. use OCP\Encryption\Exceptions\GenericEncryptionException;
  45. use OCP\Encryption\IFile;
  46. use OCP\Encryption\IManager;
  47. use OCP\Encryption\Keys\IStorage;
  48. use OCP\Files\Cache\ICacheEntry;
  49. use OCP\Files\Mount\IMountPoint;
  50. use OCP\Files\Storage;
  51. use OCP\ILogger;
  52. class Encryption extends Wrapper {
  53. use LocalTempFileTrait;
  54. /** @var string */
  55. private $mountPoint;
  56. /** @var \OC\Encryption\Util */
  57. private $util;
  58. /** @var \OCP\Encryption\IManager */
  59. private $encryptionManager;
  60. /** @var \OCP\ILogger */
  61. private $logger;
  62. /** @var string */
  63. private $uid;
  64. /** @var array */
  65. protected $unencryptedSize;
  66. /** @var \OCP\Encryption\IFile */
  67. private $fileHelper;
  68. /** @var IMountPoint */
  69. private $mount;
  70. /** @var IStorage */
  71. private $keyStorage;
  72. /** @var Update */
  73. private $update;
  74. /** @var Manager */
  75. private $mountManager;
  76. /** @var array remember for which path we execute the repair step to avoid recursions */
  77. private $fixUnencryptedSizeOf = [];
  78. /** @var ArrayCache */
  79. private $arrayCache;
  80. /**
  81. * @param array $parameters
  82. * @param IManager $encryptionManager
  83. * @param Util $util
  84. * @param ILogger $logger
  85. * @param IFile $fileHelper
  86. * @param string $uid
  87. * @param IStorage $keyStorage
  88. * @param Update $update
  89. * @param Manager $mountManager
  90. * @param ArrayCache $arrayCache
  91. */
  92. public function __construct(
  93. $parameters,
  94. IManager $encryptionManager = null,
  95. Util $util = null,
  96. ILogger $logger = null,
  97. IFile $fileHelper = null,
  98. $uid = null,
  99. IStorage $keyStorage = null,
  100. Update $update = null,
  101. Manager $mountManager = null,
  102. ArrayCache $arrayCache = null
  103. ) {
  104. $this->mountPoint = $parameters['mountPoint'];
  105. $this->mount = $parameters['mount'];
  106. $this->encryptionManager = $encryptionManager;
  107. $this->util = $util;
  108. $this->logger = $logger;
  109. $this->uid = $uid;
  110. $this->fileHelper = $fileHelper;
  111. $this->keyStorage = $keyStorage;
  112. $this->unencryptedSize = [];
  113. $this->update = $update;
  114. $this->mountManager = $mountManager;
  115. $this->arrayCache = $arrayCache;
  116. parent::__construct($parameters);
  117. }
  118. /**
  119. * see https://www.php.net/manual/en/function.filesize.php
  120. * The result for filesize when called on a folder is required to be 0
  121. *
  122. * @param string $path
  123. * @return int
  124. */
  125. public function filesize($path) {
  126. $fullPath = $this->getFullPath($path);
  127. /** @var CacheEntry $info */
  128. $info = $this->getCache()->get($path);
  129. if (isset($this->unencryptedSize[$fullPath])) {
  130. $size = $this->unencryptedSize[$fullPath];
  131. // update file cache
  132. if ($info instanceof ICacheEntry) {
  133. $info = $info->getData();
  134. $info['encrypted'] = $info['encryptedVersion'];
  135. } else {
  136. if (!is_array($info)) {
  137. $info = [];
  138. }
  139. $info['encrypted'] = true;
  140. }
  141. $info['size'] = $size;
  142. $this->getCache()->put($path, $info);
  143. return $size;
  144. }
  145. if (isset($info['fileid']) && $info['encrypted']) {
  146. return $this->verifyUnencryptedSize($path, $info['size']);
  147. }
  148. return $this->storage->filesize($path);
  149. }
  150. private function modifyMetaData(string $path, array $data): array {
  151. $fullPath = $this->getFullPath($path);
  152. $info = $this->getCache()->get($path);
  153. if (isset($this->unencryptedSize[$fullPath])) {
  154. $data['encrypted'] = true;
  155. $data['size'] = $this->unencryptedSize[$fullPath];
  156. } else {
  157. if (isset($info['fileid']) && $info['encrypted']) {
  158. $data['size'] = $this->verifyUnencryptedSize($path, $info['size']);
  159. $data['encrypted'] = true;
  160. }
  161. }
  162. if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
  163. $data['encryptedVersion'] = $info['encryptedVersion'];
  164. }
  165. return $data;
  166. }
  167. /**
  168. * @param string $path
  169. * @return array
  170. */
  171. public function getMetaData($path) {
  172. $data = $this->storage->getMetaData($path);
  173. if (is_null($data)) {
  174. return null;
  175. }
  176. return $this->modifyMetaData($path, $data);
  177. }
  178. public function getDirectoryContent($directory): \Traversable {
  179. $parent = rtrim($directory, '/');
  180. foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
  181. yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
  182. }
  183. }
  184. /**
  185. * see https://www.php.net/manual/en/function.file_get_contents.php
  186. *
  187. * @param string $path
  188. * @return string
  189. */
  190. public function file_get_contents($path) {
  191. $encryptionModule = $this->getEncryptionModule($path);
  192. if ($encryptionModule) {
  193. $handle = $this->fopen($path, "r");
  194. if (!$handle) {
  195. return false;
  196. }
  197. $data = stream_get_contents($handle);
  198. fclose($handle);
  199. return $data;
  200. }
  201. return $this->storage->file_get_contents($path);
  202. }
  203. /**
  204. * see https://www.php.net/manual/en/function.file_put_contents.php
  205. *
  206. * @param string $path
  207. * @param mixed $data
  208. * @return int|false
  209. */
  210. public function file_put_contents($path, $data) {
  211. // file put content will always be translated to a stream write
  212. $handle = $this->fopen($path, 'w');
  213. if (is_resource($handle)) {
  214. $written = fwrite($handle, $data);
  215. fclose($handle);
  216. return $written;
  217. }
  218. return false;
  219. }
  220. /**
  221. * see https://www.php.net/manual/en/function.unlink.php
  222. *
  223. * @param string $path
  224. * @return bool
  225. */
  226. public function unlink($path) {
  227. $fullPath = $this->getFullPath($path);
  228. if ($this->util->isExcluded($fullPath)) {
  229. return $this->storage->unlink($path);
  230. }
  231. $encryptionModule = $this->getEncryptionModule($path);
  232. if ($encryptionModule) {
  233. $this->keyStorage->deleteAllFileKeys($fullPath);
  234. }
  235. return $this->storage->unlink($path);
  236. }
  237. /**
  238. * see https://www.php.net/manual/en/function.rename.php
  239. *
  240. * @param string $path1
  241. * @param string $path2
  242. * @return bool
  243. */
  244. public function rename($path1, $path2) {
  245. $result = $this->storage->rename($path1, $path2);
  246. if ($result &&
  247. // versions always use the keys from the original file, so we can skip
  248. // this step for versions
  249. $this->isVersion($path2) === false &&
  250. $this->encryptionManager->isEnabled()) {
  251. $source = $this->getFullPath($path1);
  252. if (!$this->util->isExcluded($source)) {
  253. $target = $this->getFullPath($path2);
  254. if (isset($this->unencryptedSize[$source])) {
  255. $this->unencryptedSize[$target] = $this->unencryptedSize[$source];
  256. }
  257. $this->keyStorage->renameKeys($source, $target);
  258. $module = $this->getEncryptionModule($path2);
  259. if ($module) {
  260. $module->update($target, $this->uid, []);
  261. }
  262. }
  263. }
  264. return $result;
  265. }
  266. /**
  267. * see https://www.php.net/manual/en/function.rmdir.php
  268. *
  269. * @param string $path
  270. * @return bool
  271. */
  272. public function rmdir($path) {
  273. $result = $this->storage->rmdir($path);
  274. $fullPath = $this->getFullPath($path);
  275. if ($result &&
  276. $this->util->isExcluded($fullPath) === false &&
  277. $this->encryptionManager->isEnabled()
  278. ) {
  279. $this->keyStorage->deleteAllFileKeys($fullPath);
  280. }
  281. return $result;
  282. }
  283. /**
  284. * check if a file can be read
  285. *
  286. * @param string $path
  287. * @return bool
  288. */
  289. public function isReadable($path) {
  290. $isReadable = true;
  291. $metaData = $this->getMetaData($path);
  292. if (
  293. !$this->is_dir($path) &&
  294. isset($metaData['encrypted']) &&
  295. $metaData['encrypted'] === true
  296. ) {
  297. $fullPath = $this->getFullPath($path);
  298. $module = $this->getEncryptionModule($path);
  299. $isReadable = $module->isReadable($fullPath, $this->uid);
  300. }
  301. return $this->storage->isReadable($path) && $isReadable;
  302. }
  303. /**
  304. * see https://www.php.net/manual/en/function.copy.php
  305. *
  306. * @param string $path1
  307. * @param string $path2
  308. * @return bool
  309. */
  310. public function copy($path1, $path2) {
  311. $source = $this->getFullPath($path1);
  312. if ($this->util->isExcluded($source)) {
  313. return $this->storage->copy($path1, $path2);
  314. }
  315. // need to stream copy file by file in case we copy between a encrypted
  316. // and a unencrypted storage
  317. $this->unlink($path2);
  318. return $this->copyFromStorage($this, $path1, $path2);
  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->file_exists($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->logException($e, [
  403. 'message' => 'Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted',
  404. 'level' => ILogger::WARN,
  405. 'app' => 'core',
  406. ]);
  407. }
  408. // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
  409. if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
  410. if (!$targetExists || !$targetIsEncrypted) {
  411. $shouldEncrypt = false;
  412. }
  413. }
  414. if ($shouldEncrypt === true && $encryptionModule !== null) {
  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($path, $unencryptedSize) {
  438. $size = $this->storage->filesize($path);
  439. $result = $unencryptedSize;
  440. if ($unencryptedSize < 0 ||
  441. ($size > 0 && $unencryptedSize === $size)
  442. ) {
  443. // check if we already calculate the unencrypted size for the
  444. // given path to avoid recursions
  445. if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
  446. $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
  447. try {
  448. $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
  449. } catch (\Exception $e) {
  450. $this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path);
  451. $this->logger->logException($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($path, $size, $unencryptedSize) {
  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. fread($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 = fread($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'], ['size' => $newUnencryptedSize]);
  524. }
  525. return $newUnencryptedSize;
  526. }
  527. /**
  528. * @param Storage\IStorage $sourceStorage
  529. * @param string $sourceInternalPath
  530. * @param string $targetInternalPath
  531. * @param bool $preserveMtime
  532. * @return bool
  533. */
  534. public function moveFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = true) {
  535. if ($sourceStorage === $this) {
  536. return $this->rename($sourceInternalPath, $targetInternalPath);
  537. }
  538. // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
  539. // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
  540. // - copy the file cache update from $this->copyBetweenStorage to this method
  541. // - copy the copyKeys() call from $this->copyBetweenStorage to this method
  542. // - remove $this->copyBetweenStorage
  543. if (!$sourceStorage->isDeletable($sourceInternalPath)) {
  544. return false;
  545. }
  546. $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
  547. if ($result) {
  548. if ($sourceStorage->is_dir($sourceInternalPath)) {
  549. $result &= $sourceStorage->rmdir($sourceInternalPath);
  550. } else {
  551. $result &= $sourceStorage->unlink($sourceInternalPath);
  552. }
  553. }
  554. return $result;
  555. }
  556. /**
  557. * @param Storage\IStorage $sourceStorage
  558. * @param string $sourceInternalPath
  559. * @param string $targetInternalPath
  560. * @param bool $preserveMtime
  561. * @param bool $isRename
  562. * @return bool
  563. */
  564. public function copyFromStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false, $isRename = false) {
  565. // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
  566. // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
  567. // - copy the file cache update from $this->copyBetweenStorage to this method
  568. // - copy the copyKeys() call from $this->copyBetweenStorage to this method
  569. // - remove $this->copyBetweenStorage
  570. return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
  571. }
  572. /**
  573. * Update the encrypted cache version in the database
  574. *
  575. * @param Storage\IStorage $sourceStorage
  576. * @param string $sourceInternalPath
  577. * @param string $targetInternalPath
  578. * @param bool $isRename
  579. * @param bool $keepEncryptionVersion
  580. */
  581. private function updateEncryptedVersion(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, $keepEncryptionVersion) {
  582. $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
  583. $cacheInformation = [
  584. 'encrypted' => $isEncrypted,
  585. ];
  586. if ($isEncrypted) {
  587. $encryptedVersion = $sourceStorage->getCache()->get($sourceInternalPath)['encryptedVersion'];
  588. // In case of a move operation from an unencrypted to an encrypted
  589. // storage the old encrypted version would stay with "0" while the
  590. // correct value would be "1". Thus we manually set the value to "1"
  591. // for those cases.
  592. // See also https://github.com/owncloud/core/issues/23078
  593. if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
  594. $encryptedVersion = 1;
  595. }
  596. $cacheInformation['encryptedVersion'] = $encryptedVersion;
  597. }
  598. // in case of a rename we need to manipulate the source cache because
  599. // this information will be kept for the new target
  600. if ($isRename) {
  601. $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
  602. } else {
  603. $this->getCache()->put($targetInternalPath, $cacheInformation);
  604. }
  605. }
  606. /**
  607. * copy file between two storages
  608. *
  609. * @param Storage\IStorage $sourceStorage
  610. * @param string $sourceInternalPath
  611. * @param string $targetInternalPath
  612. * @param bool $preserveMtime
  613. * @param bool $isRename
  614. * @return bool
  615. * @throws \Exception
  616. */
  617. private function copyBetweenStorage(Storage\IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename) {
  618. // for versions we have nothing to do, because versions should always use the
  619. // key from the original file. Just create a 1:1 copy and done
  620. if ($this->isVersion($targetInternalPath) ||
  621. $this->isVersion($sourceInternalPath)) {
  622. // remember that we try to create a version so that we can detect it during
  623. // fopen($sourceInternalPath) and by-pass the encryption in order to
  624. // create a 1:1 copy of the file
  625. $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
  626. $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  627. $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
  628. if ($result) {
  629. $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
  630. // make sure that we update the unencrypted size for the version
  631. if (isset($info['encrypted']) && $info['encrypted'] === true) {
  632. $this->updateUnencryptedSize(
  633. $this->getFullPath($targetInternalPath),
  634. $info['size']
  635. );
  636. }
  637. $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
  638. }
  639. return $result;
  640. }
  641. // first copy the keys that we reuse the existing file key on the target location
  642. // and don't create a new one which would break versions for example.
  643. $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
  644. if (count($mount) === 1) {
  645. $mountPoint = $mount[0]->getMountPoint();
  646. $source = $mountPoint . '/' . $sourceInternalPath;
  647. $target = $this->getFullPath($targetInternalPath);
  648. $this->copyKeys($source, $target);
  649. } else {
  650. $this->logger->error('Could not find mount point, can\'t keep encryption keys');
  651. }
  652. if ($sourceStorage->is_dir($sourceInternalPath)) {
  653. $dh = $sourceStorage->opendir($sourceInternalPath);
  654. $result = $this->mkdir($targetInternalPath);
  655. if (is_resource($dh)) {
  656. while ($result and ($file = readdir($dh)) !== false) {
  657. if (!Filesystem::isIgnoredDir($file)) {
  658. $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
  659. }
  660. }
  661. }
  662. } else {
  663. try {
  664. $source = $sourceStorage->fopen($sourceInternalPath, 'r');
  665. $target = $this->fopen($targetInternalPath, 'w');
  666. [, $result] = \OC_Helper::streamCopy($source, $target);
  667. fclose($source);
  668. fclose($target);
  669. } catch (\Exception $e) {
  670. fclose($source);
  671. fclose($target);
  672. throw $e;
  673. }
  674. if ($result) {
  675. if ($preserveMtime) {
  676. $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
  677. }
  678. $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
  679. } else {
  680. // delete partially written target file
  681. $this->unlink($targetInternalPath);
  682. // delete cache entry that was created by fopen
  683. $this->getCache()->remove($targetInternalPath);
  684. }
  685. }
  686. return (bool)$result;
  687. }
  688. /**
  689. * get the path to a local version of the file.
  690. * The local version of the file can be temporary and doesn't have to be persistent across requests
  691. *
  692. * @param string $path
  693. * @return string
  694. */
  695. public function getLocalFile($path) {
  696. if ($this->encryptionManager->isEnabled()) {
  697. $cachedFile = $this->getCachedFile($path);
  698. if (is_string($cachedFile)) {
  699. return $cachedFile;
  700. }
  701. }
  702. return $this->storage->getLocalFile($path);
  703. }
  704. /**
  705. * Returns the wrapped storage's value for isLocal()
  706. *
  707. * @return bool wrapped storage's isLocal() value
  708. */
  709. public function isLocal() {
  710. if ($this->encryptionManager->isEnabled()) {
  711. return false;
  712. }
  713. return $this->storage->isLocal();
  714. }
  715. /**
  716. * see https://www.php.net/manual/en/function.stat.php
  717. * only the following keys are required in the result: size and mtime
  718. *
  719. * @param string $path
  720. * @return array
  721. */
  722. public function stat($path) {
  723. $stat = $this->storage->stat($path);
  724. $fileSize = $this->filesize($path);
  725. $stat['size'] = $fileSize;
  726. $stat[7] = $fileSize;
  727. $stat['hasHeader'] = $this->getHeaderSize($path) > 0;
  728. return $stat;
  729. }
  730. /**
  731. * see https://www.php.net/manual/en/function.hash.php
  732. *
  733. * @param string $type
  734. * @param string $path
  735. * @param bool $raw
  736. * @return string
  737. */
  738. public function hash($type, $path, $raw = false) {
  739. $fh = $this->fopen($path, 'rb');
  740. $ctx = hash_init($type);
  741. hash_update_stream($ctx, $fh);
  742. fclose($fh);
  743. return hash_final($ctx, $raw);
  744. }
  745. /**
  746. * return full path, including mount point
  747. *
  748. * @param string $path relative to mount point
  749. * @return string full path including mount point
  750. */
  751. protected function getFullPath($path) {
  752. return Filesystem::normalizePath($this->mountPoint . '/' . $path);
  753. }
  754. /**
  755. * read first block of encrypted file, typically this will contain the
  756. * encryption header
  757. *
  758. * @param string $path
  759. * @return string
  760. */
  761. protected function readFirstBlock($path) {
  762. $firstBlock = '';
  763. if ($this->storage->file_exists($path)) {
  764. $handle = $this->storage->fopen($path, 'r');
  765. $firstBlock = fread($handle, $this->util->getHeaderSize());
  766. fclose($handle);
  767. }
  768. return $firstBlock;
  769. }
  770. /**
  771. * return header size of given file
  772. *
  773. * @param string $path
  774. * @return int
  775. */
  776. protected function getHeaderSize($path) {
  777. $headerSize = 0;
  778. $realFile = $this->util->stripPartialFileExtension($path);
  779. if ($this->storage->file_exists($realFile)) {
  780. $path = $realFile;
  781. }
  782. $firstBlock = $this->readFirstBlock($path);
  783. if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
  784. $headerSize = $this->util->getHeaderSize();
  785. }
  786. return $headerSize;
  787. }
  788. /**
  789. * parse raw header to array
  790. *
  791. * @param string $rawHeader
  792. * @return array
  793. */
  794. protected function parseRawHeader($rawHeader) {
  795. $result = [];
  796. if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
  797. $header = $rawHeader;
  798. $endAt = strpos($header, Util::HEADER_END);
  799. if ($endAt !== false) {
  800. $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
  801. // +1 to not start with an ':' which would result in empty element at the beginning
  802. $exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
  803. $element = array_shift($exploded);
  804. while ($element !== Util::HEADER_END) {
  805. $result[$element] = array_shift($exploded);
  806. $element = array_shift($exploded);
  807. }
  808. }
  809. }
  810. return $result;
  811. }
  812. /**
  813. * read header from file
  814. *
  815. * @param string $path
  816. * @return array
  817. */
  818. protected function getHeader($path) {
  819. $realFile = $this->util->stripPartialFileExtension($path);
  820. $exists = $this->storage->file_exists($realFile);
  821. if ($exists) {
  822. $path = $realFile;
  823. }
  824. $firstBlock = $this->readFirstBlock($path);
  825. $result = $this->parseRawHeader($firstBlock);
  826. // if the header doesn't contain a encryption module we check if it is a
  827. // legacy file. If true, we add the default encryption module
  828. if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY])) {
  829. if (!empty($result)) {
  830. $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
  831. } elseif ($exists) {
  832. // if the header was empty we have to check first if it is a encrypted file at all
  833. // We would do query to filecache only if we know that entry in filecache exists
  834. $info = $this->getCache()->get($path);
  835. if (isset($info['encrypted']) && $info['encrypted'] === true) {
  836. $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
  837. }
  838. }
  839. }
  840. return $result;
  841. }
  842. /**
  843. * read encryption module needed to read/write the file located at $path
  844. *
  845. * @param string $path
  846. * @return null|\OCP\Encryption\IEncryptionModule
  847. * @throws ModuleDoesNotExistsException
  848. * @throws \Exception
  849. */
  850. protected function getEncryptionModule($path) {
  851. $encryptionModule = null;
  852. $header = $this->getHeader($path);
  853. $encryptionModuleId = $this->util->getEncryptionModuleId($header);
  854. if (!empty($encryptionModuleId)) {
  855. try {
  856. $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
  857. } catch (ModuleDoesNotExistsException $e) {
  858. $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
  859. throw $e;
  860. }
  861. }
  862. return $encryptionModule;
  863. }
  864. /**
  865. * @param string $path
  866. * @param int $unencryptedSize
  867. */
  868. public function updateUnencryptedSize($path, $unencryptedSize) {
  869. $this->unencryptedSize[$path] = $unencryptedSize;
  870. }
  871. /**
  872. * copy keys to new location
  873. *
  874. * @param string $source path relative to data/
  875. * @param string $target path relative to data/
  876. * @return bool
  877. */
  878. protected function copyKeys($source, $target) {
  879. if (!$this->util->isExcluded($source)) {
  880. return $this->keyStorage->copyKeys($source, $target);
  881. }
  882. return false;
  883. }
  884. /**
  885. * check if path points to a files version
  886. *
  887. * @param $path
  888. * @return bool
  889. */
  890. protected function isVersion($path) {
  891. $normalized = Filesystem::normalizePath($path);
  892. return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
  893. }
  894. /**
  895. * check if the given storage should be encrypted or not
  896. *
  897. * @param $path
  898. * @return bool
  899. */
  900. protected function shouldEncrypt($path) {
  901. $fullPath = $this->getFullPath($path);
  902. $mountPointConfig = $this->mount->getOption('encrypt', true);
  903. if ($mountPointConfig === false) {
  904. return false;
  905. }
  906. try {
  907. $encryptionModule = $this->getEncryptionModule($fullPath);
  908. } catch (ModuleDoesNotExistsException $e) {
  909. return false;
  910. }
  911. if ($encryptionModule === null) {
  912. $encryptionModule = $this->encryptionManager->getEncryptionModule();
  913. }
  914. return $encryptionModule->shouldEncrypt($fullPath);
  915. }
  916. public function writeStream(string $path, $stream, int $size = null): int {
  917. // always fall back to fopen
  918. $target = $this->fopen($path, 'w');
  919. [$count, $result] = \OC_Helper::streamCopy($stream, $target);
  920. fclose($target);
  921. return $count;
  922. }
  923. }