Manager.php 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Security\IdentityProof;
  8. use OC\Files\AppData\Factory;
  9. use OCP\Files\IAppData;
  10. use OCP\Files\NotFoundException;
  11. use OCP\IConfig;
  12. use OCP\IUser;
  13. use OCP\Security\ICrypto;
  14. use Psr\Log\LoggerInterface;
  15. class Manager {
  16. private IAppData $appData;
  17. public function __construct(
  18. Factory $appDataFactory,
  19. private ICrypto $crypto,
  20. private IConfig $config,
  21. private LoggerInterface $logger,
  22. ) {
  23. $this->appData = $appDataFactory->get('identityproof');
  24. }
  25. /**
  26. * Calls the openssl functions to generate a public and private key.
  27. * In a separate function for unit testing purposes.
  28. *
  29. * @param array $options config options to generate key {@see openssl_csr_new}
  30. *
  31. * @return array [$publicKey, $privateKey]
  32. * @throws \RuntimeException
  33. */
  34. protected function generateKeyPair(array $options = []): array {
  35. $config = [
  36. 'digest_alg' => $options['algorithm'] ?? 'sha512',
  37. 'private_key_bits' => $options['bits'] ?? 2048,
  38. 'private_key_type' => $options['type'] ?? OPENSSL_KEYTYPE_RSA,
  39. ];
  40. // Generate new key
  41. $res = openssl_pkey_new($config);
  42. if ($res === false) {
  43. $this->logOpensslError();
  44. throw new \RuntimeException('OpenSSL reported a problem');
  45. }
  46. if (openssl_pkey_export($res, $privateKey, null, $config) === false) {
  47. $this->logOpensslError();
  48. throw new \RuntimeException('OpenSSL reported a problem');
  49. }
  50. // Extract the public key from $res to $pubKey
  51. $publicKey = openssl_pkey_get_details($res);
  52. $publicKey = $publicKey['key'];
  53. return [$publicKey, $privateKey];
  54. }
  55. /**
  56. * Generate a key for a given ID
  57. * Note: If a key already exists it will be overwritten
  58. *
  59. * @param string $id key id
  60. * @param array $options config options to generate key {@see openssl_csr_new}
  61. *
  62. * @throws \RuntimeException
  63. */
  64. protected function generateKey(string $id, array $options = []): Key {
  65. [$publicKey, $privateKey] = $this->generateKeyPair($options);
  66. // Write the private and public key to the disk
  67. try {
  68. $this->appData->newFolder($id);
  69. } catch (\Exception) {
  70. }
  71. $folder = $this->appData->getFolder($id);
  72. $folder->newFile('private')
  73. ->putContent($this->crypto->encrypt($privateKey));
  74. $folder->newFile('public')
  75. ->putContent($publicKey);
  76. return new Key($publicKey, $privateKey);
  77. }
  78. /**
  79. * Get key for a specific id
  80. *
  81. * @throws \RuntimeException
  82. */
  83. protected function retrieveKey(string $id): Key {
  84. try {
  85. $folder = $this->appData->getFolder($id);
  86. $privateKey = $this->crypto->decrypt(
  87. $folder->getFile('private')->getContent()
  88. );
  89. $publicKey = $folder->getFile('public')->getContent();
  90. return new Key($publicKey, $privateKey);
  91. } catch (\Exception $e) {
  92. return $this->generateKey($id);
  93. }
  94. }
  95. /**
  96. * Get public and private key for $user
  97. *
  98. * @throws \RuntimeException
  99. */
  100. public function getKey(IUser $user): Key {
  101. $uid = $user->getUID();
  102. return $this->retrieveKey('user-' . $uid);
  103. }
  104. /**
  105. * Get instance wide public and private key
  106. *
  107. * @throws \RuntimeException
  108. */
  109. public function getSystemKey(): Key {
  110. $instanceId = $this->config->getSystemValue('instanceid', null);
  111. if ($instanceId === null) {
  112. throw new \RuntimeException('no instance id!');
  113. }
  114. return $this->retrieveKey('system-' . $instanceId);
  115. }
  116. public function hasAppKey(string $app, string $name): bool {
  117. $id = $this->generateAppKeyId($app, $name);
  118. try {
  119. $folder = $this->appData->getFolder($id);
  120. return ($folder->fileExists('public') && $folder->fileExists('private'));
  121. } catch (NotFoundException) {
  122. return false;
  123. }
  124. }
  125. public function getAppKey(string $app, string $name): Key {
  126. return $this->retrieveKey($this->generateAppKeyId($app, $name));
  127. }
  128. public function generateAppKey(string $app, string $name, array $options = []): Key {
  129. return $this->generateKey($this->generateAppKeyId($app, $name), $options);
  130. }
  131. public function deleteAppKey(string $app, string $name): bool {
  132. try {
  133. $folder = $this->appData->getFolder($this->generateAppKeyId($app, $name));
  134. $folder->delete();
  135. return true;
  136. } catch (NotFoundException) {
  137. return false;
  138. }
  139. }
  140. private function generateAppKeyId(string $app, string $name): string {
  141. return 'app-' . $app . '-' . $name;
  142. }
  143. private function logOpensslError(): void {
  144. $errors = [];
  145. while ($error = openssl_error_string()) {
  146. $errors[] = $error;
  147. }
  148. $this->logger->critical('Something is wrong with your openssl setup: ' . implode(', ', $errors));
  149. }
  150. }