1
0

Manager.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_NO_PREFERENCE,
  77. AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_PREFERRED,
  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. $userVerification = $response->attestationObject->authData->isUserVerified();
  129. return $this->repository->saveAndReturnCredentialSource($publicKeyCredentialSource, $name, $userVerification);
  130. }
  131. private function stripPort(string $serverHost): string {
  132. return preg_replace('/(:\d+$)/', '', $serverHost);
  133. }
  134. public function startAuthentication(string $uid, string $serverHost): PublicKeyCredentialRequestOptions {
  135. // List of registered PublicKeyCredentialDescriptor classes associated to the user
  136. $userVerificationRequirement = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED;
  137. $registeredPublicKeyCredentialDescriptors = array_map(function (PublicKeyCredentialEntity $entity) use (&$userVerificationRequirement) {
  138. if ($entity->getUserVerification() !== true) {
  139. $userVerificationRequirement = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED;
  140. }
  141. $credential = $entity->toPublicKeyCredentialSource();
  142. return new PublicKeyCredentialDescriptor(
  143. $credential->type,
  144. $credential->publicKeyCredentialId,
  145. );
  146. }, $this->credentialMapper->findAllForUid($uid));
  147. // Public Key Credential Request Options
  148. return new PublicKeyCredentialRequestOptions(
  149. random_bytes(32), // Challenge
  150. $this->stripPort($serverHost), // Relying Party ID
  151. $registeredPublicKeyCredentialDescriptors, // Registered PublicKeyCredentialDescriptor classes
  152. $userVerificationRequirement,
  153. 60000, // Timeout
  154. );
  155. }
  156. public function finishAuthentication(PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions, string $data, string $uid) {
  157. $attestationStatementSupportManager = new AttestationStatementSupportManager();
  158. $attestationStatementSupportManager->add(new NoneAttestationStatementSupport());
  159. $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager);
  160. $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader);
  161. $tokenBindingHandler = new TokenBindingNotSupportedHandler();
  162. $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler();
  163. $algorithmManager = new \Cose\Algorithm\Manager();
  164. $algorithmManager->add(new ES256());
  165. $algorithmManager->add(new RS256());
  166. $authenticatorAssertionResponseValidator = new AuthenticatorAssertionResponseValidator(
  167. $this->repository,
  168. $tokenBindingHandler,
  169. $extensionOutputCheckerHandler,
  170. $algorithmManager,
  171. );
  172. $authenticatorAssertionResponseValidator->setLogger($this->logger);
  173. try {
  174. $this->logger->debug('Loading publickey credentials from: ' . $data);
  175. // Load the data
  176. $publicKeyCredential = $publicKeyCredentialLoader->load($data);
  177. $response = $publicKeyCredential->response;
  178. // Check if the response is an Authenticator Attestation Response
  179. if (!$response instanceof AuthenticatorAssertionResponse) {
  180. throw new \RuntimeException('Not an authenticator attestation response');
  181. }
  182. // Check the response against the request
  183. $request = ServerRequest::fromGlobals();
  184. $publicKeyCredentialSource = $authenticatorAssertionResponseValidator->check(
  185. $publicKeyCredential->rawId,
  186. $response,
  187. $publicKeyCredentialRequestOptions,
  188. $request,
  189. $uid,
  190. ['localhost'],
  191. );
  192. } catch (\Throwable $e) {
  193. throw $e;
  194. }
  195. return true;
  196. }
  197. public function deleteRegistration(IUser $user, int $id): void {
  198. try {
  199. $entry = $this->credentialMapper->findById($user->getUID(), $id);
  200. } catch (DoesNotExistException $e) {
  201. $this->logger->warning("WebAuthn device $id does not exist, can't delete it");
  202. return;
  203. }
  204. $this->credentialMapper->delete($entry);
  205. }
  206. public function isWebAuthnAvailable(): bool {
  207. if (!extension_loaded('bcmath')) {
  208. return false;
  209. }
  210. if (!extension_loaded('gmp')) {
  211. return false;
  212. }
  213. if (!$this->config->getSystemValueBool('auth.webauthn.enabled', true)) {
  214. return false;
  215. }
  216. return true;
  217. }
  218. }