1
0

KeyManager.php 17 KB

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