1
0

KeyManager.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 OCA\Encryption;
  8. use OC\Encryption\Exceptions\DecryptionFailedException;
  9. use OC\Files\View;
  10. use OCA\Encryption\Crypto\Crypt;
  11. use OCA\Encryption\Crypto\Encryption;
  12. use OCA\Encryption\Exceptions\PrivateKeyMissingException;
  13. use OCA\Encryption\Exceptions\PublicKeyMissingException;
  14. use OCP\Encryption\Keys\IStorage;
  15. use OCP\IConfig;
  16. use OCP\IUserSession;
  17. use OCP\Lock\ILockingProvider;
  18. use Psr\Log\LoggerInterface;
  19. class KeyManager {
  20. private string $recoveryKeyId;
  21. private string $publicShareKeyId;
  22. private string $masterKeyId;
  23. private string $keyId;
  24. private string $publicKeyId = 'publicKey';
  25. private string $privateKeyId = 'privateKey';
  26. private string $shareKeyId = 'shareKey';
  27. private string $fileKeyId = 'fileKey';
  28. public function __construct(
  29. private IStorage $keyStorage,
  30. private Crypt $crypt,
  31. private IConfig $config,
  32. IUserSession $userSession,
  33. private Session $session,
  34. private LoggerInterface $logger,
  35. private Util $util,
  36. private ILockingProvider $lockingProvider,
  37. ) {
  38. $this->recoveryKeyId = $this->config->getAppValue('encryption',
  39. 'recoveryKeyId');
  40. if (empty($this->recoveryKeyId)) {
  41. $this->recoveryKeyId = 'recoveryKey_' . substr(md5((string)time()), 0, 8);
  42. $this->config->setAppValue('encryption',
  43. 'recoveryKeyId',
  44. $this->recoveryKeyId);
  45. }
  46. $this->publicShareKeyId = $this->config->getAppValue('encryption',
  47. 'publicShareKeyId');
  48. if (empty($this->publicShareKeyId)) {
  49. $this->publicShareKeyId = 'pubShare_' . substr(md5((string)time()), 0, 8);
  50. $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId);
  51. }
  52. $this->masterKeyId = $this->config->getAppValue('encryption',
  53. 'masterKeyId');
  54. if (empty($this->masterKeyId)) {
  55. $this->masterKeyId = 'master_' . substr(md5((string)time()), 0, 8);
  56. $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId);
  57. }
  58. $this->keyId = $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false;
  59. }
  60. /**
  61. * check if key pair for public link shares exists, if not we create one
  62. */
  63. public function validateShareKey() {
  64. $shareKey = $this->getPublicShareKey();
  65. if (empty($shareKey)) {
  66. $this->lockingProvider->acquireLock('encryption-generateSharedKey', ILockingProvider::LOCK_EXCLUSIVE, 'Encryption: shared key generation');
  67. try {
  68. $keyPair = $this->crypt->createKeyPair();
  69. // Save public key
  70. $this->keyStorage->setSystemUserKey(
  71. $this->publicShareKeyId . '.' . $this->publicKeyId, $keyPair['publicKey'],
  72. Encryption::ID);
  73. // Encrypt private key empty passphrase
  74. $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], '');
  75. $header = $this->crypt->generateHeader();
  76. $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey);
  77. } catch (\Throwable $e) {
  78. $this->lockingProvider->releaseLock('encryption-generateSharedKey', ILockingProvider::LOCK_EXCLUSIVE);
  79. throw $e;
  80. }
  81. $this->lockingProvider->releaseLock('encryption-generateSharedKey', ILockingProvider::LOCK_EXCLUSIVE);
  82. }
  83. }
  84. /**
  85. * check if a key pair for the master key exists, if not we create one
  86. */
  87. public function validateMasterKey() {
  88. if ($this->util->isMasterKeyEnabled() === false) {
  89. return;
  90. }
  91. $publicMasterKey = $this->getPublicMasterKey();
  92. $privateMasterKey = $this->getPrivateMasterKey();
  93. if (empty($publicMasterKey) && empty($privateMasterKey)) {
  94. // There could be a race condition here if two requests would trigger
  95. // the generation the second one would enter the key generation as long
  96. // as the first one didn't write the key to the keystorage yet
  97. $this->lockingProvider->acquireLock('encryption-generateMasterKey', ILockingProvider::LOCK_EXCLUSIVE, 'Encryption: master key generation');
  98. try {
  99. $keyPair = $this->crypt->createKeyPair();
  100. // Save public key
  101. $this->keyStorage->setSystemUserKey(
  102. $this->masterKeyId . '.' . $this->publicKeyId, $keyPair['publicKey'],
  103. Encryption::ID);
  104. // Encrypt private key with system password
  105. $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId);
  106. $header = $this->crypt->generateHeader();
  107. $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey);
  108. } catch (\Throwable $e) {
  109. $this->lockingProvider->releaseLock('encryption-generateMasterKey', ILockingProvider::LOCK_EXCLUSIVE);
  110. throw $e;
  111. }
  112. $this->lockingProvider->releaseLock('encryption-generateMasterKey', ILockingProvider::LOCK_EXCLUSIVE);
  113. } elseif (empty($publicMasterKey)) {
  114. $this->logger->error('A private master key is available but the public key could not be found. This should never happen.');
  115. return;
  116. } elseif (empty($privateMasterKey)) {
  117. $this->logger->error('A public master key is available but the private key could not be found. This should never happen.');
  118. return;
  119. }
  120. if (!$this->session->isPrivateKeySet()) {
  121. $masterKey = $this->getSystemPrivateKey($this->masterKeyId);
  122. $decryptedMasterKey = $this->crypt->decryptPrivateKey($masterKey, $this->getMasterKeyPassword(), $this->masterKeyId);
  123. $this->session->setPrivateKey($decryptedMasterKey);
  124. }
  125. // after the encryption key is available we are ready to go
  126. $this->session->setStatus(Session::INIT_SUCCESSFUL);
  127. }
  128. /**
  129. * @return bool
  130. */
  131. public function recoveryKeyExists() {
  132. $key = $this->getRecoveryKey();
  133. return !empty($key);
  134. }
  135. /**
  136. * get recovery key
  137. *
  138. * @return string
  139. */
  140. public function getRecoveryKey() {
  141. return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.' . $this->publicKeyId, Encryption::ID);
  142. }
  143. /**
  144. * get recovery key ID
  145. *
  146. * @return string
  147. */
  148. public function getRecoveryKeyId() {
  149. return $this->recoveryKeyId;
  150. }
  151. /**
  152. * @param string $password
  153. * @return bool
  154. */
  155. public function checkRecoveryPassword($password) {
  156. $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.' . $this->privateKeyId, Encryption::ID);
  157. $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
  158. if ($decryptedRecoveryKey) {
  159. return true;
  160. }
  161. return false;
  162. }
  163. /**
  164. * @param string $uid
  165. * @param string $password
  166. * @param array $keyPair
  167. * @return bool
  168. */
  169. public function storeKeyPair($uid, $password, $keyPair) {
  170. // Save Public Key
  171. $this->setPublicKey($uid, $keyPair['publicKey']);
  172. $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid);
  173. $header = $this->crypt->generateHeader();
  174. if ($encryptedKey) {
  175. $this->setPrivateKey($uid, $header . $encryptedKey);
  176. return true;
  177. }
  178. return false;
  179. }
  180. /**
  181. * @param string $password
  182. * @param array $keyPair
  183. * @return bool
  184. */
  185. public function setRecoveryKey($password, $keyPair) {
  186. // Save Public Key
  187. $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId() .
  188. '.' . $this->publicKeyId,
  189. $keyPair['publicKey'],
  190. Encryption::ID);
  191. $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password);
  192. $header = $this->crypt->generateHeader();
  193. if ($encryptedKey) {
  194. $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey);
  195. return true;
  196. }
  197. return false;
  198. }
  199. /**
  200. * @param $userId
  201. * @param $key
  202. * @return bool
  203. */
  204. public function setPublicKey($userId, $key) {
  205. return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID);
  206. }
  207. /**
  208. * @param $userId
  209. * @param string $key
  210. * @return bool
  211. */
  212. public function setPrivateKey($userId, $key) {
  213. return $this->keyStorage->setUserKey($userId,
  214. $this->privateKeyId,
  215. $key,
  216. Encryption::ID);
  217. }
  218. /**
  219. * write file key to key storage
  220. *
  221. * @param string $path
  222. * @param string $key
  223. * @return boolean
  224. */
  225. public function setFileKey($path, $key) {
  226. return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID);
  227. }
  228. /**
  229. * set all file keys (the file key and the corresponding share keys)
  230. *
  231. * @param string $path
  232. * @param array $keys
  233. */
  234. public function setAllFileKeys($path, $keys) {
  235. $this->setFileKey($path, $keys['data']);
  236. foreach ($keys['keys'] as $uid => $keyFile) {
  237. $this->setShareKey($path, $uid, $keyFile);
  238. }
  239. }
  240. /**
  241. * write share key to the key storage
  242. *
  243. * @param string $path
  244. * @param string $uid
  245. * @param string $key
  246. * @return boolean
  247. */
  248. public function setShareKey($path, $uid, $key) {
  249. $keyId = $uid . '.' . $this->shareKeyId;
  250. return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID);
  251. }
  252. /**
  253. * Decrypt private key and store it
  254. *
  255. * @param string $uid user id
  256. * @param string $passPhrase users password
  257. * @return boolean
  258. */
  259. public function init($uid, $passPhrase) {
  260. $this->session->setStatus(Session::INIT_EXECUTED);
  261. try {
  262. if ($this->util->isMasterKeyEnabled()) {
  263. $uid = $this->getMasterKeyId();
  264. $passPhrase = $this->getMasterKeyPassword();
  265. $privateKey = $this->getSystemPrivateKey($uid);
  266. } else {
  267. $privateKey = $this->getPrivateKey($uid);
  268. }
  269. $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid);
  270. } catch (PrivateKeyMissingException $e) {
  271. return false;
  272. } catch (DecryptionFailedException $e) {
  273. return false;
  274. } catch (\Exception $e) {
  275. $this->logger->warning(
  276. 'Could not decrypt the private key from user "' . $uid . '"" during login. Assume password change on the user back-end.',
  277. [
  278. 'app' => 'encryption',
  279. 'exception' => $e,
  280. ]
  281. );
  282. return false;
  283. }
  284. if ($privateKey) {
  285. $this->session->setPrivateKey($privateKey);
  286. $this->session->setStatus(Session::INIT_SUCCESSFUL);
  287. return true;
  288. }
  289. return false;
  290. }
  291. /**
  292. * @param $userId
  293. * @return string
  294. * @throws PrivateKeyMissingException
  295. */
  296. public function getPrivateKey($userId) {
  297. $privateKey = $this->keyStorage->getUserKey($userId,
  298. $this->privateKeyId, Encryption::ID);
  299. if (strlen($privateKey) !== 0) {
  300. return $privateKey;
  301. }
  302. throw new PrivateKeyMissingException($userId);
  303. }
  304. /**
  305. * @param ?bool $useLegacyFileKey null means try both
  306. */
  307. public function getFileKey(string $path, ?string $uid, ?bool $useLegacyFileKey, bool $useDecryptAll = false): string {
  308. if ($uid === '') {
  309. $uid = null;
  310. }
  311. $publicAccess = is_null($uid);
  312. $encryptedFileKey = '';
  313. if ($useLegacyFileKey ?? true) {
  314. $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID);
  315. if (empty($encryptedFileKey) && $useLegacyFileKey) {
  316. return '';
  317. }
  318. }
  319. if ($useDecryptAll) {
  320. $shareKey = $this->getShareKey($path, $this->session->getDecryptAllUid());
  321. $privateKey = $this->session->getDecryptAllKey();
  322. } elseif ($this->util->isMasterKeyEnabled()) {
  323. $uid = $this->getMasterKeyId();
  324. $shareKey = $this->getShareKey($path, $uid);
  325. if ($publicAccess) {
  326. $privateKey = $this->getSystemPrivateKey($uid);
  327. $privateKey = $this->crypt->decryptPrivateKey($privateKey, $this->getMasterKeyPassword(), $uid);
  328. } else {
  329. // when logged in, the master key is already decrypted in the session
  330. $privateKey = $this->session->getPrivateKey();
  331. }
  332. } elseif ($publicAccess) {
  333. // use public share key for public links
  334. $uid = $this->getPublicShareKeyId();
  335. $shareKey = $this->getShareKey($path, $uid);
  336. $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.' . $this->privateKeyId, Encryption::ID);
  337. $privateKey = $this->crypt->decryptPrivateKey($privateKey);
  338. } else {
  339. $shareKey = $this->getShareKey($path, $uid);
  340. $privateKey = $this->session->getPrivateKey();
  341. }
  342. if ($useLegacyFileKey ?? true) {
  343. if ($encryptedFileKey && $shareKey && $privateKey) {
  344. return $this->crypt->multiKeyDecryptLegacy($encryptedFileKey,
  345. $shareKey,
  346. $privateKey);
  347. }
  348. }
  349. if (!($useLegacyFileKey ?? false)) {
  350. if ($shareKey && $privateKey) {
  351. return $this->crypt->multiKeyDecrypt($shareKey, $privateKey);
  352. }
  353. }
  354. return '';
  355. }
  356. /**
  357. * Get the current version of a file
  358. *
  359. * @param string $path
  360. * @param View $view
  361. * @return int
  362. */
  363. public function getVersion($path, View $view) {
  364. $fileInfo = $view->getFileInfo($path);
  365. if ($fileInfo === false) {
  366. return 0;
  367. }
  368. return $fileInfo->getEncryptedVersion();
  369. }
  370. /**
  371. * Set the current version of a file
  372. *
  373. * @param string $path
  374. * @param int $version
  375. * @param View $view
  376. */
  377. public function setVersion($path, $version, View $view) {
  378. $fileInfo = $view->getFileInfo($path);
  379. if ($fileInfo !== false) {
  380. $cache = $fileInfo->getStorage()->getCache();
  381. $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]);
  382. }
  383. }
  384. /**
  385. * get the encrypted file key
  386. *
  387. * @param string $path
  388. * @return string
  389. */
  390. public function getEncryptedFileKey($path) {
  391. $encryptedFileKey = $this->keyStorage->getFileKey($path,
  392. $this->fileKeyId, Encryption::ID);
  393. return $encryptedFileKey;
  394. }
  395. /**
  396. * delete share key
  397. *
  398. * @param string $path
  399. * @param string $keyId
  400. * @return boolean
  401. */
  402. public function deleteShareKey($path, $keyId) {
  403. return $this->keyStorage->deleteFileKey(
  404. $path,
  405. $keyId . '.' . $this->shareKeyId,
  406. Encryption::ID);
  407. }
  408. /**
  409. * @param $path
  410. * @param $uid
  411. * @return mixed
  412. */
  413. public function getShareKey($path, $uid) {
  414. $keyId = $uid . '.' . $this->shareKeyId;
  415. return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID);
  416. }
  417. /**
  418. * check if user has a private and a public key
  419. *
  420. * @param string $userId
  421. * @return bool
  422. * @throws PrivateKeyMissingException
  423. * @throws PublicKeyMissingException
  424. */
  425. public function userHasKeys($userId) {
  426. $privateKey = $publicKey = true;
  427. $exception = null;
  428. try {
  429. $this->getPrivateKey($userId);
  430. } catch (PrivateKeyMissingException $e) {
  431. $privateKey = false;
  432. $exception = $e;
  433. }
  434. try {
  435. $this->getPublicKey($userId);
  436. } catch (PublicKeyMissingException $e) {
  437. $publicKey = false;
  438. $exception = $e;
  439. }
  440. if ($privateKey && $publicKey) {
  441. return true;
  442. } elseif (!$privateKey && !$publicKey) {
  443. return false;
  444. } else {
  445. throw $exception;
  446. }
  447. }
  448. /**
  449. * @param $userId
  450. * @return mixed
  451. * @throws PublicKeyMissingException
  452. */
  453. public function getPublicKey($userId) {
  454. $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID);
  455. if (strlen($publicKey) !== 0) {
  456. return $publicKey;
  457. }
  458. throw new PublicKeyMissingException($userId);
  459. }
  460. public function getPublicShareKeyId() {
  461. return $this->publicShareKeyId;
  462. }
  463. /**
  464. * get public key for public link shares
  465. *
  466. * @return string
  467. */
  468. public function getPublicShareKey() {
  469. return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.' . $this->publicKeyId, Encryption::ID);
  470. }
  471. /**
  472. * @param string $purpose
  473. * @param string $uid
  474. */
  475. public function backupUserKeys($purpose, $uid) {
  476. $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid);
  477. }
  478. /**
  479. * create a backup of the users private and public key and then delete it
  480. *
  481. * @param string $uid
  482. */
  483. public function deleteUserKeys($uid) {
  484. $this->deletePublicKey($uid);
  485. $this->deletePrivateKey($uid);
  486. }
  487. /**
  488. * @param $uid
  489. * @return bool
  490. */
  491. public function deletePublicKey($uid) {
  492. return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID);
  493. }
  494. /**
  495. * @param string $uid
  496. * @return bool
  497. */
  498. private function deletePrivateKey($uid) {
  499. return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID);
  500. }
  501. /**
  502. * @param string $path
  503. * @return bool
  504. */
  505. public function deleteAllFileKeys($path) {
  506. return $this->keyStorage->deleteAllFileKeys($path);
  507. }
  508. public function deleteLegacyFileKey(string $path): bool {
  509. return $this->keyStorage->deleteFileKey($path, $this->fileKeyId, Encryption::ID);
  510. }
  511. /**
  512. * @param array $userIds
  513. * @return array
  514. * @throws PublicKeyMissingException
  515. */
  516. public function getPublicKeys(array $userIds) {
  517. $keys = [];
  518. foreach ($userIds as $userId) {
  519. try {
  520. $keys[$userId] = $this->getPublicKey($userId);
  521. } catch (PublicKeyMissingException $e) {
  522. continue;
  523. }
  524. }
  525. return $keys;
  526. }
  527. /**
  528. * @param string $keyId
  529. * @return string returns openssl key
  530. */
  531. public function getSystemPrivateKey($keyId) {
  532. return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID);
  533. }
  534. /**
  535. * @param string $keyId
  536. * @param string $key
  537. * @return string returns openssl key
  538. */
  539. public function setSystemPrivateKey($keyId, $key) {
  540. return $this->keyStorage->setSystemUserKey(
  541. $keyId . '.' . $this->privateKeyId,
  542. $key,
  543. Encryption::ID);
  544. }
  545. /**
  546. * add system keys such as the public share key and the recovery key
  547. *
  548. * @param array $accessList
  549. * @param array $publicKeys
  550. * @param string $uid
  551. * @return array
  552. * @throws PublicKeyMissingException
  553. */
  554. public function addSystemKeys(array $accessList, array $publicKeys, $uid) {
  555. if (!empty($accessList['public'])) {
  556. $publicShareKey = $this->getPublicShareKey();
  557. if (empty($publicShareKey)) {
  558. throw new PublicKeyMissingException($this->getPublicShareKeyId());
  559. }
  560. $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey;
  561. }
  562. if ($this->recoveryKeyExists() &&
  563. $this->util->isRecoveryEnabledForUser($uid)) {
  564. $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey();
  565. }
  566. return $publicKeys;
  567. }
  568. /**
  569. * get master key password
  570. *
  571. * @return string
  572. * @throws \Exception
  573. */
  574. public function getMasterKeyPassword() {
  575. $password = $this->config->getSystemValue('secret');
  576. if (empty($password)) {
  577. throw new \Exception('Can not get secret from Nextcloud instance');
  578. }
  579. return $password;
  580. }
  581. /**
  582. * return master key id
  583. *
  584. * @return string
  585. */
  586. public function getMasterKeyId() {
  587. return $this->masterKeyId;
  588. }
  589. /**
  590. * get public master key
  591. *
  592. * @return string
  593. */
  594. public function getPublicMasterKey() {
  595. return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.' . $this->publicKeyId, Encryption::ID);
  596. }
  597. /**
  598. * get public master key
  599. *
  600. * @return string
  601. */
  602. public function getPrivateMasterKey() {
  603. return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.' . $this->privateKeyId, Encryption::ID);
  604. }
  605. }