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

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