Manager.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Authentication\WebAuthn;
  8. use Cose\Algorithm\Signature\ECDSA\ES256;
  9. use Cose\Algorithm\Signature\RSA\RS256;
  10. use Cose\Algorithms;
  11. use GuzzleHttp\Psr7\ServerRequest;
  12. use OC\Authentication\WebAuthn\Db\PublicKeyCredentialEntity;
  13. use OC\Authentication\WebAuthn\Db\PublicKeyCredentialMapper;
  14. use OCP\AppFramework\Db\DoesNotExistException;
  15. use OCP\IConfig;
  16. use OCP\IUser;
  17. use Psr\Log\LoggerInterface;
  18. use Webauthn\AttestationStatement\AttestationObjectLoader;
  19. use Webauthn\AttestationStatement\AttestationStatementSupportManager;
  20. use Webauthn\AttestationStatement\NoneAttestationStatementSupport;
  21. use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler;
  22. use Webauthn\AuthenticatorAssertionResponse;
  23. use Webauthn\AuthenticatorAssertionResponseValidator;
  24. use Webauthn\AuthenticatorAttestationResponse;
  25. use Webauthn\AuthenticatorAttestationResponseValidator;
  26. use Webauthn\AuthenticatorSelectionCriteria;
  27. use Webauthn\PublicKeyCredentialCreationOptions;
  28. use Webauthn\PublicKeyCredentialDescriptor;
  29. use Webauthn\PublicKeyCredentialLoader;
  30. use Webauthn\PublicKeyCredentialParameters;
  31. use Webauthn\PublicKeyCredentialRequestOptions;
  32. use Webauthn\PublicKeyCredentialRpEntity;
  33. use Webauthn\PublicKeyCredentialUserEntity;
  34. use Webauthn\TokenBinding\TokenBindingNotSupportedHandler;
  35. class Manager {
  36. /** @var CredentialRepository */
  37. private $repository;
  38. /** @var PublicKeyCredentialMapper */
  39. private $credentialMapper;
  40. /** @var LoggerInterface */
  41. private $logger;
  42. /** @var IConfig */
  43. private $config;
  44. public function __construct(
  45. CredentialRepository $repository,
  46. PublicKeyCredentialMapper $credentialMapper,
  47. LoggerInterface $logger,
  48. IConfig $config
  49. ) {
  50. $this->repository = $repository;
  51. $this->credentialMapper = $credentialMapper;
  52. $this->logger = $logger;
  53. $this->config = $config;
  54. }
  55. public function startRegistration(IUser $user, string $serverHost): PublicKeyCredentialCreationOptions {
  56. $rpEntity = new PublicKeyCredentialRpEntity(
  57. 'Nextcloud', //Name
  58. $this->stripPort($serverHost), //ID
  59. null //Icon
  60. );
  61. $userEntity = new PublicKeyCredentialUserEntity(
  62. $user->getUID(), // Name
  63. $user->getUID(), // ID
  64. $user->getDisplayName() // Display name
  65. // 'https://foo.example.co/avatar/123e4567-e89b-12d3-a456-426655440000' //Icon
  66. );
  67. $challenge = random_bytes(32);
  68. $publicKeyCredentialParametersList = [
  69. new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_ES256),
  70. new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_RS256),
  71. ];
  72. $timeout = 60000;
  73. $excludedPublicKeyDescriptors = [
  74. ];
  75. $authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria(
  76. null,
  77. AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED,
  78. null,
  79. false,
  80. );
  81. return new PublicKeyCredentialCreationOptions(
  82. $rpEntity,
  83. $userEntity,
  84. $challenge,
  85. $publicKeyCredentialParametersList,
  86. $authenticatorSelectionCriteria,
  87. PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE,
  88. $excludedPublicKeyDescriptors,
  89. $timeout,
  90. );
  91. }
  92. public function finishRegister(PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions, string $name, string $data): PublicKeyCredentialEntity {
  93. $tokenBindingHandler = new TokenBindingNotSupportedHandler();
  94. $attestationStatementSupportManager = new AttestationStatementSupportManager();
  95. $attestationStatementSupportManager->add(new NoneAttestationStatementSupport());
  96. $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager);
  97. $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader);
  98. // Extension Output Checker Handler
  99. $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler();
  100. // Authenticator Attestation Response Validator
  101. $authenticatorAttestationResponseValidator = new AuthenticatorAttestationResponseValidator(
  102. $attestationStatementSupportManager,
  103. $this->repository,
  104. $tokenBindingHandler,
  105. $extensionOutputCheckerHandler
  106. );
  107. $authenticatorAttestationResponseValidator->setLogger($this->logger);
  108. try {
  109. // Load the data
  110. $publicKeyCredential = $publicKeyCredentialLoader->load($data);
  111. $response = $publicKeyCredential->response;
  112. // Check if the response is an Authenticator Attestation Response
  113. if (!$response instanceof AuthenticatorAttestationResponse) {
  114. throw new \RuntimeException('Not an authenticator attestation response');
  115. }
  116. // Check the response against the request
  117. $request = ServerRequest::fromGlobals();
  118. $publicKeyCredentialSource = $authenticatorAttestationResponseValidator->check(
  119. $response,
  120. $publicKeyCredentialCreationOptions,
  121. $request,
  122. ['localhost'],
  123. );
  124. } catch (\Throwable $exception) {
  125. throw $exception;
  126. }
  127. // Persist the data
  128. return $this->repository->saveAndReturnCredentialSource($publicKeyCredentialSource, $name);
  129. }
  130. private function stripPort(string $serverHost): string {
  131. return preg_replace('/(:\d+$)/', '', $serverHost);
  132. }
  133. public function startAuthentication(string $uid, string $serverHost): PublicKeyCredentialRequestOptions {
  134. // List of registered PublicKeyCredentialDescriptor classes associated to the user
  135. $registeredPublicKeyCredentialDescriptors = array_map(function (PublicKeyCredentialEntity $entity) {
  136. $credential = $entity->toPublicKeyCredentialSource();
  137. return new PublicKeyCredentialDescriptor(
  138. $credential->type,
  139. $credential->publicKeyCredentialId,
  140. );
  141. }, $this->credentialMapper->findAllForUid($uid));
  142. // Public Key Credential Request Options
  143. return new PublicKeyCredentialRequestOptions(
  144. random_bytes(32), // Challenge
  145. $this->stripPort($serverHost), // Relying Party ID
  146. $registeredPublicKeyCredentialDescriptors, // Registered PublicKeyCredentialDescriptor classes
  147. AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED,
  148. 60000, // Timeout
  149. );
  150. }
  151. public function finishAuthentication(PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions, string $data, string $uid) {
  152. $attestationStatementSupportManager = new AttestationStatementSupportManager();
  153. $attestationStatementSupportManager->add(new NoneAttestationStatementSupport());
  154. $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager);
  155. $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader);
  156. $tokenBindingHandler = new TokenBindingNotSupportedHandler();
  157. $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler();
  158. $algorithmManager = new \Cose\Algorithm\Manager();
  159. $algorithmManager->add(new ES256());
  160. $algorithmManager->add(new RS256());
  161. $authenticatorAssertionResponseValidator = new AuthenticatorAssertionResponseValidator(
  162. $this->repository,
  163. $tokenBindingHandler,
  164. $extensionOutputCheckerHandler,
  165. $algorithmManager,
  166. );
  167. $authenticatorAssertionResponseValidator->setLogger($this->logger);
  168. try {
  169. $this->logger->debug('Loading publickey credentials from: ' . $data);
  170. // Load the data
  171. $publicKeyCredential = $publicKeyCredentialLoader->load($data);
  172. $response = $publicKeyCredential->response;
  173. // Check if the response is an Authenticator Attestation Response
  174. if (!$response instanceof AuthenticatorAssertionResponse) {
  175. throw new \RuntimeException('Not an authenticator attestation response');
  176. }
  177. // Check the response against the request
  178. $request = ServerRequest::fromGlobals();
  179. $publicKeyCredentialSource = $authenticatorAssertionResponseValidator->check(
  180. $publicKeyCredential->rawId,
  181. $response,
  182. $publicKeyCredentialRequestOptions,
  183. $request,
  184. $uid,
  185. ['localhost'],
  186. );
  187. } catch (\Throwable $e) {
  188. throw $e;
  189. }
  190. return true;
  191. }
  192. public function deleteRegistration(IUser $user, int $id): void {
  193. try {
  194. $entry = $this->credentialMapper->findById($user->getUID(), $id);
  195. } catch (DoesNotExistException $e) {
  196. $this->logger->warning("WebAuthn device $id does not exist, can't delete it");
  197. return;
  198. }
  199. $this->credentialMapper->delete($entry);
  200. }
  201. public function isWebAuthnAvailable(): bool {
  202. if (!extension_loaded('bcmath')) {
  203. return false;
  204. }
  205. if (!extension_loaded('gmp')) {
  206. return false;
  207. }
  208. if (!$this->config->getSystemValueBool('auth.webauthn.enabled', true)) {
  209. return false;
  210. }
  211. return true;
  212. }
  213. }