Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"php": ">=8.1",
"ext-json": "*",
"cakephp/cakephp": "^5.0",
"cakedc/users": "^14.3",
"cakedc/users": "^14.3.5",
"lcobucci/jwt": "~4.0.0",
"firebase/php-jwt": "^6.3"
},
Expand All @@ -43,7 +43,7 @@
"phpstan/phpstan": "^1.8",
"robthree/twofactorauth": "^1.6",
"vlucas/phpdotenv": "^3.3",
"web-auth/webauthn-lib": "^5.0"
"web-auth/webauthn-lib": "^4.4"
},
"autoload": {
"psr-4": {
Expand All @@ -58,7 +58,6 @@
}
},
"prefer-stable": true,
"minimum-stability": "dev",
"config": {
"sort-packages": true,
"allow-plugins": {
Expand Down
56 changes: 35 additions & 21 deletions src/Webauthn/AuthenticateAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@

namespace CakeDC\Api\Webauthn;

use Cake\Log\Log;
use Cake\Http\Exception\BadRequestException;
use Webauthn\AuthenticationExtensions\AuthenticationExtensionsClientInputs;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAssertionResponseValidator;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;

Expand All @@ -25,22 +28,20 @@ class AuthenticateAdapter extends BaseAdapter
public function getOptions(): PublicKeyCredentialRequestOptions
{
$userEntity = $this->getUserEntity();
$allowed = array_map(function (PublicKeyCredentialSource $credential) {
$allowedCredentials = array_map(function (PublicKeyCredentialSource $credential) {
return $credential->getPublicKeyCredentialDescriptor();
}, $this->repository->findAllForUserEntity($userEntity));
Log::error(print_r($allowed, true));

$options = $this->server->generatePublicKeyCredentialRequestOptions(
PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_PREFERRED,
$allowed
);
$options = (new PublicKeyCredentialRequestOptions(random_bytes(32)))
->setRpId($this->rpEntity->getId())
->setUserVerification(PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_PREFERRED)
->allowCredentials(...$allowedCredentials)
->setExtensions(new AuthenticationExtensionsClientInputs());

$storeEntity = $this->readStore();
Log::error(print_r($storeEntity, true));
$storeEntity['store'] = [];
$storeEntity = $this->patchStore($storeEntity, 'authenticateOptions', base64_encode(serialize($options)));
$res = $this->store->save($storeEntity);
Log::error(print_r($storeEntity, true));
Log::error(print_r($res, true));

return $options;
}
Expand All @@ -49,31 +50,44 @@ public function getOptions(): PublicKeyCredentialRequestOptions
* Verify the registration response
*
* @return \Webauthn\PublicKeyCredentialSource
* @throws \Throwable
*/
public function verifyResponse(): \Webauthn\PublicKeyCredentialSource
{
$storeEntity = $this->readStore();
Log::error(print_r($storeEntity, true));
$options = $this->getStore($storeEntity, 'authenticateOptions');
if ($options) {
$options = unserialize(base64_decode($options));
}
Log::error(print_r($options, true));

return $this->loadAndCheckAssertionResponse($options);
$publicKeyCredentialLoader = $this->createPublicKeyCredentialLoader();
$publicKeyCredential = $publicKeyCredentialLoader->loadArray($this->request->getData());
$authenticatorAssertionResponse = $publicKeyCredential->getResponse();
if ($authenticatorAssertionResponse instanceof AuthenticatorAssertionResponse) {
$authenticatorAssertionResponseValidator = $this->createAssertionResponseValidator();

return $authenticatorAssertionResponseValidator->check(
$publicKeyCredential->getRawId(),
$authenticatorAssertionResponse,
$options,
$this->request,
$this->getUserEntity()->getId(),
);
}

throw new BadRequestException(__d('cake_d_c/api', 'Could not validate credential response for authentication'));
}

/**
* @param \Webauthn\PublicKeyCredentialRequestOptions $options request options
* @return \Webauthn\PublicKeyCredentialSource
* @return \Webauthn\AuthenticatorAssertionResponseValidator
*/
protected function loadAndCheckAssertionResponse($options): PublicKeyCredentialSource
protected function createAssertionResponseValidator(): AuthenticatorAssertionResponseValidator
{
return $this->server->loadAndCheckAssertionResponse(
json_encode($this->request->getData()),
$options,
$this->getUserEntity(),
$this->request
return new AuthenticatorAssertionResponseValidator(
$this->repository,
null,
$this->createExtensionOutputCheckerHandler(),
$this->getAlgorithmManager()
);
}
}
59 changes: 59 additions & 0 deletions src/Webauthn/Base64Utility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);

/**
* Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

namespace CakeDC\Api\Webauthn;

use InvalidArgumentException;
use ParagonIE\ConstantTime\Base64UrlSafe;

/**
* Base64Utility class
*/
class Base64Utility
{
/**
* @param string $data The data to encode
* @return string
*/
public static function complyEncodedNoPadding(string $data): string
{
return Base64UrlSafe::encodeUnpadded(static::basicDecode($data));
}

/**
* @param string $data The data to encode
* @param bool $usePadding If true, the "=" padding at end of the encoded value are kept, else it is removed
* @return string The data encoded
*/
public static function basicEncode(string $data, bool $usePadding = false): string
{
$encoded = strtr(base64_encode($data), '+/', '-_');

return $usePadding === true ? $encoded : rtrim($encoded, '=');
}

/**
* @param string $data The data to decode
* @throws \InvalidArgumentException
* @return string The data decoded
*/
public static function basicDecode(string $data): string
{
$decoded = base64_decode(strtr($data, '-_', '+/'), true);
if ($decoded === false) {
throw new InvalidArgumentException('Invalid data provided');
}

return $decoded;
}
}
116 changes: 104 additions & 12 deletions src/Webauthn/BaseAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,25 @@
use CakeDC\Api\Utility\RequestParser;
use CakeDC\Api\Webauthn\Repository\UserCredentialSourceRepository;
use CakeDC\Users\Model\Table\UsersTable;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Algorithm\Signature\ECDSA\ES256K;
use Cose\Algorithm\Signature\ECDSA\ES384;
use Cose\Algorithm\Signature\ECDSA\ES512;
use Cose\Algorithm\Signature\EdDSA\Ed256;
use Cose\Algorithm\Signature\EdDSA\Ed512;
use Cose\Algorithm\Signature\RSA\PS256;
use Cose\Algorithm\Signature\RSA\PS384;
use Cose\Algorithm\Signature\RSA\PS512;
use Cose\Algorithm\Signature\RSA\RS256;
use Cose\Algorithm\Signature\RSA\RS384;
use Cose\Algorithm\Signature\RSA\RS512;
use Webauthn\AttestationStatement\AttestationObjectLoader;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\AttestationStatement\NoneAttestationStatementSupport;
use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler;
use Webauthn\PublicKeyCredentialRpEntity;
use Webauthn\PublicKeyCredentialUserEntity;
use Webauthn\Server;

class BaseAdapter
{
Expand All @@ -39,20 +55,30 @@ class BaseAdapter
protected $repository;

/**
* @var \Webauthn\Server
* @var \Cake\Datasource\EntityInterface|\CakeDC\Users\Model\Entity\User
*/
protected $server;
private $user;

/**
* @var \Cake\Datasource\EntityInterface|\CakeDC\Users\Model\Entity\User
* @var \Webauthn\PublicKeyCredentialRpEntity
*/
private $user;
protected PublicKeyCredentialRpEntity $rpEntity;

/**
* @var \CakeDC\Api\Model\Table\AuthStoreTable
*/
protected $store;

/**
* @var \Webauthn\AttestationStatement\AttestationStatementSupportManager|null
*/
protected ?AttestationStatementSupportManager $attestationStatementSupportManager = null;

/**
* @var \Cose\Algorithm\Manager|null
*/
protected ?Manager $algorithmManager = null;

/**
* Constructor.
*
Expand All @@ -67,7 +93,7 @@ public function __construct(ServerRequest $request, ?UsersTable $usersTable, $us
$store = TableRegistry::getTableLocator()->get('CakeDC/Api.AuthStore');
$this->store = $store;
$session = $this->readStore();
$rpEntity = new PublicKeyCredentialRpEntity(
$this->rpEntity = new PublicKeyCredentialRpEntity(
Configure::read('Api.Webauthn2fa.' . $this->getDomain() . '.appName'), // The application name
Configure::read('Api.Webauthn2fa.' . $this->getDomain() . '.id')
);
Expand All @@ -81,11 +107,6 @@ public function __construct(ServerRequest $request, ?UsersTable $usersTable, $us
$this->user,
$usersTable
);

$this->server = new Server(
$rpEntity,
$this->repository
);
}

/**
Expand All @@ -107,7 +128,7 @@ protected function getUserEntity(): PublicKeyCredentialUserEntity
/**
* Get the user.
*
* @return array|mixed|null
* @return mixed|array|null
*/
public function getUser()
{
Expand Down Expand Up @@ -229,4 +250,75 @@ public function getDomain($replace = true)
{
return RequestParser::getDomain($this->request, $replace);
}

/**
* @param \Webauthn\AttestationStatement\AttestationStatementSupportManager $attestationStatementSupportManager manager instance
* @return void
*/
public function setAttestationStatementSupportManager(
AttestationStatementSupportManager $attestationStatementSupportManager
): void {
$this->attestationStatementSupportManager = $attestationStatementSupportManager;
}

/**
* @return \Webauthn\AttestationStatement\AttestationStatementSupportManager
*/
protected function getAttestationStatementSupportManager(): AttestationStatementSupportManager
{
if ($this->attestationStatementSupportManager === null) {
$this->attestationStatementSupportManager = new AttestationStatementSupportManager();
$this->attestationStatementSupportManager
->add(new NoneAttestationStatementSupport());
}

return $this->attestationStatementSupportManager;
}

/**
* @return \CakeDC\Api\Webauthn\PublicKeyCredentialLoader
*/
protected function createPublicKeyCredentialLoader(): PublicKeyCredentialLoader
{
$attestationObjectLoader = new AttestationObjectLoader(
$this->getAttestationStatementSupportManager()
);

return new PublicKeyCredentialLoader(
$attestationObjectLoader
);
}

/**
* @return \Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler
*/
protected function createExtensionOutputCheckerHandler(): ExtensionOutputCheckerHandler
{
return new ExtensionOutputCheckerHandler();
}

/**
* @return \Cose\Algorithm\Manager
*/
protected function getAlgorithmManager(): Manager
{
if ($this->algorithmManager === null) {
$this->algorithmManager = Manager::create()->add(
ES256::create(),
ES256K::create(),
ES384::create(),
ES512::create(),
RS256::create(),
RS384::create(),
RS512::create(),
PS256::create(),
PS384::create(),
PS512::create(),
Ed256::create(),
Ed512::create(),
);
}

return $this->algorithmManager;
}
}
37 changes: 37 additions & 0 deletions src/Webauthn/PublicKeyCredentialLoader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);

/**
* Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

namespace CakeDC\Api\Webauthn;

use Webauthn\PublicKeyCredential;

class PublicKeyCredentialLoader extends \Webauthn\PublicKeyCredentialLoader
{
/**
* @inheritDoc
*/
public function loadArray(array $json): PublicKeyCredential
{
if (isset($json['response']['clientDataJSON']) && is_string($json['response']['clientDataJSON'])) {
$json['response']['clientDataJSON'] =
Base64Utility::complyEncodedNoPadding($json['response']['clientDataJSON']);
}

if (isset($json['response']['authenticatorData']) && is_string($json['response']['authenticatorData'])) {
$json['response']['authenticatorData'] =
Base64Utility::complyEncodedNoPadding($json['response']['authenticatorData']);
}

return parent::loadArray($json);
}
}
Loading
Loading