diff --git a/3rdparty b/3rdparty index ee8d3bf7a2bfc..c18f8b44a0433 160000 --- a/3rdparty +++ b/3rdparty @@ -1 +1 @@ -Subproject commit ee8d3bf7a2bfcbc1946da3ffd5afb1b08e317527 +Subproject commit c18f8b44a0433ed397fda4121f183f167bd2fa55 diff --git a/apps/settings/lib/Controller/WebAuthnController.php b/apps/settings/lib/Controller/WebAuthnController.php index d2e2069b13d47..d364c5899b1db 100644 --- a/apps/settings/lib/Controller/WebAuthnController.php +++ b/apps/settings/lib/Controller/WebAuthnController.php @@ -19,14 +19,15 @@ use OCP\AppFramework\Http\Attribute\OpenAPI; use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired; use OCP\AppFramework\Http\Attribute\UseSession; +use OCP\AppFramework\Http\DataDisplayResponse; use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\Response; use OCP\EventDispatcher\IEventDispatcher; use OCP\IRequest; use OCP\ISession; use OCP\IUserSession; use OCP\Log\Audit\CriticalActionPerformedEvent; use Psr\Log\LoggerInterface; -use Webauthn\PublicKeyCredentialCreationOptions; #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)] class WebAuthnController extends Controller { @@ -48,7 +49,7 @@ public function __construct( #[PasswordConfirmationRequired] #[UseSession] #[NoCSRFRequired] - public function startRegistration(): JSONResponse { + public function startRegistration(): Response { $this->logger->debug('Starting WebAuthn registration'); $credentialOptions = $this->manager->startRegistration($this->userSession->getUser(), $this->request->getServerHost()); @@ -56,7 +57,9 @@ public function startRegistration(): JSONResponse { // Set this in the session since we need it on finish $this->session->set(self::WEBAUTHN_REGISTRATION, $credentialOptions); - return new JSONResponse($credentialOptions); + $response = new DataDisplayResponse($credentialOptions); + $response->addHeader('Content-Type', 'application/json; charset=utf-8'); + return $response; } #[NoSubAdminRequired] @@ -72,11 +75,10 @@ public function finishRegistration(string $name, string $data): JSONResponse { } // Obtain the publicKeyCredentialOptions from when we started the registration - $publicKeyCredentialCreationOptions = PublicKeyCredentialCreationOptions::createFromArray($this->session->get(self::WEBAUTHN_REGISTRATION)); - + $registrationOptions = $this->session->get(self::WEBAUTHN_REGISTRATION); $this->session->remove(self::WEBAUTHN_REGISTRATION); - $credential = $this->manager->finishRegister($publicKeyCredentialCreationOptions, $name, $data); + $credential = $this->manager->finishRegister($registrationOptions, $name, $data); $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent( 'WebAuthn device with ID "%s" was added', ['deviceId' => $credential->getId()], diff --git a/apps/settings/tests/Controller/WebAuthnControllerTest.php b/apps/settings/tests/Controller/WebAuthnControllerTest.php index 7049490d1314c..7441de2e90140 100644 --- a/apps/settings/tests/Controller/WebAuthnControllerTest.php +++ b/apps/settings/tests/Controller/WebAuthnControllerTest.php @@ -21,9 +21,6 @@ use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; -use Webauthn\PublicKeyCredentialCreationOptions; -use Webauthn\PublicKeyCredentialRpEntity; -use Webauthn\PublicKeyCredentialUserEntity; class WebAuthnControllerTest extends TestCase { private Manager&MockObject $manager; @@ -50,19 +47,14 @@ protected function setUp(): void { } public function testFinishRegistrationIsAudited(): void { - $options = PublicKeyCredentialCreationOptions::create( - PublicKeyCredentialRpEntity::create('Nextcloud'), - PublicKeyCredentialUserEntity::create('jane', 'jane', 'Jane'), - random_bytes(32), - attestation: PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE, - ); $this->session->method('exists')->willReturn(true); - $this->session->method('get')->willReturn(json_decode(json_encode($options), true)); + $this->session->method('get')->willReturn('{"challenge":"abc"}'); $credential = new PublicKeyCredentialEntity(); $credential->setId(17); $this->manager->expects($this->once()) ->method('finishRegister') + ->with('{"challenge":"abc"}', 'My key', '{}') ->willReturn($credential); $this->eventDispatcher->expects($this->once()) diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml index 7a1980a19765b..3183fccf1192b 100644 --- a/build/psalm-baseline.xml +++ b/build/psalm-baseline.xml @@ -2139,11 +2139,6 @@ - - - session->get(self::WEBAUTHN_REGISTRATION))]]> - - @@ -2927,11 +2922,6 @@ - - - session->get(self::WEBAUTHN_LOGIN))]]> - - request->server]]> diff --git a/core/Controller/WebAuthnController.php b/core/Controller/WebAuthnController.php index 6faedc5e2057a..b0d2991826e0d 100644 --- a/core/Controller/WebAuthnController.php +++ b/core/Controller/WebAuthnController.php @@ -18,12 +18,13 @@ use OCP\AppFramework\Http\Attribute\FrontpageRoute; use OCP\AppFramework\Http\Attribute\PublicPage; use OCP\AppFramework\Http\Attribute\UseSession; +use OCP\AppFramework\Http\DataDisplayResponse; use OCP\AppFramework\Http\JSONResponse; +use OCP\AppFramework\Http\Response; use OCP\IRequest; use OCP\ISession; use OCP\IUserManager; use Psr\Log\LoggerInterface; -use Webauthn\PublicKeyCredentialRequestOptions; class WebAuthnController extends Controller { private const string WEBAUTHN_LOGIN = 'webauthn_login'; @@ -46,7 +47,7 @@ public function __construct( #[PublicPage] #[UseSession] #[FrontpageRoute(verb: 'POST', url: 'login/webauthn/start')] - public function startAuthentication(string $loginName): JSONResponse { + public function startAuthentication(string $loginName): Response { $this->logger->debug('Starting WebAuthn login'); $this->logger->debug('Converting login name to UID'); @@ -54,11 +55,13 @@ public function startAuthentication(string $loginName): JSONResponse { $this->logger->debug('Got UID: ' . $uid); $publicKeyCredentialRequestOptions = $this->webAuthnManger->startAuthentication($uid, $this->request->getServerHost()); - $this->session->set(self::WEBAUTHN_LOGIN, json_encode($publicKeyCredentialRequestOptions)); + $this->session->set(self::WEBAUTHN_LOGIN, $publicKeyCredentialRequestOptions); $this->session->set(self::WEBAUTHN_LOGIN_UID, $uid); $this->session->set(self::WEBAUTHN_LOGIN_NAME, $loginName); - return new JSONResponse($publicKeyCredentialRequestOptions); + $response = new DataDisplayResponse($publicKeyCredentialRequestOptions); + $response->addHeader('Content-Type', 'application/json; charset=utf-8'); + return $response; } #[PublicPage] @@ -76,7 +79,7 @@ public function finishAuthentication(string $data): JSONResponse { } // Obtain the publicKeyCredentialOptions from when we started the registration - $publicKeyCredentialRequestOptions = PublicKeyCredentialRequestOptions::createFromString($this->session->get(self::WEBAUTHN_LOGIN)); + $publicKeyCredentialRequestOptions = $this->session->get(self::WEBAUTHN_LOGIN); $uid = $this->session->get(self::WEBAUTHN_LOGIN_UID); $loginName = $this->session->get(self::WEBAUTHN_LOGIN_NAME); $authenticatorData = $this->webAuthnManger->finishAuthentication($publicKeyCredentialRequestOptions, $data, $uid); diff --git a/lib/private/Authentication/WebAuthn/CredentialRepository.php b/lib/private/Authentication/WebAuthn/CredentialRepository.php index 40a541531792a..46be35e4bc987 100644 --- a/lib/private/Authentication/WebAuthn/CredentialRepository.php +++ b/lib/private/Authentication/WebAuthn/CredentialRepository.php @@ -12,44 +12,36 @@ use OC\Authentication\WebAuthn\Db\PublicKeyCredentialEntity; use OC\Authentication\WebAuthn\Db\PublicKeyCredentialMapper; use OCP\AppFramework\Db\IMapperException; -use Webauthn\PublicKeyCredentialSource; -use Webauthn\PublicKeyCredentialSourceRepository; -use Webauthn\PublicKeyCredentialUserEntity; +use Webauthn\AttestationStatement\AttestationStatementSupportManager; +use Webauthn\AttestationStatement\NoneAttestationStatementSupport; +use Webauthn\CredentialRecord; +use Webauthn\Denormalizer\WebauthnSerializerFactory; + +class CredentialRepository { + private WebauthnSerializerFactory $serializerFactory; -class CredentialRepository implements PublicKeyCredentialSourceRepository { public function __construct( private PublicKeyCredentialMapper $credentialMapper, ) { + $attestationStatementSupportManager = AttestationStatementSupportManager::create(); + $attestationStatementSupportManager->add(NoneAttestationStatementSupport::create()); + $this->serializerFactory = new WebauthnSerializerFactory($attestationStatementSupportManager); } - #[\Override] - public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKeyCredentialSource { + public function findOneByCredentialId(string $publicKeyCredentialId): ?CredentialRecord { try { $entity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialId); - return $entity->toPublicKeyCredentialSource(); - } catch (IMapperException $e) { + return $this->mapToCredentialRecord($entity); + } catch (IMapperException) { return null; } } - /** - * @return PublicKeyCredentialSource[] - */ - #[\Override] - public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array { - $uid = $publicKeyCredentialUserEntity->getId(); - $entities = $this->credentialMapper->findAllForUid($uid); - - return array_map(function (PublicKeyCredentialEntity $entity) { - return $entity->toPublicKeyCredentialSource(); - }, $entities); - } - - public function saveAndReturnCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, ?string $name = null, bool $userVerification = false): PublicKeyCredentialEntity { + public function saveCredentialSource(CredentialRecord $credentialRecord, ?string $name = null, bool $userVerification = false): PublicKeyCredentialEntity { $oldEntity = null; try { - $oldEntity = $this->credentialMapper->findOneByCredentialId($publicKeyCredentialSource->getPublicKeyCredentialId()); + $oldEntity = $this->credentialMapper->findOneByCredentialId($credentialRecord->publicKeyCredentialId); } catch (IMapperException $e) { } @@ -59,7 +51,13 @@ public function saveAndReturnCredentialSource(PublicKeyCredentialSource $publicK $name = 'default'; } - $entity = PublicKeyCredentialEntity::fromPublicKeyCrendentialSource($name, $publicKeyCredentialSource, $userVerification); + $credentialId = base64_encode($credentialRecord->publicKeyCredentialId); + $entity = new PublicKeyCredentialEntity(); + $entity->setName($name); + $entity->setUid($credentialRecord->userHandle); + $entity->setUserVerification($userVerification); + $entity->setPublicKeyCredentialId($credentialId); + $entity->setData($this->serializeCredentialRecord($credentialRecord)); if ($oldEntity) { if ($oldEntity->getUid() !== $entity->getUid()) { @@ -79,8 +77,17 @@ public function saveAndReturnCredentialSource(PublicKeyCredentialSource $publicK return $this->credentialMapper->insertOrUpdate($entity); } - #[\Override] - public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource, ?string $name = null): void { - $this->saveAndReturnCredentialSource($publicKeyCredentialSource, $name); + public function mapToCredentialRecord(PublicKeyCredentialEntity $entity): CredentialRecord { + $serializer = $this->serializerFactory->create(); + return $serializer->deserialize( + $entity->getData(), + CredentialRecord::class, + 'json', + ); + } + + private function serializeCredentialRecord(CredentialRecord $credentialRecord): string { + $serializer = $this->serializerFactory->create(); + return $serializer->serialize($credentialRecord, 'json'); } } diff --git a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php index b3a780cb8e4b0..3c82d7c91e388 100644 --- a/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php +++ b/lib/private/Authentication/WebAuthn/Db/PublicKeyCredentialEntity.php @@ -11,7 +11,6 @@ use JsonSerializable; use OCP\AppFramework\Db\Entity; -use Webauthn\PublicKeyCredentialSource; /** * @since 19.0.0 @@ -24,26 +23,21 @@ * @method void setPublicKeyCredentialId(string $id); * @method string getData(); * @method void setData(string $data); - * - * @since 30.0.0 Add userVerification attribute * @method bool|null getUserVerification(); * @method void setUserVerification(bool $userVerification); + * + * @since 30.0.0 Add userVerification attribute */ class PublicKeyCredentialEntity extends Entity implements JsonSerializable { - /** @var string */ - protected $name; + protected ?string $name = null; - /** @var string */ - protected $uid; + protected ?string $uid = null; - /** @var string */ - protected $publicKeyCredentialId; + protected ?string $publicKeyCredentialId = null; - /** @var string */ - protected $data; + protected ?string $data = null; - /** @var bool|null */ - protected $userVerification; + protected ?bool $userVerification = null; public function __construct() { $this->addType('name', 'string'); @@ -53,24 +47,6 @@ public function __construct() { $this->addType('userVerification', 'boolean'); } - public static function fromPublicKeyCrendentialSource(string $name, PublicKeyCredentialSource $publicKeyCredentialSource, bool $userVerification): PublicKeyCredentialEntity { - $publicKeyCredentialEntity = new self(); - - $publicKeyCredentialEntity->setName($name); - $publicKeyCredentialEntity->setUid($publicKeyCredentialSource->getUserHandle()); - $publicKeyCredentialEntity->setPublicKeyCredentialId(base64_encode($publicKeyCredentialSource->getPublicKeyCredentialId())); - $publicKeyCredentialEntity->setData(json_encode($publicKeyCredentialSource)); - $publicKeyCredentialEntity->setUserVerification($userVerification); - - return $publicKeyCredentialEntity; - } - - public function toPublicKeyCredentialSource(): PublicKeyCredentialSource { - return PublicKeyCredentialSource::createFromArray( - json_decode($this->getData(), true) - ); - } - /** * @inheritDoc */ diff --git a/lib/private/Authentication/WebAuthn/Manager.php b/lib/private/Authentication/WebAuthn/Manager.php index 4837fb324aa23..8204d6d5b3db2 100644 --- a/lib/private/Authentication/WebAuthn/Manager.php +++ b/lib/private/Authentication/WebAuthn/Manager.php @@ -9,9 +9,11 @@ namespace OC\Authentication\WebAuthn; +use Cose\Algorithm\Manager as AlgorithmManager; use Cose\Algorithm\Signature\ECDSA\ES256; +use Cose\Algorithm\Signature\EdDSA\EdDSA; +use Cose\Algorithm\Signature\RSA\PS256; use Cose\Algorithm\Signature\RSA\RS256; -use Cose\Algorithms; use GuzzleHttp\Psr7\ServerRequest; use OC\Authentication\WebAuthn\Db\PublicKeyCredentialEntity; use OC\Authentication\WebAuthn\Db\PublicKeyCredentialMapper; @@ -19,103 +21,96 @@ use OCP\IConfig; use OCP\IUser; use Psr\Log\LoggerInterface; -use Webauthn\AttestationStatement\AttestationObjectLoader; +use RuntimeException; +use Symfony\Component\Serializer\Encoder\JsonEncode; +use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; use Webauthn\AttestationStatement\AttestationStatementSupportManager; use Webauthn\AttestationStatement\NoneAttestationStatementSupport; -use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler; use Webauthn\AuthenticatorAssertionResponse; use Webauthn\AuthenticatorAssertionResponseValidator; use Webauthn\AuthenticatorAttestationResponse; use Webauthn\AuthenticatorAttestationResponseValidator; use Webauthn\AuthenticatorData; use Webauthn\AuthenticatorSelectionCriteria; +use Webauthn\CeremonyStep\CeremonyStepManagerFactory; +use Webauthn\Denormalizer\WebauthnSerializerFactory; +use Webauthn\PublicKeyCredential; use Webauthn\PublicKeyCredentialCreationOptions; use Webauthn\PublicKeyCredentialDescriptor; -use Webauthn\PublicKeyCredentialLoader; use Webauthn\PublicKeyCredentialParameters; use Webauthn\PublicKeyCredentialRequestOptions; use Webauthn\PublicKeyCredentialRpEntity; use Webauthn\PublicKeyCredentialUserEntity; -use Webauthn\TokenBinding\TokenBindingNotSupportedHandler; class Manager { + private const int TIMEOUT = 60000; + + private WebauthnSerializerFactory $serializerFactory; + + private AlgorithmManager $algorithmManager; + public function __construct( private CredentialRepository $repository, private PublicKeyCredentialMapper $credentialMapper, private LoggerInterface $logger, private IConfig $config, ) { + $attestationStatementSupportManager = AttestationStatementSupportManager::create(); + $attestationStatementSupportManager->add(NoneAttestationStatementSupport::create()); + $this->serializerFactory = new WebauthnSerializerFactory($attestationStatementSupportManager); + + // Ordered by preference, the order is kept in the registration options + $this->algorithmManager = AlgorithmManager::create(); + // ECDSA using the P-256 curve and SHA-256; widely supported by hardware keys and platform authenticators. + $this->algorithmManager->add(ES256::create()); + // EdDSA with the Ed25519 curve; modern and efficient signature algorithm, but less widely supported. + if (EdDSA::isSupported()) { + $this->algorithmManager->add(new EdDSA()); + } + // RSASSA-PSS with SHA-256; modern and more secure RSA alternative. (PSS padding is more secure than PKCS#1 v1.5) + $this->algorithmManager->add(PS256::create()); + // RSA Signature with PKCS#1 v1.5 padding and SHA-256; legacy standard included for broader compatibility. + $this->algorithmManager->add(RS256::create()); } - public function startRegistration(IUser $user, string $serverHost): PublicKeyCredentialCreationOptions { - $rpEntity = new PublicKeyCredentialRpEntity( - 'Nextcloud', //Name - $this->stripPort($serverHost), //ID - null //Icon - ); - - $userEntity = new PublicKeyCredentialUserEntity( - $user->getUID(), // Name - $user->getUID(), // ID - $user->getDisplayName() // Display name - // 'https://foo.example.co/avatar/123e4567-e89b-12d3-a456-426655440000' //Icon - ); - - $challenge = random_bytes(32); - - $publicKeyCredentialParametersList = [ - new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_ES256), - new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_RS256), - ]; - - $timeout = 60000; - - $excludedPublicKeyDescriptors = [ - ]; - - $authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria( - AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_NO_PREFERENCE, - AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_PREFERRED, - null, - false, - ); - - return new PublicKeyCredentialCreationOptions( - $rpEntity, - $userEntity, - $challenge, - $publicKeyCredentialParametersList, - $authenticatorSelectionCriteria, - PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE, - $excludedPublicKeyDescriptors, - $timeout, + /** + * Start a Webauthn registration + * + * @param IUser $user - The user for which the registration is being started + * @param string $serverHost - The server host (used to determine the relying party ID) + * @return string The registration options to be sent to the client, serialized as a JSON string {@see https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson} + */ + public function startRegistration(IUser $user, string $serverHost): string { + $options = $this->getRegistrationOptions($user, $serverHost, random_bytes(32)); + $serializer = $this->serializerFactory->create(); + return $serializer->serialize( + $options, + 'json', + [ + AbstractObjectNormalizer::SKIP_NULL_VALUES => true, + JsonEncode::OPTIONS => JSON_THROW_ON_ERROR, + ], ); } - public function finishRegister(PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions, string $name, string $data): PublicKeyCredentialEntity { - $tokenBindingHandler = new TokenBindingNotSupportedHandler(); - - $attestationStatementSupportManager = new AttestationStatementSupportManager(); - $attestationStatementSupportManager->add(new NoneAttestationStatementSupport()); - - $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager); - $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader); - - // Extension Output Checker Handler - $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler(); - - // Authenticator Attestation Response Validator - $authenticatorAttestationResponseValidator = new AuthenticatorAttestationResponseValidator( - $attestationStatementSupportManager, - $this->repository, - $tokenBindingHandler, - $extensionOutputCheckerHandler - ); + /** + * Finish the Webauthn registration + * + * @param string $registrationOptions - The registration options that were sent to the client, serialized as a JSON string {@see https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson} + * @param string $name - The name of the credential to be saved + * @param string $data - The data returned from the client, serialized as a JSON string {@see https://w3c.github.io/webauthn/#typedefdef-publickeycredentialjson} + * @throws RuntimeException - If the registration options or data are invalid + */ + public function finishRegister(string $registrationOptions, string $name, string $data): PublicKeyCredentialEntity { + $csmFactory = $this->getCeremonyStepManagerFactory(); + $creationCSM = $csmFactory->creationCeremony(); + $authenticatorAttestationResponseValidator = AuthenticatorAttestationResponseValidator::create($creationCSM); $authenticatorAttestationResponseValidator->setLogger($this->logger); try { - // Load the data - $publicKeyCredential = $publicKeyCredentialLoader->load($data); + $serializer = $this->serializerFactory->create(); + $registrationOptions = $serializer->deserialize($registrationOptions, PublicKeyCredentialCreationOptions::class, 'json'); + $publicKeyCredential = $serializer->deserialize($data, PublicKeyCredential::class, 'json'); $response = $publicKeyCredential->response; // Check if the response is an Authenticator Attestation Response @@ -128,31 +123,33 @@ public function finishRegister(PublicKeyCredentialCreationOptions $publicKeyCred $publicKeyCredentialSource = $authenticatorAttestationResponseValidator->check( $response, - $publicKeyCredentialCreationOptions, - $request, - ['localhost'], + $registrationOptions, + $request->getUri()->getHost(), ); - } catch (\Throwable $exception) { - throw $exception; + } catch (\UnexpectedValueException $exception) { + throw new \RuntimeException('Invalid registration options or data', previous: $exception); } // Persist the data $userVerification = $response->attestationObject->authData->isUserVerified(); - return $this->repository->saveAndReturnCredentialSource($publicKeyCredentialSource, $name, $userVerification); - } - - private function stripPort(string $serverHost): string { - return preg_replace('/(:\d+$)/', '', $serverHost) ?? ''; + return $this->repository->saveCredentialSource($publicKeyCredentialSource, $name, $userVerification); } - public function startAuthentication(string $uid, string $serverHost): PublicKeyCredentialRequestOptions { + /** + * Start Webauthn authentication + * + * @param string $uid - The user ID for which the authentication is being started + * @param string $serverHost - The server host (used to determine the relying party ID) + * @return string The authentication options to be sent to the client, serialized as a JSON string {@see https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson} + */ + public function startAuthentication(string $uid, string $serverHost): string { // List of registered PublicKeyCredentialDescriptor classes associated to the user $userVerificationRequirement = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED; $registeredPublicKeyCredentialDescriptors = array_map(function (PublicKeyCredentialEntity $entity) use (&$userVerificationRequirement) { if ($entity->getUserVerification() !== true) { $userVerificationRequirement = AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED; } - $credential = $entity->toPublicKeyCredentialSource(); + $credential = $this->repository->mapToCredentialRecord($entity); return new PublicKeyCredentialDescriptor( $credential->type, $credential->publicKeyCredentialId, @@ -160,41 +157,43 @@ public function startAuthentication(string $uid, string $serverHost): PublicKeyC }, $this->credentialMapper->findAllForUid($uid)); // Public Key Credential Request Options - return new PublicKeyCredentialRequestOptions( - random_bytes(32), // Challenge - $this->stripPort($serverHost), // Relying Party ID - $registeredPublicKeyCredentialDescriptors, // Registered PublicKeyCredentialDescriptor classes + $options = new PublicKeyCredentialRequestOptions( + random_bytes(32), + $this->stripPort($serverHost), + $registeredPublicKeyCredentialDescriptors, $userVerificationRequirement, - 60000, // Timeout + self::TIMEOUT, ); - } - - public function finishAuthentication(PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions, string $data, string $uid): AuthenticatorData { - $attestationStatementSupportManager = new AttestationStatementSupportManager(); - $attestationStatementSupportManager->add(new NoneAttestationStatementSupport()); - - $attestationObjectLoader = new AttestationObjectLoader($attestationStatementSupportManager); - $publicKeyCredentialLoader = new PublicKeyCredentialLoader($attestationObjectLoader); - $tokenBindingHandler = new TokenBindingNotSupportedHandler(); - $extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler(); - $algorithmManager = new \Cose\Algorithm\Manager(); - $algorithmManager->add(new ES256()); - $algorithmManager->add(new RS256()); + $serializer = $this->serializerFactory->create(); + return $serializer->serialize( + $options, + 'json', + [ + AbstractObjectNormalizer::SKIP_NULL_VALUES => true, + JsonEncode::OPTIONS => JSON_THROW_ON_ERROR, + ]); + } - $authenticatorAssertionResponseValidator = new AuthenticatorAssertionResponseValidator( - $this->repository, - $tokenBindingHandler, - $extensionOutputCheckerHandler, - $algorithmManager, - ); - $authenticatorAssertionResponseValidator->setLogger($this->logger); + /** + * Finish authentication of a Webauthn request + * @param string $requestOptions - The authentication options that were sent to the client, serialized as a JSON string {@see https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson} + * @param string $data - The data returned from the client, serialized as a JSON string {@see https://w3c.github.io/webauthn/#typedefdef-publickeycredentialjson} + * @param string $uid - The user ID for which the authentication is being finished + */ + public function finishAuthentication(string $requestOptions, string $data, string $uid): AuthenticatorData { + $csmFactory = $this->getCeremonyStepManagerFactory(); + $assertionCSM = $csmFactory->requestCeremony(); + $authenticatorAttestationResponseValidator = AuthenticatorAssertionResponseValidator::create($assertionCSM); + $authenticatorAttestationResponseValidator->setLogger($this->logger); try { $this->logger->debug('Loading publickey credentials from: ' . $data); // Load the data - $publicKeyCredential = $publicKeyCredentialLoader->load($data); + $serializer = $this->serializerFactory->create(); + $publicKeyCredentialRequestOptions = $serializer->deserialize($requestOptions, PublicKeyCredentialRequestOptions::class, 'json'); + $publicKeyCredential = $serializer->deserialize($data, PublicKeyCredential::class, 'json'); $response = $publicKeyCredential->response; // Check if the response is an Authenticator Attestation Response @@ -202,17 +201,22 @@ public function finishAuthentication(PublicKeyCredentialRequestOptions $publicKe throw new \RuntimeException('Not an authenticator attestation response'); } + $record = $this->repository->findOneByCredentialId($publicKeyCredential->rawId); + if ($record === null) { + throw new \RuntimeException('No credential found for the given ID'); + } + // Check the response against the request $request = ServerRequest::fromGlobals(); - $publicKeyCredentialSource = $authenticatorAssertionResponseValidator->check( - $publicKeyCredential->rawId, + $updatedRecord = $authenticatorAttestationResponseValidator->check( + $record, $response, $publicKeyCredentialRequestOptions, - $request, + $request->getUri()->getHost(), $uid, - ['localhost'], ); + $this->repository->saveCredentialSource($updatedRecord); } catch (\Throwable $e) { throw $e; } @@ -220,6 +224,12 @@ public function finishAuthentication(PublicKeyCredentialRequestOptions $publicKe return $response->authenticatorData; } + /** + * Delete a WebAuthn registration + * + * @param IUser $user - The user for which the registration is being deleted + * @param int $id - The ID of the registration to be deleted + */ public function deleteRegistration(IUser $user, int $id): void { try { $entry = $this->credentialMapper->findById($user->getUID(), $id); @@ -231,6 +241,9 @@ public function deleteRegistration(IUser $user, int $id): void { $this->credentialMapper->delete($entry); } + /** + * Check if WebAuthn is available + */ public function isWebAuthnAvailable(): bool { if (!$this->config->getSystemValueBool('auth.webauthn.enabled', true)) { return false; @@ -238,4 +251,46 @@ public function isWebAuthnAvailable(): bool { return true; } + + protected function getRegistrationOptions(IUser $user, string $serverHost, string $challenge): PublicKeyCredentialCreationOptions { + $rpEntity = new PublicKeyCredentialRpEntity('Nextcloud', $this->stripPort($serverHost)); + $userEntity = new PublicKeyCredentialUserEntity( + $user->getUID(), + $user->getUID(), + $user->getDisplayName(), + ); + + $publicKeyCredentialParametersList = array_map( + fn (int $algorithm) => new PublicKeyCredentialParameters(PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY, $algorithm), + iterator_to_array($this->algorithmManager->list(), false), + ); + + $authenticatorSelectionCriteria = new AuthenticatorSelectionCriteria( + AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_NO_PREFERENCE, + AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_PREFERRED, + null, + ); + + return new PublicKeyCredentialCreationOptions( + $rpEntity, + $userEntity, + $challenge, + $publicKeyCredentialParametersList, + $authenticatorSelectionCriteria, + PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE, + timeout: self::TIMEOUT, + ); + } + + private function getCeremonyStepManagerFactory(): CeremonyStepManagerFactory { + $csmFactory = new CeremonyStepManagerFactory(); + $csmFactory->setAlgorithmManager($this->algorithmManager); + // Browsers allow WebAuthn on plain HTTP for localhost only + $csmFactory->setSecuredRelyingPartyId(['localhost']); + return $csmFactory; + } + + private function stripPort(string $serverHost): string { + return preg_replace('/(:\d+$)/', '', $serverHost) ?? ''; + } } diff --git a/tests/lib/Authentication/WebAuthn/CredentialRepositoryTest.php b/tests/lib/Authentication/WebAuthn/CredentialRepositoryTest.php new file mode 100644 index 0000000000000..16d55e6afcdd4 --- /dev/null +++ b/tests/lib/Authentication/WebAuthn/CredentialRepositoryTest.php @@ -0,0 +1,140 @@ +mapper = $this->createMock(PublicKeyCredentialMapper::class); + $this->repository = new CredentialRepository($this->mapper); + } + + /** + * Data as stored by webauthn-lib 4.x (PublicKeyCredentialSource::jsonSerialize) + */ + public function testMapLegacyCredentialSource(): void { + $entity = new PublicKeyCredentialEntity(); + $entity->setData(json_encode([ + 'publicKeyCredentialId' => 'Y3JlZGVudGlhbC1pZA', + 'type' => 'public-key', + 'transports' => ['usb'], + 'attestationType' => 'none', + 'trustPath' => ['type' => 'Webauthn\\TrustPath\\EmptyTrustPath'], + 'aaguid' => '00000000-0000-0000-0000-000000000000', + 'credentialPublicKey' => 'cHVibGljLWtleQ', + 'userHandle' => 'amFuZQ', + 'counter' => 42, + 'otherUI' => [], + 'backupEligible' => false, + 'backupStatus' => false, + 'uvInitialized' => true, + ])); + + $record = $this->repository->mapToCredentialRecord($entity); + + $this->assertSame('credential-id', $record->publicKeyCredentialId); + $this->assertSame('public-key', $record->type); + $this->assertSame(['usb'], $record->transports); + $this->assertSame('none', $record->attestationType); + $this->assertInstanceOf(EmptyTrustPath::class, $record->trustPath); + $this->assertSame('public-key', $record->credentialPublicKey); + $this->assertSame('jane', $record->userHandle); + $this->assertSame(42, $record->counter); + $this->assertTrue($record->uvInitialized); + } + + public function testSaveAndFindRoundTrip(): void { + $record = $this->createRecord('jane'); + + $this->mapper->method('findOneByCredentialId') + ->willThrowException(new DoesNotExistException('')); + $this->mapper->expects($this->once()) + ->method('insertOrUpdate') + ->willReturnArgument(0); + + $entity = $this->repository->saveCredentialSource($record, 'My key', true); + + $this->assertSame('My key', $entity->getName()); + $this->assertSame('jane', $entity->getUid()); + $this->assertSame(base64_encode('credential-id'), $entity->getPublicKeyCredentialId()); + $this->assertTrue($entity->getUserVerification()); + $this->assertEquals($record, $this->repository->mapToCredentialRecord($entity)); + } + + public function testSaveKeepsExistingEntity(): void { + $oldEntity = new PublicKeyCredentialEntity(); + $oldEntity->setId(17); + $oldEntity->setUid('jane'); + $oldEntity->setName('My key'); + $oldEntity->setUserVerification(true); + + $this->mapper->method('findOneByCredentialId') + ->with('credential-id') + ->willReturn($oldEntity); + $this->mapper->expects($this->once()) + ->method('insertOrUpdate') + ->willReturnArgument(0); + + $entity = $this->repository->saveCredentialSource($this->createRecord('jane')); + + $this->assertSame(17, $entity->getId()); + $this->assertSame('My key', $entity->getName()); + $this->assertTrue($entity->getUserVerification()); + } + + public function testSaveRejectsUidMismatch(): void { + $oldEntity = new PublicKeyCredentialEntity(); + $oldEntity->setId(17); + $oldEntity->setUid('john'); + + $this->mapper->method('findOneByCredentialId') + ->willReturn($oldEntity); + $this->mapper->expects($this->never()) + ->method('insertOrUpdate'); + + $this->expectException(\InvalidArgumentException::class); + $this->repository->saveCredentialSource($this->createRecord('jane')); + } + + public function testFindOneByCredentialIdNotFound(): void { + $this->mapper->method('findOneByCredentialId') + ->willThrowException(new DoesNotExistException('')); + + $this->assertNull($this->repository->findOneByCredentialId('credential-id')); + } + + private function createRecord(string $uid): CredentialRecord { + return CredentialRecord::create( + 'credential-id', + 'public-key', + ['usb'], + 'none', + EmptyTrustPath::create(), + Uuid::fromString('00000000-0000-0000-0000-000000000000'), + 'public-key', + $uid, + 0, + ); + } +} diff --git a/tests/lib/Authentication/WebAuthn/ManagerTest.php b/tests/lib/Authentication/WebAuthn/ManagerTest.php new file mode 100644 index 0000000000000..b3d2bccaaba27 --- /dev/null +++ b/tests/lib/Authentication/WebAuthn/ManagerTest.php @@ -0,0 +1,209 @@ +repository = $this->createMock(CredentialRepository::class); + $this->mapper = $this->createMock(PublicKeyCredentialMapper::class); + $this->manager = new Manager( + $this->repository, + $this->mapper, + $this->createMock(LoggerInterface::class), + $this->createMock(IConfig::class), + ); + } + + public function testStartRegistration(): void { + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('jane'); + $user->method('getDisplayName')->willReturn('Jane Doe'); + + $options = json_decode($this->manager->startRegistration($user, 'cloud.example.com:8443'), true, flags: JSON_THROW_ON_ERROR); + + $this->assertEquals(['name' => 'Nextcloud', 'id' => 'cloud.example.com'], $options['rp']); + $this->assertEquals(['name' => 'jane', 'id' => Base64UrlSafe::encodeUnpadded('jane'), 'displayName' => 'Jane Doe'], $options['user']); + $this->assertSame(32, strlen(Base64UrlSafe::decodeNoPadding($options['challenge']))); + $this->assertSame('none', $options['attestation']); + $this->assertSame(60000, $options['timeout']); + + $expectedAlgorithms = EdDSA::isSupported() + ? [Algorithms::COSE_ALGORITHM_ES256, Algorithms::COSE_ALGORITHM_EDDSA, Algorithms::COSE_ALGORITHM_PS256, Algorithms::COSE_ALGORITHM_RS256] + : [Algorithms::COSE_ALGORITHM_ES256, Algorithms::COSE_ALGORITHM_PS256, Algorithms::COSE_ALGORITHM_RS256]; + $this->assertSame( + array_map(fn (int $alg) => ['type' => 'public-key', 'alg' => $alg], $expectedAlgorithms), + $options['pubKeyCredParams'], + ); + } + + public function testFinishRegisterInvalidData(): void { + $this->expectException(\RuntimeException::class); + $this->manager->finishRegister('not json', 'My key', '{}'); + } + + public static function dataStartAuthenticationUserVerification(): array { + return [ + 'all devices verify the user' => [[true, true], 'required'], + 'one device without user verification' => [[true, false], 'discouraged'], + ]; + } + + #[\PHPUnit\Framework\Attributes\DataProvider('dataStartAuthenticationUserVerification')] + public function testStartAuthentication(array $userVerification, string $expected): void { + $entities = array_map(function (bool $uv) { + $entity = new PublicKeyCredentialEntity(); + $entity->setUserVerification($uv); + return $entity; + }, $userVerification); + $this->mapper->method('findAllForUid') + ->with('jane') + ->willReturn($entities); + $this->repository->method('mapToCredentialRecord') + ->willReturn($this->createRecord('public-key')); + + $options = json_decode($this->manager->startAuthentication('jane', 'cloud.example.com:8443'), true, flags: JSON_THROW_ON_ERROR); + + $this->assertSame('cloud.example.com', $options['rpId']); + $this->assertSame($expected, $options['userVerification']); + $this->assertSame(60000, $options['timeout']); + $this->assertCount(count($userVerification), $options['allowCredentials']); + $this->assertSame(['type' => 'public-key', 'id' => Base64UrlSafe::encodeUnpadded(self::CREDENTIAL_ID)], $options['allowCredentials'][0]); + } + + /** + * A PS256 credential must be verifiable on login, and plain HTTP is accepted for localhost. + */ + public function testFinishAuthenticationPS256OnLocalhost(): void { + [$requestOptions, $data] = $this->preparePS256Authentication('localhost', 'http://localhost:8080'); + + $this->repository->expects($this->once()) + ->method('saveCredentialSource') + ->with($this->callback(fn (CredentialRecord $record) => $record->counter === 1)); + + $authenticatorData = $this->manager->finishAuthentication($requestOptions, $data, 'jane'); + $this->assertTrue($authenticatorData->isUserVerified()); + } + + public function testFinishAuthenticationRequiresHttps(): void { + [$requestOptions, $data] = $this->preparePS256Authentication('cloud.example.com', 'http://cloud.example.com'); + + $this->repository->expects($this->never()) + ->method('saveCredentialSource'); + + $this->expectException(AuthenticatorResponseVerificationException::class); + $this->manager->finishAuthentication($requestOptions, $data, 'jane'); + } + + /** + * @return array{string, string} The serialized request options and the client response + */ + private function preparePS256Authentication(string $rpId, string $origin): array { + $rsa = openssl_pkey_get_details(openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]))['rsa']; + $privateKey = RsaKey::create([ + Key::TYPE => Key::TYPE_RSA, + RsaKey::DATA_N => $rsa['n'], + RsaKey::DATA_E => $rsa['e'], + RsaKey::DATA_D => $rsa['d'], + RsaKey::DATA_P => $rsa['p'], + RsaKey::DATA_Q => $rsa['q'], + RsaKey::DATA_DP => $rsa['dmp1'], + RsaKey::DATA_DQ => $rsa['dmq1'], + RsaKey::DATA_QI => $rsa['iqmp'], + ]); + $coseKey = MapObject::create() + ->add(UnsignedIntegerObject::create(Key::TYPE), UnsignedIntegerObject::create(Key::TYPE_RSA)) + ->add(UnsignedIntegerObject::create(Key::ALG), NegativeIntegerObject::create(Algorithms::COSE_ALGORITHM_PS256)) + ->add(NegativeIntegerObject::create(RsaKey::DATA_N), ByteStringObject::create($rsa['n'])) + ->add(NegativeIntegerObject::create(RsaKey::DATA_E), ByteStringObject::create($rsa['e'])); + $record = $this->createRecord((string)$coseKey); + + $entity = new PublicKeyCredentialEntity(); + $entity->setUserVerification(true); + $this->mapper->method('findAllForUid')->willReturn([$entity]); + $this->repository->method('mapToCredentialRecord')->willReturn($record); + $this->repository->method('findOneByCredentialId') + ->with(self::CREDENTIAL_ID) + ->willReturn($record); + + $requestOptions = $this->manager->startAuthentication('jane', $rpId); + $challenge = json_decode($requestOptions, true, flags: JSON_THROW_ON_ERROR)['challenge']; + + $clientDataJSON = json_encode([ + 'type' => 'webauthn.get', + 'challenge' => $challenge, + 'origin' => $origin, + 'crossOrigin' => false, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES); + // RP ID hash, flags (user present + user verified) and signature counter + $authenticatorData = hash('sha256', $rpId, true) . chr(0x05) . pack('N', 1); + $signature = PS256::create()->sign($authenticatorData . hash('sha256', $clientDataJSON, true), $privateKey); + + $data = json_encode([ + 'id' => Base64UrlSafe::encodeUnpadded(self::CREDENTIAL_ID), + 'rawId' => Base64UrlSafe::encodeUnpadded(self::CREDENTIAL_ID), + 'type' => 'public-key', + 'response' => [ + 'clientDataJSON' => Base64UrlSafe::encodeUnpadded($clientDataJSON), + 'authenticatorData' => Base64UrlSafe::encodeUnpadded($authenticatorData), + 'signature' => Base64UrlSafe::encodeUnpadded($signature), + 'userHandle' => Base64UrlSafe::encodeUnpadded('jane'), + ], + 'clientExtensionResults' => [], + ], JSON_THROW_ON_ERROR); + + return [$requestOptions, $data]; + } + + private function createRecord(string $credentialPublicKey): CredentialRecord { + return CredentialRecord::create( + self::CREDENTIAL_ID, + 'public-key', + [], + 'none', + EmptyTrustPath::create(), + Uuid::fromString('00000000-0000-0000-0000-000000000000'), + $credentialPublicKey, + 'jane', + 0, + ); + } +}