You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Manager.php 9.1KB

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