Storage.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Encryption\Keys;
  8. use OC\Encryption\Util;
  9. use OC\Files\Filesystem;
  10. use OC\Files\View;
  11. use OC\ServerNotAvailableException;
  12. use OC\User\NoUserException;
  13. use OCP\Encryption\Keys\IStorage;
  14. use OCP\IConfig;
  15. use OCP\Security\ICrypto;
  16. class Storage implements IStorage {
  17. // hidden file which indicate that the folder is a valid key storage
  18. public const KEY_STORAGE_MARKER = '.oc_key_storage';
  19. /** @var View */
  20. private $view;
  21. /** @var Util */
  22. private $util;
  23. // base dir where all the file related keys are stored
  24. /** @var string */
  25. private $keys_base_dir;
  26. // root of the key storage default is empty which means that we use the data folder
  27. /** @var string */
  28. private $root_dir;
  29. /** @var string */
  30. private $encryption_base_dir;
  31. /** @var string */
  32. private $backup_base_dir;
  33. /** @var array */
  34. private $keyCache = [];
  35. /** @var ICrypto */
  36. private $crypto;
  37. /** @var IConfig */
  38. private $config;
  39. /**
  40. * @param View $view
  41. * @param Util $util
  42. */
  43. public function __construct(View $view, Util $util, ICrypto $crypto, IConfig $config) {
  44. $this->view = $view;
  45. $this->util = $util;
  46. $this->encryption_base_dir = '/files_encryption';
  47. $this->keys_base_dir = $this->encryption_base_dir . '/keys';
  48. $this->backup_base_dir = $this->encryption_base_dir . '/backup';
  49. $this->root_dir = $this->util->getKeyStorageRoot();
  50. $this->crypto = $crypto;
  51. $this->config = $config;
  52. }
  53. /**
  54. * @inheritdoc
  55. */
  56. public function getUserKey($uid, $keyId, $encryptionModuleId) {
  57. $path = $this->constructUserKeyPath($encryptionModuleId, $keyId, $uid);
  58. return base64_decode($this->getKeyWithUid($path, $uid));
  59. }
  60. /**
  61. * @inheritdoc
  62. */
  63. public function getFileKey($path, $keyId, $encryptionModuleId) {
  64. $realFile = $this->util->stripPartialFileExtension($path);
  65. $keyDir = $this->util->getFileKeyDir($encryptionModuleId, $realFile);
  66. $key = $this->getKey($keyDir . $keyId)['key'];
  67. if ($key === '' && $realFile !== $path) {
  68. // Check if the part file has keys and use them, if no normal keys
  69. // exist. This is required to fix copyBetweenStorage() when we
  70. // rename a .part file over storage borders.
  71. $keyDir = $this->util->getFileKeyDir($encryptionModuleId, $path);
  72. $key = $this->getKey($keyDir . $keyId)['key'];
  73. }
  74. return base64_decode($key);
  75. }
  76. /**
  77. * @inheritdoc
  78. */
  79. public function getSystemUserKey($keyId, $encryptionModuleId) {
  80. $path = $this->constructUserKeyPath($encryptionModuleId, $keyId, null);
  81. return base64_decode($this->getKeyWithUid($path, null));
  82. }
  83. /**
  84. * @inheritdoc
  85. */
  86. public function setUserKey($uid, $keyId, $key, $encryptionModuleId) {
  87. $path = $this->constructUserKeyPath($encryptionModuleId, $keyId, $uid);
  88. return $this->setKey($path, [
  89. 'key' => base64_encode($key),
  90. 'uid' => $uid,
  91. ]);
  92. }
  93. /**
  94. * @inheritdoc
  95. */
  96. public function setFileKey($path, $keyId, $key, $encryptionModuleId) {
  97. $keyDir = $this->util->getFileKeyDir($encryptionModuleId, $path);
  98. return $this->setKey($keyDir . $keyId, [
  99. 'key' => base64_encode($key),
  100. ]);
  101. }
  102. /**
  103. * @inheritdoc
  104. */
  105. public function setSystemUserKey($keyId, $key, $encryptionModuleId) {
  106. $path = $this->constructUserKeyPath($encryptionModuleId, $keyId, null);
  107. return $this->setKey($path, [
  108. 'key' => base64_encode($key),
  109. 'uid' => null,
  110. ]);
  111. }
  112. /**
  113. * @inheritdoc
  114. */
  115. public function deleteUserKey($uid, $keyId, $encryptionModuleId) {
  116. try {
  117. $path = $this->constructUserKeyPath($encryptionModuleId, $keyId, $uid);
  118. return !$this->view->file_exists($path) || $this->view->unlink($path);
  119. } catch (NoUserException $e) {
  120. // this exception can come from initMountPoints() from setupUserMounts()
  121. // for a deleted user.
  122. //
  123. // It means, that:
  124. // - we are not running in alternative storage mode because we don't call
  125. // initMountPoints() in that mode
  126. // - the keys were in the user's home but since the user was deleted, the
  127. // user's home is gone and so are the keys
  128. //
  129. // So there is nothing to do, just ignore.
  130. }
  131. }
  132. /**
  133. * @inheritdoc
  134. */
  135. public function deleteFileKey($path, $keyId, $encryptionModuleId) {
  136. $keyDir = $this->util->getFileKeyDir($encryptionModuleId, $path);
  137. return !$this->view->file_exists($keyDir . $keyId) || $this->view->unlink($keyDir . $keyId);
  138. }
  139. /**
  140. * @inheritdoc
  141. */
  142. public function deleteAllFileKeys($path) {
  143. $keyDir = $this->util->getFileKeyDir('', $path);
  144. return !$this->view->file_exists($keyDir) || $this->view->deleteAll($keyDir);
  145. }
  146. /**
  147. * @inheritdoc
  148. */
  149. public function deleteSystemUserKey($keyId, $encryptionModuleId) {
  150. $path = $this->constructUserKeyPath($encryptionModuleId, $keyId, null);
  151. return !$this->view->file_exists($path) || $this->view->unlink($path);
  152. }
  153. /**
  154. * construct path to users key
  155. *
  156. * @param string $encryptionModuleId
  157. * @param string $keyId
  158. * @param string $uid
  159. * @return string
  160. */
  161. protected function constructUserKeyPath($encryptionModuleId, $keyId, $uid) {
  162. if ($uid === null) {
  163. $path = $this->root_dir . '/' . $this->encryption_base_dir . '/' . $encryptionModuleId . '/' . $keyId;
  164. } else {
  165. $path = $this->root_dir . '/' . $uid . $this->encryption_base_dir . '/'
  166. . $encryptionModuleId . '/' . $uid . '.' . $keyId;
  167. }
  168. return \OC\Files\Filesystem::normalizePath($path);
  169. }
  170. /**
  171. * @param string $path
  172. * @param string|null $uid
  173. * @return string
  174. * @throws ServerNotAvailableException
  175. *
  176. * Small helper function to fetch the key and verify the value for user and system keys
  177. */
  178. private function getKeyWithUid(string $path, ?string $uid): string {
  179. $data = $this->getKey($path);
  180. if (!isset($data['key'])) {
  181. throw new ServerNotAvailableException('Key is invalid');
  182. }
  183. if ($data['key'] === '') {
  184. return '';
  185. }
  186. if (!array_key_exists('uid', $data) || $data['uid'] !== $uid) {
  187. // If the migration is done we error out
  188. $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0.0');
  189. if (version_compare($versionFromBeforeUpdate, '20.0.0.1', '<=')) {
  190. return $data['key'];
  191. }
  192. if ($this->config->getSystemValueBool('encryption.key_storage_migrated', true)) {
  193. throw new ServerNotAvailableException('Key has been modified');
  194. } else {
  195. //Otherwise we migrate
  196. $data['uid'] = $uid;
  197. $this->setKey($path, $data);
  198. }
  199. }
  200. return $data['key'];
  201. }
  202. /**
  203. * read key from hard disk
  204. *
  205. * @param string $path to key
  206. * @return array containing key as base64encoded key, and possible the uid
  207. */
  208. private function getKey($path): array {
  209. $key = [
  210. 'key' => '',
  211. ];
  212. if ($this->view->file_exists($path)) {
  213. if (isset($this->keyCache[$path])) {
  214. $key = $this->keyCache[$path];
  215. } else {
  216. $data = $this->view->file_get_contents($path);
  217. // Version <20.0.0.1 doesn't have this
  218. $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0.0');
  219. if (version_compare($versionFromBeforeUpdate, '20.0.0.1', '<=')) {
  220. $key = [
  221. 'key' => base64_encode($data),
  222. ];
  223. } else {
  224. if ($this->config->getSystemValueBool('encryption.key_storage_migrated', true)) {
  225. try {
  226. $clearData = $this->crypto->decrypt($data);
  227. } catch (\Exception $e) {
  228. throw new ServerNotAvailableException('Could not decrypt key', 0, $e);
  229. }
  230. $dataArray = json_decode($clearData, true);
  231. if ($dataArray === null) {
  232. throw new ServerNotAvailableException('Invalid encryption key');
  233. }
  234. $key = $dataArray;
  235. } else {
  236. /*
  237. * Even if not all keys are migrated we should still try to decrypt it (in case some have moved).
  238. * However it is only a failure now if it is an array and decryption fails
  239. */
  240. $fallback = false;
  241. try {
  242. $clearData = $this->crypto->decrypt($data);
  243. } catch (\Throwable $e) {
  244. $fallback = true;
  245. }
  246. if (!$fallback) {
  247. $dataArray = json_decode($clearData, true);
  248. if ($dataArray === null) {
  249. throw new ServerNotAvailableException('Invalid encryption key');
  250. }
  251. $key = $dataArray;
  252. } else {
  253. $key = [
  254. 'key' => base64_encode($data),
  255. ];
  256. }
  257. }
  258. }
  259. $this->keyCache[$path] = $key;
  260. }
  261. }
  262. return $key;
  263. }
  264. /**
  265. * write key to disk
  266. *
  267. *
  268. * @param string $path path to key directory
  269. * @param array $key key
  270. * @return bool
  271. */
  272. private function setKey($path, $key) {
  273. $this->keySetPreparation(dirname($path));
  274. $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0.0');
  275. if (version_compare($versionFromBeforeUpdate, '20.0.0.1', '<=')) {
  276. // Only store old format if this happens during the migration.
  277. // TODO: Remove for 21
  278. $data = base64_decode($key['key']);
  279. } else {
  280. // Wrap the data
  281. $data = $this->crypto->encrypt(json_encode($key));
  282. }
  283. $result = $this->view->file_put_contents($path, $data);
  284. if (is_int($result) && $result > 0) {
  285. $this->keyCache[$path] = $key;
  286. return true;
  287. }
  288. return false;
  289. }
  290. /**
  291. * move keys if a file was renamed
  292. *
  293. * @param string $source
  294. * @param string $target
  295. * @return boolean
  296. */
  297. public function renameKeys($source, $target) {
  298. $sourcePath = $this->getPathToKeys($source);
  299. $targetPath = $this->getPathToKeys($target);
  300. if ($this->view->file_exists($sourcePath)) {
  301. $this->keySetPreparation(dirname($targetPath));
  302. $this->view->rename($sourcePath, $targetPath);
  303. return true;
  304. }
  305. return false;
  306. }
  307. /**
  308. * copy keys if a file was renamed
  309. *
  310. * @param string $source
  311. * @param string $target
  312. * @return boolean
  313. */
  314. public function copyKeys($source, $target) {
  315. $sourcePath = $this->getPathToKeys($source);
  316. $targetPath = $this->getPathToKeys($target);
  317. if ($this->view->file_exists($sourcePath)) {
  318. $this->keySetPreparation(dirname($targetPath));
  319. $this->view->copy($sourcePath, $targetPath);
  320. return true;
  321. }
  322. return false;
  323. }
  324. /**
  325. * backup keys of a given encryption module
  326. *
  327. * @param string $encryptionModuleId
  328. * @param string $purpose
  329. * @param string $uid
  330. * @return bool
  331. * @since 12.0.0
  332. */
  333. public function backupUserKeys($encryptionModuleId, $purpose, $uid) {
  334. $source = $uid . $this->encryption_base_dir . '/' . $encryptionModuleId;
  335. $backupDir = $uid . $this->backup_base_dir;
  336. if (!$this->view->file_exists($backupDir)) {
  337. $this->view->mkdir($backupDir);
  338. }
  339. $backupDir = $backupDir . '/' . $purpose . '.' . $encryptionModuleId . '.' . $this->getTimestamp();
  340. $this->view->mkdir($backupDir);
  341. return $this->view->copy($source, $backupDir);
  342. }
  343. /**
  344. * get the current timestamp
  345. *
  346. * @return int
  347. */
  348. protected function getTimestamp() {
  349. return time();
  350. }
  351. /**
  352. * get system wide path and detect mount points
  353. *
  354. * @param string $path
  355. * @return string
  356. */
  357. protected function getPathToKeys($path) {
  358. [$owner, $relativePath] = $this->util->getUidAndFilename($path);
  359. $systemWideMountPoint = $this->util->isSystemWideMountPoint($relativePath, $owner);
  360. if ($systemWideMountPoint) {
  361. $systemPath = $this->root_dir . '/' . $this->keys_base_dir . $relativePath . '/';
  362. } else {
  363. $systemPath = $this->root_dir . '/' . $owner . $this->keys_base_dir . $relativePath . '/';
  364. }
  365. return Filesystem::normalizePath($systemPath, false);
  366. }
  367. /**
  368. * Make preparations to filesystem for saving a key file
  369. *
  370. * @param string $path relative to the views root
  371. */
  372. protected function keySetPreparation($path) {
  373. // If the file resides within a subdirectory, create it
  374. if (!$this->view->file_exists($path)) {
  375. $sub_dirs = explode('/', ltrim($path, '/'));
  376. $dir = '';
  377. foreach ($sub_dirs as $sub_dir) {
  378. $dir .= '/' . $sub_dir;
  379. if (!$this->view->is_dir($dir)) {
  380. $this->view->mkdir($dir);
  381. }
  382. }
  383. }
  384. }
  385. }