Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,336 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function array_merge;
use CBOR\Decoder;
use CBOR\Normalizable;
use Cose\Algorithms;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use function count;
use function in_array;
use function openssl_verify;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitTagging;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use function sprintf;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class AndroidKeyAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_ANDROID = '1.3.6.1.4.1.11129.2.1.17';
/**
* Tags of the AuthorizationList members that are inspected during the verification procedure.
*
* @see https://source.android.com/docs/security/features/keystore/attestation#schema
*/
private const ANDROID_TAG_PURPOSE = 1;
private const ANDROID_TAG_ALL_APPLICATIONS = 600;
private const ANDROID_TAG_ORIGIN = 702;
private const KM_PURPOSE_SIGN = 2;
private const KM_ORIGIN_GENERATED = 0;
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'android-key';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create($attestation);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
foreach (['sig', 'x5c', 'alg'] as $key) {
array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('The attestation statement value "%s" is missing.', $key)
);
}
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
(is_countable($certificates) ? count(
$certificates
) : 0) > 0 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createBasic(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid trust path. Shall contain certificates.'
);
$certificates = $trustPath->certificates;
// Decode leaf attestation certificate
$leaf = $certificates[0];
$this->checkCertificate($leaf, $clientDataJSONHash, $authenticatorData);
$signedData = $authenticatorData->authData . $clientDataJSONHash;
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$alg = (int) $algRaw;
/** @var string $sig */
$sig = $attestationStatement->get('sig');
return openssl_verify($signedData, $sig, $leaf, Algorithms::getOpensslAlgorithmFor($alg)) === 1;
}
/**
* @see https://www.w3.org/TR/webauthn-3/#sctn-android-key-attestation
*/
private function checkCertificate(
string $certificate,
string $clientDataHash,
AuthenticatorData $authenticatorData
): void {
// Check that authData publicKey matches the public key in the attestation certificate
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential data found'
);
$publicKeyData = $attestedCredentialData->credentialPublicKey;
$publicKeyData !== null || throw AttestationStatementVerificationException::create(
'No attested public key found'
);
$publicDataStream = new StringStream($publicKeyData);
$coseKey = $this->decoder->decode($publicDataStream);
$coseKey instanceof Normalizable || throw AttestationStatementVerificationException::create(
'Invalid attested public key found'
);
$publicDataStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key data. Presence of extra bytes.'
);
$publicDataStream->close();
/** @var array<int, mixed> $coseKeyData */
$coseKeyData = $coseKey->normalize();
$publicKey = Key::createFromData($coseKeyData);
($publicKey instanceof Ec2Key) || ($publicKey instanceof RsaKey) || throw AttestationStatementVerificationException::create(
'Unsupported key type'
);
/* --------------------------- */
/**
* @see https://w3c.github.io/webauthn/#sctn-key-attstn-cert-requirements
* @see https://source.android.com/docs/security/features/keystore/attestation#attestation-certificate
*/
$cert = Certificate::fromPEM(PEM::fromString($certificate));
// We check the attested key corresponds to the key in the certificate
PEM::fromString($publicKey->asPEM())->string() === $cert->tbsCertificate()
->subjectPublicKeyInfo()
->toPEM()
->string() || throw AttestationStatementVerificationException::create('Invalid key');
$extensions = $cert->tbsCertificate()
->extensions();
// Find Android KeyStore Extension with OID self::OID_ANDROID in certificate extensions
$extensions->has(self::OID_ANDROID) || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_ANDROID . '" is missing'
);
/** @var UnknownExtension $androidExtension */
$androidExtension = $extensions->get(self::OID_ANDROID);
/**
* Parse the Android extension value structure
* @see https://source.android.com/docs/security/features/keystore/attestation#attestation-extension
*/
$extensionAsAsn1 = Sequence::fromDER($androidExtension->extensionValue());
// Check that attestationChallenge is set to the clientDataHash.
$extensionAsAsn1->has(4) || throw AttestationStatementVerificationException::create(
'The attestationChallenge field is missing'
);
$ext = $extensionAsAsn1->at(4)
->asElement();
$ext instanceof OctetString || throw AttestationStatementVerificationException::create(
'The attestationChallenge field must be an OctetString'
);
$clientDataHash === $ext->string() || throw AttestationStatementVerificationException::create(
'The client data hash is not valid'
);
// Check that both teeEnforced and softwareEnforced structures don't contain allApplications(600) tag.
$extensionAsAsn1->has(6) || throw AttestationStatementVerificationException::create(
'The softwareEnforced field is missing'
);
$softwareEnforcedFlags = $extensionAsAsn1->at(6)
->asElement();
$softwareEnforcedFlags instanceof Sequence || throw AttestationStatementVerificationException::create(
'The softwareEnforced field must be a Sequence'
);
$this->checkAbsenceOfAllApplicationsTag($softwareEnforcedFlags);
$extensionAsAsn1->has(7) || throw AttestationStatementVerificationException::create(
'The teeEnforced field is missing'
);
$teeEnforcedFlags = $extensionAsAsn1->at(7)
->asElement();
$teeEnforcedFlags instanceof Sequence || throw AttestationStatementVerificationException::create(
'The teeEnforced field must be a Sequence'
);
$this->checkAbsenceOfAllApplicationsTag($teeEnforcedFlags);
$this->checkKeyOriginAndPurpose($softwareEnforcedFlags, $teeEnforcedFlags);
}
/**
* The union of both authorization lists is used, which is what the specification mandates unless the Relying Party
* decides to accept keys from a trusted execution environment only.
*
* @see https://w3c.github.io/webauthn/#sctn-android-key-attestation
*/
private function checkKeyOriginAndPurpose(Sequence $softwareEnforced, Sequence $teeEnforced): void
{
$origins = [];
$purposes = [];
foreach ([$softwareEnforced, $teeEnforced] as $authorizationList) {
$origin = $this->findOrigin($authorizationList);
if ($origin !== null) {
$origins[] = $origin;
}
$purposes = array_merge($purposes, $this->findPurposes($authorizationList));
}
$origins !== [] || throw AttestationStatementVerificationException::create(
'The origin field is missing from the authorization lists'
);
foreach ($origins as $origin) {
$origin === self::KM_ORIGIN_GENERATED || throw AttestationStatementVerificationException::create(
'The key was not generated by the authenticator'
);
}
$purposes !== [] || throw AttestationStatementVerificationException::create(
'The purpose field is missing from the authorization lists'
);
in_array(self::KM_PURPOSE_SIGN, $purposes, true) || throw AttestationStatementVerificationException::create(
'The key is not allowed to sign'
);
}
private function findOrigin(Sequence $authorizationList): null|int
{
$element = $this->findTaggedElement($authorizationList, self::ANDROID_TAG_ORIGIN);
if ($element === null) {
return null;
}
return $element->explicit()
->asInteger()
->intNumber();
}
/**
* @return list<int>
*/
private function findPurposes(Sequence $authorizationList): array
{
$element = $this->findTaggedElement($authorizationList, self::ANDROID_TAG_PURPOSE);
if ($element === null) {
return [];
}
$purposes = [];
foreach ($element->explicit()->asSet()->elements() as $purpose) {
$purposes[] = $purpose->asInteger()
->intNumber();
}
return $purposes;
}
private function findTaggedElement(Sequence $authorizationList, int $tag): null|ExplicitTagging
{
foreach ($authorizationList->elements() as $item) {
$element = $item->asElement();
$element instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
'Invalid tag'
);
if ($element->tag() === $tag) {
return $element;
}
}
return null;
}
private function checkAbsenceOfAllApplicationsTag(Sequence $sequence): void
{
foreach ($sequence->elements() as $tag) {
$element = $tag->asElement();
$element instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
'Invalid tag'
);
$element->tag() !== self::ANDROID_TAG_ALL_APPLICATIONS || throw AttestationStatementVerificationException::create(
'The allApplications tag (' . self::ANDROID_TAG_ALL_APPLICATIONS . ') is forbidden - key must be bound to specific application'
);
}
}
}

View file

@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\Normalizable;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use Cose\Key\RsaKey;
use function count;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitTagging;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class AppleAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_APPLE = '1.2.840.113635.100.8.2';
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'apple';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
array_key_exists('x5c', $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" is missing.'
);
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
(is_countable($certificates) ? count(
$certificates
) : 0) > 0 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createAnonymizationCA(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid trust path'
);
$certificates = $trustPath->certificates;
// Decode leaf attestation certificate
$leaf = $certificates[0];
$this->checkCertificateAndGetPublicKey($leaf, $clientDataJSONHash, $authenticatorData);
return true;
}
/**
* @see https://www.w3.org/TR/webauthn-3/#sctn-apple-anonymous-attestation
*/
private function checkCertificateAndGetPublicKey(
string $certificate,
string $clientDataHash,
AuthenticatorData $authenticatorData
): void {
// Check that authData publicKey matches the public key in the attestation certificate
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential data found'
);
$publicKeyData = $attestedCredentialData->credentialPublicKey;
$publicKeyData !== null || throw AttestationStatementVerificationException::create(
'No attested public key found'
);
$publicDataStream = new StringStream($publicKeyData);
$coseKey = $this->decoder->decode($publicDataStream);
$coseKey instanceof Normalizable || throw AttestationStatementVerificationException::create(
'Invalid attested public key found'
);
$publicDataStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key data. Presence of extra bytes.'
);
$publicDataStream->close();
/** @var array<int, mixed> $coseKeyData */
$coseKeyData = $coseKey->normalize();
$publicKey = Key::createFromData($coseKeyData);
($publicKey instanceof Ec2Key) || ($publicKey instanceof RsaKey) || throw AttestationStatementVerificationException::create(
'Unsupported key type'
);
/* --------------------------- */
$cert = Certificate::fromPEM(PEM::fromString($certificate));
// We check the attested key corresponds to the key in the certificate
PEM::fromString($publicKey->asPEM())->string() === $cert->tbsCertificate()
->subjectPublicKeyInfo()
->toPEM()
->string() || throw AttestationStatementVerificationException::create('Invalid key');
$extensions = $cert->tbsCertificate()
->extensions();
// Find Apple Extension with OID "1.2.840.113635.100.8.2" in certificate extensions
$extensions->has(self::OID_APPLE) || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is missing'
);
/** @var UnknownExtension $appleExtension */
$appleExtension = $extensions->get(self::OID_APPLE);
$extensionSequence = Sequence::fromDER($appleExtension->extensionValue());
$extensionSequence->has(0) || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is message'
);
$firstExtension = $extensionSequence->at(0);
$firstExtension->isTagged() || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is invalid'
);
$taggedExtension = $firstExtension->asTagged()
->asElement();
$taggedExtension instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is invalid'
);
$explicitExtension = $taggedExtension->explicit()
->asElement();
$explicitExtension instanceof OctetString || throw AttestationStatementVerificationException::create(
'The certificate extension "' . self::OID_APPLE . '" is invalid'
);
$extensionData = $explicitExtension->string();
$nonceToHash = $authenticatorData->authData . $clientDataHash;
$nonce = hash('sha256', $nonceToHash, true);
hash_equals($nonce, $extensionData) || throw AttestationStatementVerificationException::create(
'The client data hash is not valid'
);
}
}

View file

@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use Webauthn\AuthenticatorData;
use Webauthn\MetadataService\Statement\MetadataStatement;
class AttestationObject
{
public ?MetadataStatement $metadataStatement = null;
public function __construct(
public readonly string $rawAttestationObject,
public AttestationStatement $attStmt,
public readonly AuthenticatorData $authData
) {
}
public static function create(
string $rawAttestationObject,
AttestationStatement $attStmt,
AuthenticatorData $authData
): self {
return new self($rawAttestationObject, $attStmt, $authData);
}
}

View file

@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\Normalizable;
use function is_array;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Throwable;
use Webauthn\AuthenticatorDataLoader;
use Webauthn\Event\AttestationObjectLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\InvalidDataException;
use Webauthn\MetadataService\CanLogData;
use Webauthn\StringStream;
use Webauthn\Util\Base64;
class AttestationObjectLoader implements CanDispatchEvents, CanLogData
{
private LoggerInterface $logger;
private EventDispatcherInterface $dispatcher;
public function __construct(
private readonly AttestationStatementSupportManager $attestationStatementSupportManager
) {
$this->logger = new NullLogger();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(AttestationStatementSupportManager $attestationStatementSupportManager): self
{
return new self($attestationStatementSupportManager);
}
public function load(string $data): AttestationObject
{
try {
$this->logger->info('Trying to load the data', [
'data' => $data,
]);
$decodedData = Base64::decode($data);
$stream = new StringStream($decodedData);
$parsed = Decoder::create()->decode($stream);
$this->logger->info('Loading the Attestation Statement');
$parsed instanceof Normalizable || throw InvalidDataException::create(
$parsed,
'Invalid attestation object. Unexpected object.'
);
$attestationObject = $parsed->normalize();
$stream->isEOF() || throw InvalidDataException::create(
null,
'Invalid attestation object. Presence of extra bytes.'
);
$stream->close();
is_array($attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
array_key_exists('authData', $attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
array_key_exists('fmt', $attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
array_key_exists('attStmt', $attestationObject) || throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object'
);
/** @var array{fmt: string, authData: string, attStmt: array<string, mixed>} $attestationObject */
$attestationStatementSupport = $this->attestationStatementSupportManager->get($attestationObject['fmt']);
$attestationStatement = $attestationStatementSupport->load($attestationObject);
$this->logger->info('Attestation Statement loaded');
$this->logger->debug('Attestation Statement loaded', [
'attestationStatement' => $attestationStatement,
]);
$authData = $attestationObject['authData'];
$authDataLoader = AuthenticatorDataLoader::create();
$authenticatorData = $authDataLoader->load($authData);
$attestationObject = AttestationObject::create($data, $attestationStatement, $authenticatorData);
$this->logger->info('Attestation Object loaded');
$this->logger->debug('Attestation Object', [
'ed' => $attestationObject,
]);
$this->dispatcher->dispatch(AttestationObjectLoaded::create($attestationObject));
return $attestationObject;
} catch (Throwable $throwable) {
$this->logger->error('An error occurred', [
'exception' => $throwable,
]);
throw $throwable;
}
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
}

View file

@ -0,0 +1,97 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function sprintf;
use Webauthn\Exception\InvalidDataException;
use Webauthn\TrustPath\TrustPath;
class AttestationStatement
{
final public const TYPE_NONE = 'none';
final public const TYPE_BASIC = 'basic';
final public const TYPE_SELF = 'self';
final public const TYPE_ATTCA = 'attca';
final public const TYPE_ANONCA = 'anonca';
/**
* @param array<string, mixed> $attStmt
*/
public function __construct(
public readonly string $fmt,
public readonly array $attStmt,
public readonly string $type,
public readonly TrustPath $trustPath
) {
}
/**
* @param array<string, mixed> $attStmt
*/
public static function create(string $fmt, array $attStmt, string $type, TrustPath $trustPath): self
{
return new self($fmt, $attStmt, $type, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createNone(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_NONE, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createBasic(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_BASIC, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createSelf(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_SELF, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createAttCA(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_ATTCA, $trustPath);
}
/**
* @param array<string, mixed> $attStmt
*/
public static function createAnonymizationCA(string $fmt, array $attStmt, TrustPath $trustPath): self
{
return self::create($fmt, $attStmt, self::TYPE_ANONCA, $trustPath);
}
public function has(string $key): bool
{
return array_key_exists($key, $this->attStmt);
}
public function get(string $key): mixed
{
$this->has($key) || throw InvalidDataException::create($this->attStmt, sprintf(
'The attestation statement has no key "%s".',
$key
));
return $this->attStmt[$key];
}
}

View file

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use Webauthn\AuthenticatorData;
interface AttestationStatementSupport
{
public function name(): string;
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement;
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool;
}

View file

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function sprintf;
use Webauthn\Exception\InvalidDataException;
class AttestationStatementSupportManager
{
/**
* @param AttestationStatementSupport[] $attestationStatementSupports
*/
public function __construct(
private array $attestationStatementSupports = []
) {
$this->add(new NoneAttestationStatementSupport());
foreach ($attestationStatementSupports as $attestationStatementSupport) {
if ($attestationStatementSupport instanceof AttestationStatementSupportManagerAwareInterface) {
$attestationStatementSupport->setAttestationStatementSupportManager($this);
}
$this->add($attestationStatementSupport);
}
}
/**
* @param AttestationStatementSupport[] $attestationStatementSupports
*/
public static function create(array $attestationStatementSupports = []): self
{
return new self($attestationStatementSupports);
}
public function add(AttestationStatementSupport $attestationStatementSupport): void
{
$this->attestationStatementSupports[$attestationStatementSupport->name()] = $attestationStatementSupport;
}
public function has(string $name): bool
{
return array_key_exists($name, $this->attestationStatementSupports);
}
public function get(string $name): AttestationStatementSupport
{
$this->has($name) || throw InvalidDataException::create($name, sprintf(
'The attestation statement format "%s" is not supported.',
$name
));
return $this->attestationStatementSupports[$name];
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
interface AttestationStatementSupportManagerAwareInterface
{
public function setAttestationStatementSupportManager(AttestationStatementSupportManager $manager): void;
}

View file

@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
trait AttestationStatementSupportManagerAwareTrait
{
private AttestationStatementSupportManager $attestationStatementSupportManager;
public function setAttestationStatementSupportManager(AttestationStatementSupportManager $manager): void
{
$this->attestationStatementSupportManager = $manager;
}
}

View file

@ -0,0 +1,223 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use function count;
use InvalidArgumentException;
use function is_array;
use Psr\EventDispatcher\EventDispatcherInterface;
use function sprintf;
use Throwable;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidDataException;
use Webauthn\TrustPath\EmptyTrustPath;
/**
* Compound Attestation Statement Support
*
* Supports the "compound" attestation format as defined in WebAuthn Level 3
* @see https://w3c.github.io/webauthn/#sctn-compound-attestation
*
* The compound format allows multiple attestation statements of different formats
* to be included together. This is useful for hybrid authenticators or scenarios
* where multiple attestation proofs are needed.
*/
final class CompoundAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents, AttestationStatementSupportManagerAwareInterface
{
use AttestationStatementSupportManagerAwareTrait;
private const ATTESTATION_TYPE_TRUST_ORDER = [
AttestationStatement::TYPE_ATTCA,
AttestationStatement::TYPE_ANONCA,
AttestationStatement::TYPE_BASIC,
AttestationStatement::TYPE_SELF,
AttestationStatement::TYPE_NONE,
];
private EventDispatcherInterface $dispatcher;
private ?float $ratio = 1.0;
private ?int $minimum = null;
public function __construct()
{
$this->dispatcher = new NullEventDispatcher();
$this->attestationStatementSupportManager = AttestationStatementSupportManager::create();
}
public function setMinimum(int $minimum): void
{
$this->checkRules(null, $minimum);
$this->minimum = $minimum;
$this->ratio = null;
}
public function setRatio(float $ratio): void
{
$this->checkRules($ratio, null);
$this->ratio = $ratio;
$this->minimum = null;
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'compound';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create($attestation);
is_array($attestation['attStmt']) || throw AttestationStatementLoadingException::create($attestation);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
$loadedAttestations = [];
foreach ($attStmt as $index => $nestedAttestationObject) {
is_array($nestedAttestationObject) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('Attestation at index %s must be an array.', (string) $index)
);
array_key_exists('fmt', $nestedAttestationObject) || throw InvalidDataException::create(
$nestedAttestationObject,
'Invalid attestation object'
);
/** @var string $fmt */
$fmt = $nestedAttestationObject['fmt'];
$fmt !== 'compound' || throw InvalidDataException::create(
$nestedAttestationObject,
'Compound attestation object in a compound attestation is not allowed.'
);
array_key_exists('attStmt', $nestedAttestationObject) || throw InvalidDataException::create(
$nestedAttestationObject,
'Invalid attestation object'
);
$this->attestationStatementSupportManager->has($fmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('Unsupported attestation format "%s" at index %s.', $fmt, (string) $index)
);
/** @var array<string, mixed> $nestedAttestationObject */
$attestationStatementSupport = $this->attestationStatementSupportManager->get($fmt);
$loadedAttestations[] = $attestationStatementSupport->load($nestedAttestationObject);
}
/** @var string $compoundFmt */
$compoundFmt = $attestation['fmt'];
$attestationType = $this->deriveAttestationType($loadedAttestations);
// Create a compound attestation statement with compound trust path
$attestationStatement = AttestationStatement::create(
$compoundFmt,
$loadedAttestations,
$attestationType,
EmptyTrustPath::create()
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
count($attestationStatement->attStmt) > 1 || throw AttestationStatementVerificationException::create(
'Compound attestation must contain at least two attestations.'
);
// Verify all nested attestations
$countValid = 0;
$total = count($attestationStatement->attStmt);
foreach ($attestationStatement->attStmt as $nestedAttestationObject) {
/** @var AttestationStatement $nestedAttestationObject */
$attestationStatementSupport = $this->attestationStatementSupportManager->get(
$nestedAttestationObject->fmt
);
try {
$isValid = $attestationStatementSupport->isValid(
$clientDataJSONHash,
$nestedAttestationObject,
$authenticatorData
);
if ($isValid) {
$countValid++;
}
} catch (Throwable) {
// Nothing to do
}
}
if ($this->minimum !== null) {
return $countValid >= $this->minimum;
}
return $countValid / $total >= $this->ratio;
}
/**
* Derives the compound attestation type from the nested attestation types
* by selecting the weakest (least trusted) type among them.
*
* @param array<AttestationStatement> $loadedAttestations
*/
private function deriveAttestationType(array $loadedAttestations): string
{
$weakest = 0;
foreach ($loadedAttestations as $stmt) {
$index = array_search($stmt->type, self::ATTESTATION_TYPE_TRUST_ORDER, true);
if ($index === false) {
return AttestationStatement::TYPE_NONE;
}
if ($index > $weakest) {
$weakest = $index;
}
}
return self::ATTESTATION_TYPE_TRUST_ORDER[$weakest];
}
private function checkRules(?float $ratio, ?int $minimum): void
{
if ($ratio !== null && ($ratio <= 0 || $ratio > 1)) {
throw new InvalidArgumentException('The ratio must be greater than 0 and less than or equal to 1.');
}
if ($minimum !== null && $minimum <= 1) {
throw new InvalidArgumentException('The minimum must be greater than 1.');
}
if ($ratio !== null && $minimum !== null) {
throw new InvalidArgumentException('You cannot define both ratio and minimum at the same time.');
}
if ($ratio === null && $minimum === null) {
throw new InvalidArgumentException('You must define either ratio or minimum.');
}
}
}

View file

@ -0,0 +1,191 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\MapObject;
use Cose\Key\Ec2Key;
use function count;
use function is_array;
use const OPENSSL_ALGO_SHA256;
use function openssl_pkey_get_public;
use function openssl_verify;
use OpenSSLAsymmetricKey;
use Psr\EventDispatcher\EventDispatcherInterface;
use function sprintf;
use Throwable;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class FidoU2FAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'fido-u2f';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
foreach (['sig', 'x5c'] as $key) {
array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('The attestation statement value "%s" is missing.', $key)
);
}
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
is_array($certificates) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with one certificate.'
);
count($certificates) === 1 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with one certificate.'
);
reset($certificates);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
$this->checkCertificate($certificates[0]);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createBasic(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$authenticatorData->attestedCredentialData
?->aaguid
->__toString() === '00000000-0000-0000-0000-000000000000' || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid AAGUID for fido-u2f attestation statement. Shall be "00000000-0000-0000-0000-000000000000"'
);
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid trust path'
);
$dataToVerify = "\0";
$dataToVerify .= $authenticatorData->rpIdHash;
$dataToVerify .= $clientDataJSONHash;
$dataToVerify .= $authenticatorData->attestedCredentialData
->credentialId;
$dataToVerify .= $this->extractPublicKey($authenticatorData->attestedCredentialData->credentialPublicKey);
/** @var string $sig */
$sig = $attestationStatement->get('sig');
return openssl_verify($dataToVerify, $sig, $trustPath->certificates[0], OPENSSL_ALGO_SHA256) === 1;
}
private function extractPublicKey(?string $publicKey): string
{
$publicKey !== null || throw AttestationStatementVerificationException::create(
'The attested credential data does not contain a valid public key.'
);
$publicKeyStream = new StringStream($publicKey);
$coseKey = $this->decoder->decode($publicKeyStream);
$publicKeyStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key. Presence of extra bytes.'
);
$publicKeyStream->close();
$coseKey instanceof MapObject || throw AttestationStatementVerificationException::create(
'The attested credential data does not contain a valid public key.'
);
$coseKey = $coseKey->normalize();
$ec2Key = new Ec2Key($coseKey + [
Ec2Key::TYPE => 2,
Ec2Key::DATA_CURVE => Ec2Key::CURVE_P256,
]);
return "\x04" . $ec2Key->x() . $ec2Key->y();
}
private function checkCertificate(string $publicKey): void
{
try {
$resource = openssl_pkey_get_public($publicKey);
$resource !== false || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
/** @var OpenSSLAsymmetricKey $resource */
$details = openssl_pkey_get_details($resource);
} catch (Throwable $throwable) {
throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain',
$throwable
);
}
is_array($details) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
array_key_exists('ec', $details) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
/** @var array<string, mixed> $ec */
$ec = $details['ec'];
array_key_exists('curve_name', $ec) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
$ec['curve_name'] === 'prime256v1' || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
array_key_exists('curve_oid', $ec) || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
$ec['curve_oid'] === '1.2.840.10045.3.1.7' || throw AttestationStatementVerificationException::create(
'Invalid certificate or certificate chain'
);
}
}

View file

@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function count;
use function is_array;
use function is_string;
use Psr\EventDispatcher\EventDispatcherInterface;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\TrustPath\EmptyTrustPath;
final class NoneAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private EventDispatcherInterface $dispatcher;
public function __construct()
{
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(): self
{
return new self();
}
public function name(): string
{
return 'none';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
$format = $attestation['fmt'] ?? null;
$attestationStatement = $attestation['attStmt'] ?? [];
(is_string($format) && $format !== '') || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
(is_array(
$attestationStatement
) && $attestationStatement === []) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
$attestationStatement = AttestationStatement::createNone(
$format,
$attestationStatement,
EmptyTrustPath::create()
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
return count($attestationStatement->attStmt) === 0;
}
}

View file

@ -0,0 +1,305 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\MapObject;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\Signature;
use Cose\Algorithms;
use Cose\Key\Key;
use function count;
use function is_array;
use function is_string;
use function openssl_verify;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X501\ASN1\AttributeType;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\Exception\InvalidDataException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
use Webauthn\TrustPath\EmptyTrustPath;
use Webauthn\Util\CoseSignatureFixer;
final class PackedAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_FIDO_GEN_CE_AAGUID = '1.3.6.1.4.1.45724.1.1.4';
private readonly Decoder $decoder;
private EventDispatcherInterface $dispatcher;
public function __construct(
private readonly Manager $algorithmManager
) {
$this->decoder = Decoder::create();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(Manager $algorithmManager): self
{
return new self($algorithmManager);
}
public function name(): string
{
return 'packed';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
array_key_exists('sig', $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "sig" is missing.'
);
array_key_exists('alg', $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "alg" is missing.'
);
is_string($attStmt['sig']) || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "sig" is missing.'
);
return match (true) {
array_key_exists('x5c', $attStmt) => $this->loadBasicType($attestation),
default => $this->loadEmptyType($attestation),
};
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
return match (true) {
$trustPath instanceof CertificateTrustPath => $this->processWithCertificate(
$clientDataJSONHash,
$attestationStatement,
$authenticatorData,
$trustPath
),
$trustPath instanceof EmptyTrustPath => $this->processWithSelfAttestation(
$clientDataJSONHash,
$attestationStatement,
$authenticatorData
),
default => throw InvalidAttestationStatementException::create(
$attestationStatement,
'Unsupported attestation statement'
),
};
}
/**
* @param mixed[] $attestation
*/
private function loadBasicType(array $attestation): AttestationStatement
{
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
/** @var array<string> $certificates */
$certificates = $attStmt['x5c'];
is_array($certificates) || throw AttestationStatementVerificationException::create(
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
count($certificates) > 0 || throw AttestationStatementVerificationException::create(
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$certificates = CertificateToolbox::convertAllDERToPEM($certificates);
/** @var string $fmt */
$fmt = $attestation['fmt'];
$attestationStatement = AttestationStatement::createBasic(
$fmt,
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
/**
* @param mixed[] $attestation
*/
private function loadEmptyType(array $attestation): AttestationStatement
{
/** @var string $fmt */
$fmt = $attestation['fmt'];
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
$attestationStatement = AttestationStatement::createSelf($fmt, $attStmt, EmptyTrustPath::create());
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
// https://www.w3.org/TR/webauthn-3/#sctn-packed-attestation-cert-requirements
private function checkCertificate(string $attestnCert, AuthenticatorData $authenticatorData): void
{
$certificate = Certificate::fromPEM(PEM::fromString($attestnCert));
$tbsCertificate = $certificate->tbsCertificate();
// Check version (X.509 version 3 is encoded as 2)
$tbsCertificate->version() === TBSCertificate::VERSION_3 || throw AttestationStatementVerificationException::create(
'Invalid certificate version'
);
// Check subject field
$subject = $tbsCertificate->subject();
$subject->countOfType(
AttributeType::OID_COUNTRY_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-C must be set');
$subject->countOfType(
AttributeType::OID_ORGANIZATION_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-O must be set');
$subject->countOfType(
AttributeType::OID_ORGANIZATIONAL_UNIT_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-OU must be set');
$subject->countOfType(
AttributeType::OID_COMMON_NAME
) > 0 || throw AttestationStatementVerificationException::create('Certificate Subject-CN must be set');
$ouValue = $subject->firstValueOf('OU')
->stringValue();
$ouValue === 'Authenticator Attestation' || throw AttestationStatementVerificationException::create(
'Invalid certificate name. The Subject Organization Unit must be "Authenticator Attestation"'
);
// Check extensions
$extensions = $tbsCertificate->extensions();
// Check certificate is not a CA cert
$extensions->hasBasicConstraints() || throw AttestationStatementVerificationException::create(
'The Basic Constraints extension must have the CA component set to false'
);
! $extensions->basicConstraints()
->isCA() || throw AttestationStatementVerificationException::create(
'The Basic Constraints extension must have the CA component set to false'
);
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential available'
);
// id-fido-gen-ce-aaguid OID check
if ($extensions->has(self::OID_FIDO_GEN_CE_AAGUID)) {
/** @var UnknownExtension $aaguidExtension */
$aaguidExtension = $extensions->get(self::OID_FIDO_GEN_CE_AAGUID);
! $aaguidExtension->isCritical() || throw AttestationStatementVerificationException::create(
'Extension ' . self::OID_FIDO_GEN_CE_AAGUID . ' must not be marked as critical'
);
$aaguidElement = UnspecifiedType::fromDER($aaguidExtension->extensionValue())->asElement();
$aaguidElement instanceof OctetString || throw AttestationStatementVerificationException::create(
'Invalid ' . self::OID_FIDO_GEN_CE_AAGUID . ' extension format'
);
$aaguidValue = $aaguidElement->string();
hash_equals(
$attestedCredentialData->aaguid
->toBinary(),
$aaguidValue
) || throw AttestationStatementVerificationException::create(
'The value of the "aaguid" does not match with the certificate extension ' . self::OID_FIDO_GEN_CE_AAGUID
);
}
}
private function processWithCertificate(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData,
CertificateTrustPath $trustPath
): bool {
$certificates = $trustPath->certificates;
// Check leaf certificate
$this->checkCertificate($certificates[0], $authenticatorData);
// Get the COSE algorithm identifier and the corresponding OpenSSL one
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$coseAlgorithmIdentifier = (int) $algRaw;
$opensslAlgorithmIdentifier = Algorithms::getOpensslAlgorithmFor($coseAlgorithmIdentifier);
// Verification of the signature
$signedData = $authenticatorData->authData . $clientDataJSONHash;
/** @var string $sig */
$sig = $attestationStatement->get('sig');
$result = openssl_verify($signedData, $sig, $certificates[0], $opensslAlgorithmIdentifier);
return $result === 1;
}
private function processWithSelfAttestation(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$attestedCredentialData = $authenticatorData->attestedCredentialData;
$attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
'No attested credential available'
);
$credentialPublicKey = $attestedCredentialData->credentialPublicKey;
$credentialPublicKey !== null || throw AttestationStatementVerificationException::create(
'No credential public key available'
);
$publicKeyStream = new StringStream($credentialPublicKey);
$publicKey = $this->decoder->decode($publicKeyStream);
$publicKeyStream->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public key. Presence of extra bytes.'
);
$publicKeyStream->close();
$publicKey instanceof MapObject || throw AttestationStatementVerificationException::create(
'The attested credential data does not contain a valid public key.'
);
$publicKey = $publicKey->normalize();
$publicKey = new Key($publicKey);
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$alg = (int) $algRaw;
$publicKey->alg() === $alg || throw AttestationStatementVerificationException::create(
'The algorithm of the attestation statement and the key are not identical.'
);
$dataToVerify = $authenticatorData->authData . $clientDataJSONHash;
$algorithm = $this->algorithmManager->get($alg);
if (! $algorithm instanceof Signature) {
throw InvalidDataException::create($algorithm, 'Invalid algorithm');
}
/** @var string $sigForFix */
$sigForFix = $attestationStatement->get('sig');
$signature = CoseSignatureFixer::fix($sigForFix, $algorithm);
return $algorithm->verify($dataToVerify, $publicKey, $signature);
}
}

View file

@ -0,0 +1,461 @@
<?php
declare(strict_types=1);
namespace Webauthn\AttestationStatement;
use function array_key_exists;
use CBOR\Decoder;
use CBOR\MapObject;
use Cose\Algorithms;
use Cose\Key\Ec2Key;
use Cose\Key\Key;
use Cose\Key\OkpKey;
use Cose\Key\RsaKey;
use function count;
use DateTimeImmutable;
use function openssl_verify;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Psr\Clock\ClockInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
use SpomkyLabs\Pki\CryptoEncoding\PEM;
use SpomkyLabs\Pki\X509\Certificate\Certificate;
use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
use function sprintf;
use Symfony\Component\Clock\NativeClock;
use function unpack;
use Webauthn\AuthenticatorData;
use Webauthn\Event\AttestationStatementLoaded;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AttestationStatementLoadingException;
use Webauthn\Exception\AttestationStatementVerificationException;
use Webauthn\Exception\InvalidAttestationStatementException;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\StringStream;
use Webauthn\TrustPath\CertificateTrustPath;
final class TPMAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
{
private const OID_FIDO_GEN_CE_AAGUID = '1.3.6.1.4.1.45724.1.1.4';
private const OID_AIK_CERTIFICATE = '2.23.133.8.3';
private EventDispatcherInterface $dispatcher;
private readonly ClockInterface $clock;
public function __construct(null|ClockInterface $clock = null)
{
$this->clock = $clock ?? new NativeClock();
$this->dispatcher = new NullEventDispatcher();
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->dispatcher = $eventDispatcher;
}
public static function create(null|ClockInterface $clock = null): self
{
return new self($clock);
}
public function name(): string
{
return 'tpm';
}
/**
* @param array<string, mixed> $attestation
*/
public function load(array $attestation): AttestationStatement
{
array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var array<string, mixed> $attStmt */
$attStmt = $attestation['attStmt'];
foreach (['ver', 'ver', 'sig', 'alg', 'certInfo', 'pubArea'] as $key) {
array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
$attestation,
sprintf('The attestation statement value "%s" is missing.', $key)
);
}
$attStmt['ver'] === '2.0' || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var string $certInfoData */
$certInfoData = $attStmt['certInfo'];
$certInfo = $this->checkCertInfo($certInfoData);
bin2hex($certInfo['type']) === '8017' || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attestation object'
);
/** @var string $pubAreaData */
$pubAreaData = $attStmt['pubArea'];
$pubArea = $this->checkPubArea($pubAreaData);
$pubAreaAttestedNameAlg = substr($certInfo['attestedName'], 0, 2);
/** @var string $pubAreaRaw */
$pubAreaRaw = $attStmt['pubArea'];
$pubAreaHash = hash($this->getTPMHash($pubAreaAttestedNameAlg), $pubAreaRaw, true);
$attestedName = $pubAreaAttestedNameAlg . $pubAreaHash;
$attestedName === $certInfo['attestedName'] || throw AttestationStatementLoadingException::create(
$attestation,
'Invalid attested name'
);
$attStmt['parsedCertInfo'] = $certInfo;
$attStmt['parsedPubArea'] = $pubArea;
/** @var array<string> $x5c */
$x5c = $attStmt['x5c'];
$certificates = CertificateToolbox::convertAllDERToPEM($x5c);
count($certificates) > 0 || throw AttestationStatementLoadingException::create(
$attestation,
'The attestation statement value "x5c" must be a list with at least one certificate.'
);
$attestationStatement = AttestationStatement::createAttCA(
$this->name(),
$attStmt,
CertificateTrustPath::create($certificates)
);
$this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
return $attestationStatement;
}
public function isValid(
string $clientDataJSONHash,
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$attToBeSigned = $authenticatorData->authData . $clientDataJSONHash;
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$alg = (int) $algRaw;
$attToBeSignedHash = hash(Algorithms::getHashAlgorithmFor($alg), $attToBeSigned, true);
/** @var array{extraData: string} $parsedCertInfo */
$parsedCertInfo = $attestationStatement->get('parsedCertInfo');
$parsedCertInfo['extraData'] === $attToBeSignedHash || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Invalid attestation hash'
);
$credentialPublicKey = $authenticatorData->attestedCredentialData?->credentialPublicKey;
$credentialPublicKey !== null || throw InvalidAttestationStatementException::create(
$attestationStatement,
'Not credential public key available in the attested credential data'
);
/** @var array{unique: string} $parsedPubArea */
$parsedPubArea = $attestationStatement->get('parsedPubArea');
$this->checkUniquePublicKey($parsedPubArea['unique'], $credentialPublicKey);
return match (true) {
$attestationStatement->trustPath instanceof CertificateTrustPath => $this->processWithCertificate(
$attestationStatement,
$authenticatorData
),
default => throw InvalidAttestationStatementException::create(
$attestationStatement,
'Unsupported attestation statement'
),
};
}
private function checkUniquePublicKey(string $unique, string $cborPublicKey): void
{
$cborDecoder = Decoder::create();
$publicKey = $cborDecoder->decode(new StringStream($cborPublicKey));
$publicKey instanceof MapObject || throw AttestationStatementVerificationException::create(
'Invalid public key'
);
$key = Key::create($publicKey->normalize());
switch ($key->type()) {
case Key::TYPE_OKP:
$uniqueFromKey = (new OkpKey($key->getData()))->x();
break;
case Key::TYPE_EC2:
$ec2Key = new Ec2Key($key->getData());
$uniqueFromKey = "\x04" . $ec2Key->x() . $ec2Key->y();
break;
case Key::TYPE_RSA:
$uniqueFromKey = (new RsaKey($key->getData()))->n();
break;
default:
throw AttestationStatementVerificationException::create('Invalid or unsupported key type.');
}
$unique === $uniqueFromKey || throw AttestationStatementVerificationException::create(
'Invalid pubArea.unique value'
);
}
/**
* @return mixed[]
*/
/**
* @return array{magic: string, type: string, qualifiedSigner: string, extraData: string, clockInfo: string, firmwareVersion: string, attestedName: string, attestedQualifiedName: string}
*/
private function checkCertInfo(string $data): array
{
$certInfo = new StringStream($data);
$magic = $certInfo->read(4);
bin2hex($magic) === 'ff544347' || throw AttestationStatementVerificationException::create(
'Invalid attestation object'
);
$type = $certInfo->read(2);
/** @var array{1: int} $qualifiedSignerLengthData */
$qualifiedSignerLengthData = unpack('n', $certInfo->read(2));
$qualifiedSigner = $certInfo->read($qualifiedSignerLengthData[1]); // Ignored
/** @var array{1: int} $extraDataLengthData */
$extraDataLengthData = unpack('n', $certInfo->read(2));
$extraData = $certInfo->read($extraDataLengthData[1]);
$clockInfo = $certInfo->read(17); // Ignore
$firmwareVersion = $certInfo->read(8);
/** @var array{1: int} $attestedNameLengthData */
$attestedNameLengthData = unpack('n', $certInfo->read(2));
$attestedName = $certInfo->read($attestedNameLengthData[1]);
/** @var array{1: int} $attestedQualifiedNameLengthData */
$attestedQualifiedNameLengthData = unpack('n', $certInfo->read(2));
$attestedQualifiedName = $certInfo->read($attestedQualifiedNameLengthData[1]); // Ignore
$certInfo->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid certificate information. Presence of extra bytes.'
);
$certInfo->close();
return [
'magic' => $magic,
'type' => $type,
'qualifiedSigner' => $qualifiedSigner,
'extraData' => $extraData,
'clockInfo' => $clockInfo,
'firmwareVersion' => $firmwareVersion,
'attestedName' => $attestedName,
'attestedQualifiedName' => $attestedQualifiedName,
];
}
/**
* @return mixed[]
*/
private function checkPubArea(string $data): array
{
$pubArea = new StringStream($data);
$type = $pubArea->read(2);
$nameAlg = $pubArea->read(2);
$objectAttributes = $pubArea->read(4);
/** @var array{1: int} $authPolicyLengthData */
$authPolicyLengthData = unpack('n', $pubArea->read(2));
$authPolicy = $pubArea->read($authPolicyLengthData[1]);
$parameters = $this->getParameters($type, $pubArea);
$unique = $this->getUnique($type, $pubArea);
$pubArea->isEOF() || throw AttestationStatementVerificationException::create(
'Invalid public area. Presence of extra bytes.'
);
$pubArea->close();
return [
'type' => $type,
'nameAlg' => $nameAlg,
'objectAttributes' => $objectAttributes,
'authPolicy' => $authPolicy,
'parameters' => $parameters,
'unique' => $unique,
];
}
/**
* @return mixed[]
*/
private function getParameters(string $type, StringStream $stream): array
{
return match (bin2hex($type)) {
'0001' => $this->getRsaParameters($stream),
'0023' => [
'symmetric' => $stream->read(2),
'scheme' => $stream->read(2),
'curveId' => $stream->read(2),
'kdf' => $stream->read(2),
],
default => throw AttestationStatementVerificationException::create('Unsupported type'),
};
}
private function getUnique(string $type, StringStream $stream): string
{
switch (bin2hex($type)) {
case '0001':
/** @var array{1: int} $uniqueLengthData */
$uniqueLengthData = unpack('n', $stream->read(2));
return $stream->read($uniqueLengthData[1]);
case '0023':
/** @var array{1: int} $xLenData */
$xLenData = unpack('n', $stream->read(2));
$x = $stream->read($xLenData[1]);
/** @var array{1: int} $yLenData */
$yLenData = unpack('n', $stream->read(2));
$y = $stream->read($yLenData[1]);
return "\04" . $x . $y;
default:
throw AttestationStatementVerificationException::create('Unsupported type');
}
}
/**
* @return array{symmetric: string, scheme: string, keyBits: int, exponent: string}
*/
private function getRsaParameters(StringStream $stream): array
{
$symmetric = $stream->read(2);
$scheme = $stream->read(2);
/** @var array{1: int} $keyBitsData */
$keyBitsData = unpack('n', $stream->read(2));
return [
'symmetric' => $symmetric,
'scheme' => $scheme,
'keyBits' => $keyBitsData[1],
'exponent' => $this->getExponent($stream->read(4)),
];
}
private function getExponent(string $exponent): string
{
return bin2hex($exponent) === '00000000' ? Base64UrlSafe::decodeNoPadding('AQAB') : $exponent;
}
private function getTPMHash(string $nameAlg): string
{
return match (bin2hex($nameAlg)) {
'0004' => 'sha1',
'000b' => 'sha256',
'000c' => 'sha384',
'000d' => 'sha512',
default => throw AttestationStatementVerificationException::create('Unsupported hash algorithm'),
};
}
private function processWithCertificate(
AttestationStatement $attestationStatement,
AuthenticatorData $authenticatorData
): bool {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw AttestationStatementVerificationException::create(
'Invalid trust path'
);
$certificates = $trustPath->certificates;
// Check certificate CA chain and returns the Attestation Certificate
$this->checkCertificate($certificates[0], $authenticatorData);
// Get the COSE algorithm identifier and the corresponding OpenSSL one
/** @var int|string $algRaw */
$algRaw = $attestationStatement->get('alg');
$coseAlgorithmIdentifier = (int) $algRaw;
$opensslAlgorithmIdentifier = Algorithms::getOpensslAlgorithmFor($coseAlgorithmIdentifier);
/** @var string $certInfo */
$certInfo = $attestationStatement->get('certInfo');
/** @var string $sig */
$sig = $attestationStatement->get('sig');
$result = openssl_verify($certInfo, $sig, $certificates[0], $opensslAlgorithmIdentifier);
return $result === 1;
}
// https://www.w3.org/TR/webauthn-3/#sctn-tpm-cert-requirements
private function checkCertificate(string $attestnCert, AuthenticatorData $authenticatorData): void
{
$certificate = Certificate::fromPEM(PEM::fromString($attestnCert));
$tbsCertificate = $certificate->tbsCertificate();
// Version MUST be set to 3 (X.509 version 3 is encoded as 2)
$tbsCertificate->version() === TBSCertificate::VERSION_3 || throw AttestationStatementVerificationException::create(
'Invalid certificate version'
);
// Subject field MUST be set to empty
$tbsCertificate->subject()
->count() === 0 || throw AttestationStatementVerificationException::create(
'Invalid certificate name. The Subject should be empty'
);
// Check period of validity
$validity = $tbsCertificate->validity();
$startDate = DateTimeImmutable::createFromInterface($validity->notBefore()->dateTime());
$startDate < $this->clock->now() || throw AttestationStatementVerificationException::create(
'Invalid certificate start date.'
);
$endDate = DateTimeImmutable::createFromInterface($validity->notAfter()->dateTime());
$endDate > $this->clock->now() || throw AttestationStatementVerificationException::create(
'Invalid certificate end date.'
);
// Check extensions
$extensions = $tbsCertificate->extensions();
// Check Subject Alternative Name extension
$extensions->hasSubjectAlternativeName() || throw AttestationStatementVerificationException::create(
'The Subject Alternative Name extension must be set'
);
// Check Extended Key Usage extension MUST contain the OID 2.23.133.8.3
$extensions->hasExtendedKeyUsage() || throw AttestationStatementVerificationException::create(
'The Extended Key Usage extensions must contain ' . self::OID_AIK_CERTIFICATE,
);
$extendedKeyUsage = $extensions->extendedKeyUsage();
$extendedKeyUsage->has(self::OID_AIK_CERTIFICATE) || throw AttestationStatementVerificationException::create(
'The Extended Key Usage extensions must contain ' . self::OID_AIK_CERTIFICATE,
);
// The Basic Constraints extension MUST have the CA component set to false.
$extensions->basicConstraints()
->isCA() === false || throw AttestationStatementVerificationException::create(
'The Basic Constraints extension must have the CA component set to false'
);
// id-fido-gen-ce-aaguid OID check
if ($extensions->has(self::OID_FIDO_GEN_CE_AAGUID)) {
/** @var UnknownExtension $aaguidExtension */
$aaguidExtension = $extensions->get(self::OID_FIDO_GEN_CE_AAGUID);
$aaguidElement = UnspecifiedType::fromDER($aaguidExtension->extensionValue())->asElement();
$aaguidElement instanceof OctetString || throw AttestationStatementVerificationException::create(
'Invalid ' . self::OID_FIDO_GEN_CE_AAGUID . ' extension format'
);
$aaguidValue = $aaguidElement->string();
hash_equals(
$authenticatorData->attestedCredentialData
?->aaguid
->toBinary() ?? '',
$aaguidValue
) || throw AttestationStatementVerificationException::create(
'The value of the "aaguid" does not match with the certificate'
);
}
}
}

View file

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Symfony\Component\Uid\Uuid;
/**
* @see https://www.w3.org/TR/webauthn/#sec-attested-credential-data
*/
class AttestedCredentialData
{
public function __construct(
public Uuid $aaguid,
public readonly string $credentialId,
public readonly ?string $credentialPublicKey
) {
}
public static function create(Uuid $aaguid, string $credentialId, ?string $credentialPublicKey = null): self
{
return new self($aaguid, $credentialId, $credentialPublicKey);
}
}

View file

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class AppIdExcludeInputExtension extends AuthenticationExtension
{
public static function enable(string $value): AuthenticationExtension
{
return self::create('appidExclude', $value);
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class AppIdInputExtension extends AuthenticationExtension
{
public static function enable(): AuthenticationExtension
{
return self::create('appid', true);
}
public static function disable(): AuthenticationExtension
{
return self::create('appid', false);
}
}

View file

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
class AuthenticationExtension
{
public function __construct(
public readonly string $name,
public readonly mixed $value
) {
}
public static function create(string $name, mixed $value): self
{
return new self($name, $value);
}
}

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use CBOR\CBORObject;
use CBOR\MapObject;
use Webauthn\Exception\AuthenticationExtensionException;
abstract class AuthenticationExtensionLoader
{
public static function load(CBORObject $object): AuthenticationExtensions
{
$object instanceof MapObject || throw AuthenticationExtensionException::create('Invalid extension object');
/** @var array<string, mixed> $data */
$data = $object->normalize();
return AuthenticationExtensions::create(
array_map(
fn (mixed $value, string $key) => AuthenticationExtension::create($key, $value),
$data,
array_keys($data)
)
);
}
}

View file

@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use function array_key_exists;
use ArrayAccess;
use ArrayIterator;
use function count;
use const COUNT_NORMAL;
use Countable;
use function is_string;
use Iterator;
use IteratorAggregate;
use function sprintf;
use Webauthn\Exception\AuthenticationExtensionException;
/**
* @implements IteratorAggregate<string, AuthenticationExtension>
* @implements ArrayAccess<string, AuthenticationExtension>
*/
final class AuthenticationExtensions implements Countable, IteratorAggregate, ArrayAccess
{
/**
* @var array<string, AuthenticationExtension>
*/
public array $extensions;
/**
* @param array<array-key, mixed|AuthenticationExtension> $extensions
*/
public function __construct(array $extensions = [])
{
$list = [];
foreach ($extensions as $key => $extension) {
if ($extension instanceof AuthenticationExtension) {
$list[$extension->name] = $extension;
continue;
}
if (is_string($key)) {
$list[$key] = AuthenticationExtension::create($key, $extension);
continue;
}
throw new AuthenticationExtensionException('Invalid extension');
}
$this->extensions = $list;
}
/**
* @param array<array-key, AuthenticationExtension> $extensions
*/
public static function create(array $extensions = []): static
{
return new static($extensions);
}
public function has(string $key): bool
{
return array_key_exists($key, $this->extensions);
}
public function get(string $key): AuthenticationExtension
{
$this->has($key) || throw AuthenticationExtensionException::create(sprintf(
'The extension with key "%s" is not available',
$key
));
return $this->extensions[$key];
}
/**
* @return Iterator<string, AuthenticationExtension>
*/
public function getIterator(): Iterator
{
return new ArrayIterator($this->extensions);
}
/**
* @param 0|1 $mode
*/
public function count(int $mode = COUNT_NORMAL): int
{
return count($this->extensions, $mode);
}
public function offsetExists(mixed $offset): bool
{
return array_key_exists($offset, $this->extensions);
}
public function offsetGet(mixed $offset): AuthenticationExtension
{
return $this->extensions[$offset];
}
public function offsetSet(mixed $offset, mixed $value): void
{
if ($value === null) {
return;
}
if ($value instanceof AuthenticationExtension) {
$this->extensions[$value->name] = $value;
return;
}
if (is_string($offset)) {
$this->extensions[$offset] = AuthenticationExtension::create($offset, $value);
return;
}
throw new AuthenticationExtensionException('Invalid extension');
}
public function offsetUnset(mixed $offset): void
{
unset($this->extensions[$offset]);
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class CredentialPropertiesInputExtension extends AuthenticationExtension
{
public static function enable(): AuthenticationExtension
{
return self::create('credProps', true);
}
public static function disable(): AuthenticationExtension
{
return self::create('credProps', false);
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
interface ExtensionOutputChecker
{
public function check(AuthenticationExtensions $inputs, AuthenticationExtensions $outputs): void;
}

View file

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
class ExtensionOutputCheckerHandler
{
/**
* @var ExtensionOutputChecker[]
*/
private array $checkers = [];
public static function create(): self
{
return new self();
}
public function add(ExtensionOutputChecker $checker): void
{
$this->checkers[] = $checker;
}
public function check(AuthenticationExtensions $inputs, AuthenticationExtensions $outputs): void
{
foreach ($this->checkers as $checker) {
$checker->check($inputs, $outputs);
}
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use Exception;
use Throwable;
class ExtensionOutputError extends Exception
{
public function __construct(
public readonly AuthenticationExtension $authenticationExtension,
string $message = '',
int $code = 0,
?Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
}

View file

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use function assert;
use function in_array;
final class LargeBlobInputExtension extends AuthenticationExtension
{
public const REQUIRED = 'required';
public const PREFERRED = 'preferred';
public static function support(string $support): AuthenticationExtension
{
assert(in_array($support, [self::REQUIRED, self::PREFERRED], true), 'Invalid support value.');
return self::create('largeBlob', [
'support' => $support,
]);
}
public static function read(): AuthenticationExtension
{
return self::create('largeBlob', [
'read' => true,
]);
}
public static function write(string $value): AuthenticationExtension
{
return self::create('largeBlob', [
'write' => $value,
]);
}
}

View file

@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class PseudoRandomFunctionInputExtension extends AuthenticationExtension
{
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
use function array_key_exists;
use ParagonIE\ConstantTime\Base64UrlSafe;
final class PseudoRandomFunctionInputExtensionBuilder
{
/**
* @var array{eval?: array{first: string, second?: string}, evalByCredential?: array<string, array{first: string, second?: string}>}
*/
private array $values = [];
private function __construct()
{
}
public static function create(): self
{
return new self();
}
public function withInputs(string $first, null|string $second = null): self
{
$eval = [
'first' => Base64UrlSafe::encodeUnpadded($first),
];
if ($second !== null) {
$eval['second'] = Base64UrlSafe::encodeUnpadded($second);
}
$this->values['eval'] = $eval;
return $this;
}
/**
* The credential ID is expected in its raw binary form, as stored in a credential record. The specification requires
* the keys of the "evalByCredential" map to be the base64url encoding of the credential ID, so the encoding is done
* here and MUST NOT be done by the caller.
*/
public function withCredentialInputs(string $credentialId, string $first, null|string $second = null): self
{
$eval = [
'first' => Base64UrlSafe::encodeUnpadded($first),
];
if ($second !== null) {
$eval['second'] = Base64UrlSafe::encodeUnpadded($second);
}
if (! array_key_exists('evalByCredential', $this->values)) {
$this->values['evalByCredential'] = [];
}
$this->values['evalByCredential'][Base64UrlSafe::encodeUnpadded($credentialId)] = $eval;
return $this;
}
public function build(): PseudoRandomFunctionInputExtension
{
return new PseudoRandomFunctionInputExtension('prf', $this->values);
}
}

View file

@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Webauthn\AuthenticationExtensions;
final class UvmInputExtension extends AuthenticationExtension
{
public static function enable(): AuthenticationExtension
{
return self::create('uvm', true);
}
public static function disable(): AuthenticationExtension
{
return self::create('uvm', false);
}
}

View file

@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Webauthn\AttestationStatement\AttestationObject;
/**
* @see https://www.w3.org/TR/webauthn/#authenticatorassertionresponse
*/
class AuthenticatorAssertionResponse extends AuthenticatorResponse
{
public function __construct(
CollectedClientData $clientDataJSON,
public readonly AuthenticatorData $authenticatorData,
public readonly string $signature,
public readonly ?string $userHandle,
public readonly null|AttestationObject $attestationObject = null,
) {
parent::__construct($clientDataJSON);
}
public static function create(
CollectedClientData $clientDataJSON,
AuthenticatorData $authenticatorData,
string $signature,
?string $userHandle = null,
null|AttestationObject $attestationObject = null,
): self {
return new self($clientDataJSON, $authenticatorData, $signature, $userHandle, $attestationObject);
}
}

View file

@ -0,0 +1,188 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Throwable;
use function trigger_deprecation;
use Webauthn\CeremonyStep\CeremonyStepManager;
use Webauthn\Event\AuthenticatorAssertionResponseValidationFailedEvent;
use Webauthn\Event\AuthenticatorAssertionResponseValidationSucceededEvent;
use Webauthn\Event\BackupEligibilityChangedEvent;
use Webauthn\Event\BackupStatusChangedEvent;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\MetadataService\CanLogData;
class AuthenticatorAssertionResponseValidator implements CanLogData, CanDispatchEvents
{
private LoggerInterface $logger;
private EventDispatcherInterface $eventDispatcher;
public function __construct(
private readonly CeremonyStepManager $ceremonyStepManager
) {
$this->eventDispatcher = new NullEventDispatcher();
$this->logger = new NullLogger();
}
public static function create(CeremonyStepManager $ceremonyStepManager): self
{
return new self($ceremonyStepManager);
}
/**
* @see https://www.w3.org/TR/webauthn/#verifying-assertion
*/
public function check(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse $authenticatorAssertionResponse,
PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions,
string $host,
?string $userHandle,
): CredentialRecord {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::check()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
try {
$this->logger->info('Checking the authenticator assertion response', [
'credentialRecord' => $credentialRecord,
'authenticatorAssertionResponse' => $authenticatorAssertionResponse,
'publicKeyCredentialRequestOptions' => $publicKeyCredentialRequestOptions,
'host' => $host,
'userHandle' => $userHandle,
]);
$this->ceremonyStepManager->process(
$credentialRecord,
$authenticatorAssertionResponse,
$publicKeyCredentialRequestOptions,
$userHandle,
$host
);
// Store previous backup state values to detect changes
$previousBackupEligible = $credentialRecord->backupEligible;
$previousBackupStatus = $credentialRecord->backupStatus;
$credentialRecord->counter = $authenticatorAssertionResponse->authenticatorData->signCount; // 26.1.
$credentialRecord->backupEligible = $authenticatorAssertionResponse->authenticatorData->isBackupEligible(); // 26.2.
$credentialRecord->backupStatus = $authenticatorAssertionResponse->authenticatorData->isBackedUp(); // 26.2.
if ($credentialRecord->uvInitialized === false) {
$credentialRecord->uvInitialized = $authenticatorAssertionResponse->authenticatorData->isUserVerified(); // 26.3.
}
// Dispatch events if backup state changed
if ($previousBackupEligible !== $credentialRecord->backupEligible) {
$this->eventDispatcher->dispatch(
new BackupEligibilityChangedEvent(
$credentialRecord,
$previousBackupEligible,
$credentialRecord->backupEligible
)
);
}
if ($previousBackupStatus !== $credentialRecord->backupStatus) {
$this->eventDispatcher->dispatch(
new BackupStatusChangedEvent(
$credentialRecord,
$previousBackupStatus,
$credentialRecord->backupStatus
)
);
}
/*
* 26.3.
* OPTIONALLY, if response.attestationObject is present, update credentialRecord.attestationObject to the value of response.attestationObject and update credentialRecord.attestationClientDataJSON to the value of response.clientDataJSON.
*/
// All good. We can continue.
$this->logger->info('The assertion is valid');
$this->logger->debug('Credential Record', [
'credentialRecord' => $credentialRecord,
]);
$this->eventDispatcher->dispatch(
$this->createAuthenticatorAssertionResponseValidationSucceededEvent(
$authenticatorAssertionResponse,
$publicKeyCredentialRequestOptions,
$host,
$userHandle,
$credentialRecord
)
);
// 27.
return $credentialRecord;
} catch (AuthenticatorResponseVerificationException $throwable) {
$this->logger->error('An error occurred', [
'exception' => $throwable,
]);
$this->eventDispatcher->dispatch(
$this->createAuthenticatorAssertionResponseValidationFailedEvent(
$credentialRecord,
$authenticatorAssertionResponse,
$publicKeyCredentialRequestOptions,
$host,
$userHandle,
$throwable
)
);
throw $throwable;
}
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->eventDispatcher = $eventDispatcher;
}
protected function createAuthenticatorAssertionResponseValidationSucceededEvent(
AuthenticatorAssertionResponse $authenticatorAssertionResponse,
PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions,
string $host,
?string $userHandle,
CredentialRecord $credentialRecord
): AuthenticatorAssertionResponseValidationSucceededEvent {
return new AuthenticatorAssertionResponseValidationSucceededEvent(
$authenticatorAssertionResponse,
$publicKeyCredentialRequestOptions,
$host,
$userHandle,
$credentialRecord
);
}
protected function createAuthenticatorAssertionResponseValidationFailedEvent(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse $authenticatorAssertionResponse,
PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions,
string $host,
?string $userHandle,
Throwable $throwable
): AuthenticatorAssertionResponseValidationFailedEvent {
return new AuthenticatorAssertionResponseValidationFailedEvent(
$credentialRecord,
$authenticatorAssertionResponse,
$publicKeyCredentialRequestOptions,
$host,
$userHandle,
$throwable
);
}
}

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Webauthn\AttestationStatement\AttestationObject;
/**
* @see https://www.w3.org/TR/webauthn/#authenticatorattestationresponse
*/
class AuthenticatorAttestationResponse extends AuthenticatorResponse
{
/**
* @param string[] $transports
*/
public function __construct(
CollectedClientData $clientDataJSON,
public readonly AttestationObject $attestationObject,
public readonly array $transports = []
) {
parent::__construct($clientDataJSON);
}
/**
* @param string[] $transports
*/
public static function create(
CollectedClientData $clientDataJSON,
AttestationObject $attestationObject,
array $transports = []
): self {
return new self($clientDataJSON, $attestationObject, $transports);
}
}

View file

@ -0,0 +1,195 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Throwable;
use Webauthn\CeremonyStep\CeremonyStepManager;
use Webauthn\Event\AuthenticatorAttestationResponseValidationFailedEvent;
use Webauthn\Event\AuthenticatorAttestationResponseValidationSucceededEvent;
use Webauthn\Event\BackupEligibilityChangedEvent;
use Webauthn\Event\BackupStatusChangedEvent;
use Webauthn\Event\CanDispatchEvents;
use Webauthn\Event\NullEventDispatcher;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\MetadataService\CanLogData;
class AuthenticatorAttestationResponseValidator implements CanLogData, CanDispatchEvents
{
private LoggerInterface $logger;
private EventDispatcherInterface $eventDispatcher;
public function __construct(
private readonly CeremonyStepManager $ceremonyStepManager
) {
$this->eventDispatcher = new NullEventDispatcher();
$this->logger = new NullLogger();
}
public static function create(CeremonyStepManager $ceremonyStepManager): self
{
return new self($ceremonyStepManager);
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
{
$this->eventDispatcher = $eventDispatcher;
}
/**
* @see https://www.w3.org/TR/webauthn/#registering-a-new-credential
*/
public function check(
AuthenticatorAttestationResponse $authenticatorAttestationResponse,
PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions,
string $host,
): CredentialRecord {
try {
$this->logger->info('Checking the authenticator attestation response', [
'authenticatorAttestationResponse' => $authenticatorAttestationResponse,
'publicKeyCredentialCreationOptions' => $publicKeyCredentialCreationOptions,
'host' => $host,
]);
$credentialRecord = $this->createCredentialRecord(
$authenticatorAttestationResponse,
$publicKeyCredentialCreationOptions
);
$this->ceremonyStepManager->process(
$credentialRecord,
$authenticatorAttestationResponse,
$publicKeyCredentialCreationOptions,
$publicKeyCredentialCreationOptions->user->id,
$host
);
// Store previous backup state values to detect changes (will be null for new credentials)
$previousBackupEligible = $credentialRecord->backupEligible;
$previousBackupStatus = $credentialRecord->backupStatus;
$credentialRecord->counter = $authenticatorAttestationResponse->attestationObject->authData->signCount;
$credentialRecord->backupEligible = $authenticatorAttestationResponse->attestationObject->authData->isBackupEligible();
$credentialRecord->backupStatus = $authenticatorAttestationResponse->attestationObject->authData->isBackedUp();
$credentialRecord->uvInitialized = $authenticatorAttestationResponse->attestationObject->authData->isUserVerified();
// Dispatch events if backup state changed
if ($previousBackupEligible !== $credentialRecord->backupEligible) {
$this->eventDispatcher->dispatch(
new BackupEligibilityChangedEvent(
$credentialRecord,
$previousBackupEligible,
$credentialRecord->backupEligible
)
);
}
if ($previousBackupStatus !== $credentialRecord->backupStatus) {
$this->eventDispatcher->dispatch(
new BackupStatusChangedEvent(
$credentialRecord,
$previousBackupStatus,
$credentialRecord->backupStatus
)
);
}
$this->logger->info('The attestation is valid');
$this->logger->debug('Credential Record', [
'credentialRecord' => $credentialRecord,
]);
$this->eventDispatcher->dispatch(
$this->createAuthenticatorAttestationResponseValidationSucceededEvent(
$authenticatorAttestationResponse,
$publicKeyCredentialCreationOptions,
$host,
$credentialRecord
)
);
return $credentialRecord;
} catch (Throwable $throwable) {
$this->logger->error('An error occurred', [
'exception' => $throwable,
]);
$this->eventDispatcher->dispatch(
$this->createAuthenticatorAttestationResponseValidationFailedEvent(
$authenticatorAttestationResponse,
$publicKeyCredentialCreationOptions,
$host,
$throwable
)
);
throw $throwable;
}
}
protected function createAuthenticatorAttestationResponseValidationSucceededEvent(
AuthenticatorAttestationResponse $authenticatorAttestationResponse,
PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions,
string $host,
CredentialRecord $credentialRecord
): AuthenticatorAttestationResponseValidationSucceededEvent {
return new AuthenticatorAttestationResponseValidationSucceededEvent(
$authenticatorAttestationResponse,
$publicKeyCredentialCreationOptions,
$host,
$credentialRecord
);
}
protected function createAuthenticatorAttestationResponseValidationFailedEvent(
AuthenticatorAttestationResponse $authenticatorAttestationResponse,
PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions,
string $host,
Throwable $throwable
): AuthenticatorAttestationResponseValidationFailedEvent {
return new AuthenticatorAttestationResponseValidationFailedEvent(
$authenticatorAttestationResponse,
$publicKeyCredentialCreationOptions,
$host,
$throwable
);
}
private function createCredentialRecord(
AuthenticatorAttestationResponse $authenticatorAttestationResponse,
PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions,
): CredentialRecord {
$attestationObject = $authenticatorAttestationResponse->attestationObject;
$attestedCredentialData = $attestationObject->authData->attestedCredentialData;
$attestedCredentialData !== null || throw AuthenticatorResponseVerificationException::create(
'Not attested credential data'
);
$credentialId = $attestedCredentialData->credentialId;
$credentialPublicKey = $attestedCredentialData->credentialPublicKey;
$credentialPublicKey !== null || throw AuthenticatorResponseVerificationException::create(
'Not credential public key available in the attested credential data'
);
$userHandle = $publicKeyCredentialCreationOptions->user->id;
$transports = $authenticatorAttestationResponse->transports;
return CredentialRecord::create(
$credentialId,
PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY,
$transports,
$attestationObject->attStmt
->type,
$attestationObject->attStmt
->trustPath,
$attestedCredentialData->aaguid,
$credentialPublicKey,
$userHandle,
$attestationObject->authData
->signCount,
);
}
}

View file

@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use function ord;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
/**
* @see https://www.w3.org/TR/webauthn/#sec-authenticator-data
* @see https://www.w3.org/TR/webauthn/#flags
*/
class AuthenticatorData
{
final public const FLAG_UP = 0b00000001;
final public const FLAG_RFU1 = 0b00000010;
final public const FLAG_UV = 0b00000100;
final public const FLAG_BE = 0b00001000;
final public const FLAG_BS = 0b00010000;
final public const FLAG_RFU2 = 0b00100000;
final public const FLAG_AT = 0b01000000;
final public const FLAG_ED = 0b10000000;
public function __construct(
public readonly string $authData,
public readonly string $rpIdHash,
public readonly string $flags,
public readonly int $signCount,
public readonly null|AttestedCredentialData $attestedCredentialData,
public readonly null|AuthenticationExtensions $extensions
) {
}
public static function create(
string $authData,
string $rpIdHash,
string $flags,
int $signCount,
null|AttestedCredentialData $attestedCredentialData = null,
null|AuthenticationExtensions $extensions = null
): self {
return new self($authData, $rpIdHash, $flags, $signCount, $attestedCredentialData, $extensions);
}
public function isUserPresent(): bool
{
return 0 !== (ord($this->flags) & self::FLAG_UP);
}
public function isUserVerified(): bool
{
return 0 !== (ord($this->flags) & self::FLAG_UV);
}
public function isBackupEligible(): bool
{
return 0 !== (ord($this->flags) & self::FLAG_BE);
}
public function isBackedUp(): bool
{
return 0 !== (ord($this->flags) & self::FLAG_BS);
}
public function hasAttestedCredentialData(): bool
{
return 0 !== (ord($this->flags) & self::FLAG_AT);
}
public function hasExtensions(): bool
{
return 0 !== (ord($this->flags) & self::FLAG_ED);
}
public function getReservedForFutureUse1(): int
{
return ord($this->flags) & self::FLAG_RFU1;
}
public function getReservedForFutureUse2(): int
{
return ord($this->flags) & self::FLAG_RFU2;
}
}

View file

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use CBOR\ByteStringObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\NegativeIntegerObject;
use CBOR\TextStringObject;
use CBOR\UnsignedIntegerObject;
use function chr;
use function ord;
use Symfony\Component\Uid\Uuid;
use Webauthn\AuthenticationExtensions\AuthenticationExtensionLoader;
use Webauthn\Exception\InvalidDataException;
final readonly class AuthenticatorDataLoader
{
private Decoder $decoder;
private function __construct()
{
$this->decoder = Decoder::create();
}
public static function create(): self
{
return new self();
}
public function load(string $authData): AuthenticatorData
{
$authData = $this->fixIncorrectEdDSAKey($authData);
$authDataStream = new StringStream($authData);
$rp_id_hash = $authDataStream->read(32);
$flags = $authDataStream->read(1);
$signCountRaw = $authDataStream->read(4);
/** @var array{1: int} $signCount */
$signCount = unpack('N', $signCountRaw);
$attestedCredentialData = null;
if (0 !== (ord($flags) & AuthenticatorData::FLAG_AT)) {
$aaguid = Uuid::fromBinary($authDataStream->read(16));
$credentialLengthRaw = $authDataStream->read(2);
/** @var array{1: int} $credentialLength */
$credentialLength = unpack('n', $credentialLengthRaw);
$credentialId = $authDataStream->read($credentialLength[1]);
$credentialPublicKey = $this->decoder->decode($authDataStream);
$credentialPublicKey instanceof MapObject || throw InvalidDataException::create(
$authData,
'The data does not contain a valid credential public key.'
);
$attestedCredentialData = AttestedCredentialData::create(
$aaguid,
$credentialId,
(string) $credentialPublicKey
);
}
$extension = null;
if (0 !== (ord($flags) & AuthenticatorData::FLAG_ED)) {
$extension = $this->decoder->decode($authDataStream);
$extension = AuthenticationExtensionLoader::load($extension);
}
$authDataStream->isEOF() || throw InvalidDataException::create(
$authData,
'Invalid authentication data. Presence of extra bytes.'
);
$authDataStream->close();
return AuthenticatorData::create(
$authData,
$rp_id_hash,
$flags,
$signCount[1],
$attestedCredentialData,
$extension
);
}
private function fixIncorrectEdDSAKey(string $data): string
{
/** @var string $needle */
$needle = hex2bin('a301634f4b500327206745643235353139');
/** @var string $correct */
$correct = hex2bin('a401634f4b500327206745643235353139');
$position = strpos($data, $needle);
if ($position === false) {
return $data;
}
$begin = substr($data, 0, $position);
$end = substr($data, $position);
$end = str_replace($needle, $correct, $end);
$cbor = new StringStream($end);
$badKey = $this->decoder->decode($cbor);
($badKey instanceof MapObject && $cbor->isEOF()) || throw InvalidDataException::create(
$end,
'Invalid authentication data. Presence of extra bytes.'
);
$badX = $badKey->get(-2);
$badX instanceof ListObject || throw InvalidDataException::create($end, 'Invalid authentication data.');
/** @var list<string> $normalizedBadX */
$normalizedBadX = $badX->normalize();
$keyBytes = array_reduce(
$normalizedBadX,
static fn (string $carry, string $item): string => $carry . chr((int) $item),
''
);
$correctX = ByteStringObject::create($keyBytes);
$correctKey = MapObject::create()
->add(UnsignedIntegerObject::create(1), TextStringObject::create('OKP'))
->add(UnsignedIntegerObject::create(3), NegativeIntegerObject::create(-8))
->add(NegativeIntegerObject::create(-1), TextStringObject::create('Ed25519'))
->add(NegativeIntegerObject::create(-2), $correctX);
return $begin . $correctKey;
}
}

View file

@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace Webauthn;
/**
* @see https://www.w3.org/TR/webauthn/#authenticatorresponse
*/
abstract class AuthenticatorResponse
{
public function __construct(
public readonly CollectedClientData $clientDataJSON
) {
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use function in_array;
use InvalidArgumentException;
class AuthenticatorSelectionCriteria
{
final public const AUTHENTICATOR_ATTACHMENT_NO_PREFERENCE = null;
final public const AUTHENTICATOR_ATTACHMENT_PLATFORM = 'platform';
final public const AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM = 'cross-platform';
final public const AUTHENTICATOR_ATTACHMENTS = [
self::AUTHENTICATOR_ATTACHMENT_NO_PREFERENCE,
self::AUTHENTICATOR_ATTACHMENT_PLATFORM,
self::AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM,
];
final public const USER_VERIFICATION_REQUIREMENT_REQUIRED = 'required';
final public const USER_VERIFICATION_REQUIREMENT_PREFERRED = 'preferred';
final public const USER_VERIFICATION_REQUIREMENT_DISCOURAGED = 'discouraged';
final public const USER_VERIFICATION_REQUIREMENTS = [
self::USER_VERIFICATION_REQUIREMENT_REQUIRED,
self::USER_VERIFICATION_REQUIREMENT_PREFERRED,
self::USER_VERIFICATION_REQUIREMENT_DISCOURAGED,
];
final public const RESIDENT_KEY_REQUIREMENT_NO_PREFERENCE = null;
final public const RESIDENT_KEY_REQUIREMENT_REQUIRED = 'required';
final public const RESIDENT_KEY_REQUIREMENT_PREFERRED = 'preferred';
final public const RESIDENT_KEY_REQUIREMENT_DISCOURAGED = 'discouraged';
final public const RESIDENT_KEY_REQUIREMENTS = [
self::RESIDENT_KEY_REQUIREMENT_NO_PREFERENCE,
self::RESIDENT_KEY_REQUIREMENT_REQUIRED,
self::RESIDENT_KEY_REQUIREMENT_PREFERRED,
self::RESIDENT_KEY_REQUIREMENT_DISCOURAGED,
];
/**
* Legacy property for backward compatibility.
*
* requireResidentKey is based on residentKey for backward compatibility
* Per WebAuthn Level 3 spec: "Relying Parties SHOULD set it to true if, and only if, residentKey is set to required."
* Only set when residentKey is "required"; leave uninitialized otherwise
*/
public readonly ?bool $requireResidentKey;
public function __construct(
public null|string $authenticatorAttachment = null,
public string $userVerification = self::USER_VERIFICATION_REQUIREMENT_PREFERRED,
public null|string $residentKey = self::RESIDENT_KEY_REQUIREMENT_NO_PREFERENCE,
) {
in_array($authenticatorAttachment, self::AUTHENTICATOR_ATTACHMENTS, true) || throw new InvalidArgumentException(
'Invalid authenticator attachment'
);
in_array($userVerification, self::USER_VERIFICATION_REQUIREMENTS, true) || throw new InvalidArgumentException(
'Invalid user verification'
);
in_array($residentKey, self::RESIDENT_KEY_REQUIREMENTS, true) || throw new InvalidArgumentException(
'Invalid resident key'
);
if ($residentKey === self::RESIDENT_KEY_REQUIREMENT_REQUIRED) {
$this->requireResidentKey = true;
} else {
$this->requireResidentKey = null;
}
}
public static function create(
?string $authenticatorAttachment = null,
string $userVerification = self::USER_VERIFICATION_REQUIREMENT_PREFERRED,
null|string $residentKey = self::RESIDENT_KEY_REQUIREMENT_NO_PREFERENCE,
): self {
return new self($authenticatorAttachment, $userVerification, $residentKey);
}
}

View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
interface CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void;
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CeremonyStepManager
{
/**
* @param CeremonyStep[] $steps
*/
public function __construct(
private array $steps
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
foreach ($this->steps as $step) {
$step->process(
$credentialRecord,
$authenticatorResponse,
$publicKeyCredentialOptions,
$userHandle,
$host
);
}
}
}

View file

@ -0,0 +1,201 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Algorithm\Signature\RSA\RS256;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\AttestationStatement\NoneAttestationStatementSupport;
use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler;
use Webauthn\Counter\CounterChecker;
use Webauthn\Counter\ThrowExceptionIfInvalid;
use Webauthn\MetadataService\CertificateChain\CertificateChainValidator;
use Webauthn\MetadataService\MetadataStatementRepository;
use Webauthn\MetadataService\StatusReportRepository;
final class CeremonyStepManagerFactory
{
private CounterChecker $counterChecker;
private Manager $algorithmManager;
private null|MetadataStatementRepository $metadataStatementRepository = null;
private null|StatusReportRepository $statusReportRepository = null;
private null|CertificateChainValidator $certificateChainValidator = null;
private null|TopOriginValidator $topOriginValidator = null;
/**
* @var string[]
*/
private null|array $securedRelyingPartyId = null;
/**
* @var string[]
*/
private null|array $allowedOrigins = null;
private bool $allowSubdomains = false;
private AttestationStatementSupportManager $attestationStatementSupportManager;
private ExtensionOutputCheckerHandler $extensionOutputCheckerHandler;
public function __construct()
{
$this->counterChecker = new ThrowExceptionIfInvalid();
$this->algorithmManager = Manager::create()->add(ES256::create(), RS256::create());
$this->attestationStatementSupportManager = new AttestationStatementSupportManager([
new NoneAttestationStatementSupport(),
]);
$this->extensionOutputCheckerHandler = new ExtensionOutputCheckerHandler();
}
public function setCounterChecker(CounterChecker $counterChecker): void
{
$this->counterChecker = $counterChecker;
}
/**
* @deprecated since 5.2.0 and will be removed in 6.0.0. Use setAllowedOrigins instead.
* @param string[] $securedRelyingPartyId
*/
public function setSecuredRelyingPartyId(array $securedRelyingPartyId): void
{
$this->securedRelyingPartyId = $securedRelyingPartyId;
}
/**
* @param string[] $allowedOrigins
*/
public function setAllowedOrigins(array $allowedOrigins, bool $allowSubdomains = false): void
{
$this->allowedOrigins = $allowedOrigins;
$this->allowSubdomains = $allowSubdomains;
}
public function setExtensionOutputCheckerHandler(ExtensionOutputCheckerHandler $extensionOutputCheckerHandler): void
{
$this->extensionOutputCheckerHandler = $extensionOutputCheckerHandler;
}
public function setAttestationStatementSupportManager(
AttestationStatementSupportManager $attestationStatementSupportManager
): void {
$this->attestationStatementSupportManager = $attestationStatementSupportManager;
}
public function setAlgorithmManager(Manager $algorithmManager): void
{
$this->algorithmManager = $algorithmManager;
}
public function enableMetadataStatementSupport(
MetadataStatementRepository $metadataStatementRepository,
StatusReportRepository $statusReportRepository,
CertificateChainValidator $certificateChainValidator
): void {
$this->metadataStatementRepository = $metadataStatementRepository;
$this->statusReportRepository = $statusReportRepository;
$this->certificateChainValidator = $certificateChainValidator;
}
public function enableCertificateChainValidator(CertificateChainValidator $certificateChainValidator): void
{
$this->certificateChainValidator = $certificateChainValidator;
}
public function enableTopOriginValidator(TopOriginValidator $topOriginValidator): void
{
$this->topOriginValidator = $topOriginValidator;
}
public function requestCeremony(): CeremonyStepManager
{
/* @see https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion */
return new CeremonyStepManager([
new CheckAllowedCredentialList(),
new CheckUserHandle(),
new CheckClientDataCollectorType(),
new CheckChallenge(),
$this->allowedOrigins === null ? new CheckOrigin(
$this->securedRelyingPartyId ?? []
) : new CheckAllowedOrigins(
$this->allowedOrigins,
$this->allowSubdomains,
$this->securedRelyingPartyId ?? []
),
new CheckTopOrigin($this->topOriginValidator),
new CheckRelyingPartyIdIdHash(),
new CheckUserWasPresent(),
new CheckUserVerification(),
new CheckBackupBitsAreConsistent(),
new CheckExtensions($this->extensionOutputCheckerHandler),
new CheckSignature($this->algorithmManager),
new CheckCounter($this->counterChecker),
]);
}
public function creationCeremony(): CeremonyStepManager
{
return $this->buildCreationCeremony(true);
}
/**
* Create a ceremony manager for Conditional Create (auto-register)
*
* Use this when creating credentials with mediation: 'conditional',
* where user presence may be false after password authentication.
*
* @see https://github.com/w3c/webauthn/wiki/Explainer:-Conditional-Create
* @see https://github.com/web-auth/webauthn-framework/issues/719
*/
public function conditionalCreateCeremony(): CeremonyStepManager
{
return $this->buildCreationCeremony(false);
}
private function buildCreationCeremony(bool $requireUserPresence): CeremonyStepManager
{
$metadataStatementChecker = new CheckMetadataStatement();
if ($this->certificateChainValidator !== null) {
$metadataStatementChecker->enableCertificateChainValidator($this->certificateChainValidator);
}
if ($this->metadataStatementRepository !== null && $this->statusReportRepository !== null && $this->certificateChainValidator !== null) {
$metadataStatementChecker->enableMetadataStatementSupport(
$this->metadataStatementRepository,
$this->statusReportRepository,
$this->certificateChainValidator,
);
}
/* @see https://www.w3.org/TR/webauthn-3/#sctn-registering-a-new-credential */
return new CeremonyStepManager([
new CheckClientDataCollectorType(),
new CheckChallenge(),
$this->allowedOrigins === null ? new CheckOrigin(
$this->securedRelyingPartyId ?? []
) : new CheckAllowedOrigins(
$this->allowedOrigins,
$this->allowSubdomains,
$this->securedRelyingPartyId ?? []
),
new CheckTopOrigin($this->topOriginValidator),
new CheckRelyingPartyIdIdHash(),
new CheckUserWasPresent($requireUserPresence),
new CheckUserVerification($requireUserPresence),
new CheckBackupBitsAreConsistent(),
new CheckAlgorithm(),
new CheckExtensions($this->extensionOutputCheckerHandler),
new CheckAttestationFormatIsKnownAndValid($this->attestationStatementSupportManager),
new CheckHasAttestedCredentialData(),
$metadataStatementChecker,
new CheckCredentialId(),
]);
}
}

View file

@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use CBOR\Decoder;
use CBOR\Normalizable;
use Cose\Algorithms;
use Cose\Key\Key;
use function count;
use function in_array;
use function is_array;
use function sprintf;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\StringStream;
use Webauthn\U2FPublicKey;
class CheckAlgorithm implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (! $publicKeyCredentialOptions instanceof PublicKeyCredentialCreationOptions) {
return;
}
$credentialPublicKey = $credentialRecord->getAttestedCredentialData()
->credentialPublicKey;
$credentialPublicKey !== null || throw AuthenticatorResponseVerificationException::create(
'No public key available.'
);
$algorithms = array_map(
fn ($pubKeyCredParam) => $pubKeyCredParam->alg,
$publicKeyCredentialOptions->pubKeyCredParams
);
if (count($algorithms) === 0) {
$algorithms = [Algorithms::COSE_ALGORITHM_ES256, Algorithms::COSE_ALGORITHM_RS256];
}
$coseKey = $this->getCoseKey($credentialPublicKey);
in_array($coseKey->alg(), $algorithms, true) || throw AuthenticatorResponseVerificationException::create(
sprintf('Invalid algorithm. Expected one of %s but got %d', implode(', ', $algorithms), $coseKey->alg())
);
}
private function getCoseKey(string $credentialPublicKey): Key
{
$isU2F = U2FPublicKey::isU2FKey($credentialPublicKey);
if ($isU2F) {
$credentialPublicKey = U2FPublicKey::convertToCoseKey($credentialPublicKey);
}
$stream = new StringStream($credentialPublicKey);
$credentialPublicKeyStream = Decoder::create()->decode($stream);
$stream->isEOF() || throw AuthenticatorResponseVerificationException::create(
'Invalid key. Presence of extra bytes.'
);
$stream->close();
$credentialPublicKeyStream instanceof Normalizable || throw AuthenticatorResponseVerificationException::create(
'Invalid attestation object. Unexpected object.'
);
$normalizedData = $credentialPublicKeyStream->normalize();
is_array($normalizedData) || throw AuthenticatorResponseVerificationException::create(
'Invalid attestation object. Unexpected object.'
);
/** @var array<int|string, mixed> $normalizedData */
return Key::create($normalizedData);
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function count;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final class CheckAllowedCredentialList implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (! $publicKeyCredentialOptions instanceof PublicKeyCredentialRequestOptions) {
return;
}
if (count($publicKeyCredentialOptions->allowCredentials) === 0) {
return;
}
foreach ($publicKeyCredentialOptions->allowCredentials as $allowedCredential) {
if (hash_equals($allowedCredential->id, $credentialRecord->publicKeyCredentialId)) {
return;
}
}
throw AuthenticatorResponseVerificationException::create('The credential ID is not allowed.');
}
}

View file

@ -0,0 +1,226 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function count;
use function in_array;
use InvalidArgumentException;
use function is_array;
use function is_string;
use function sprintf;
use function trigger_deprecation;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CheckAllowedOrigins implements CeremonyStep
{
/**
* Full origin entries (scheme://host[:port]) from allowed origins.
*
* @var string[]
*/
private array $fullOrigins;
/**
* Non-URL facet identifiers (e.g. android:apk-key-hash:...) matched verbatim against clientDataJSON.origin.
*
* @var string[]
*/
private array $rawOrigins;
/**
* @param string[] $allowedOrigins
* @param string[] $securedRelyingPartyId RP IDs that are allowed to use HTTP (e.g. localhost for development)
*/
public function __construct(
array $allowedOrigins,
private bool $allowSubdomains = false,
private array $securedRelyingPartyId = [],
) {
$fullOrigins = [];
$rawOrigins = [];
foreach ($allowedOrigins as $allowedOrigin) {
$parsed = parse_url($allowedOrigin);
$parsed !== false || throw new InvalidArgumentException(sprintf('Invalid origin: %s', $allowedOrigin));
if (isset($parsed['scheme'], $parsed['host'])) {
$fullOrigins[] = self::buildOrigin($parsed['scheme'], $parsed['host'], $parsed['port'] ?? null);
} elseif (isset($parsed['scheme'])) {
$rawOrigins[] = $allowedOrigin;
} else {
// Host-only entries are normalized to https:// since WebAuthn requires TLS
$host = $parsed['host'] ?? $allowedOrigin;
$fullOrigins[] = self::buildOrigin('https', $host, null);
}
}
$this->fullOrigins = array_unique($fullOrigins);
$this->rawOrigins = array_unique($rawOrigins);
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$C = $authenticatorResponse->clientDataJSON;
if (in_array($C->origin, $this->rawOrigins, true)) {
return;
}
$parsedOrigin = parse_url($C->origin);
is_array($parsedOrigin) || throw AuthenticatorResponseVerificationException::create(
'Invalid origin. Unable to parse the origin.'
);
$originHost = $parsedOrigin['host'] ?? $C->origin;
$hasAllowedOrigins = count($this->fullOrigins) !== 0 || count($this->rawOrigins) !== 0;
if ($hasAllowedOrigins) {
// Full origin match (scheme + host + port)
if (isset($parsedOrigin['scheme'], $parsedOrigin['host'])) {
$normalizedOrigin = self::buildOrigin(
$parsedOrigin['scheme'],
$parsedOrigin['host'],
$parsedOrigin['port'] ?? null
);
if (in_array($normalizedOrigin, $this->fullOrigins, true)) {
return;
}
}
// Subdomain matching
$isSubDomain = $this->isSubdomainOfFullOrigins($parsedOrigin);
if ($this->allowSubdomains && $isSubDomain) {
return;
}
if (! $this->allowSubdomains && $isSubDomain) {
throw AuthenticatorResponseVerificationException::create('Invalid origin. Subdomains are not allowed.');
}
throw AuthenticatorResponseVerificationException::create(
'Invalid origin. Not in the list of allowed origins.'
);
}
$rpId = $publicKeyCredentialOptions->rpId ?? $publicKeyCredentialOptions->rp->id ?? $host;
$facetId = $this->getFacetId($rpId, $publicKeyCredentialOptions->extensions, $authData->extensions);
if (! in_array($facetId, $this->securedRelyingPartyId, true)) {
$scheme = $parsedOrigin['scheme'] ?? '';
$scheme === 'https' || throw AuthenticatorResponseVerificationException::create(
'Invalid scheme. HTTPS required.'
);
}
$facetId !== '' || throw AuthenticatorResponseVerificationException::create(
'Invalid origin. Unable to determine the facet ID.'
);
if ($originHost === $facetId) {
return;
}
$isSubDomains = $this->isSubdomainOf($originHost, $facetId);
if ($this->allowSubdomains && $isSubDomains) {
return;
}
if (! $this->allowSubdomains && $isSubDomains) {
throw AuthenticatorResponseVerificationException::create('Invalid origin. Subdomains are not allowed.');
}
throw AuthenticatorResponseVerificationException::create('Invalid origin.');
}
/**
* @param array<string, mixed> $parsedOrigin Parsed origin from parse_url()
*/
private function isSubdomainOfFullOrigins(array $parsedOrigin): bool
{
if (! isset($parsedOrigin['scheme'], $parsedOrigin['host'])) {
return false;
}
/** @var string $originScheme */
$originScheme = $parsedOrigin['scheme'];
/** @var string $originHost */
$originHost = $parsedOrigin['host'];
$originPort = $parsedOrigin['port'] ?? null;
foreach ($this->fullOrigins as $fullOrigin) {
$parsedAllowed = parse_url($fullOrigin);
if (! is_array($parsedAllowed) || ! isset($parsedAllowed['scheme'], $parsedAllowed['host'])) {
continue;
}
/** @var string $allowedScheme */
$allowedScheme = $parsedAllowed['scheme'];
/** @var string $allowedHost */
$allowedHost = $parsedAllowed['host'];
if ($originScheme !== $allowedScheme) {
continue;
}
$allowedPort = $parsedAllowed['port'] ?? null;
if ($originPort !== $allowedPort) {
continue;
}
if ($this->isSubdomainOf($originHost, $allowedHost)) {
return true;
}
}
return false;
}
private static function buildOrigin(string $scheme, string $host, ?int $port): string
{
if ($port === null) {
return sprintf('%s://%s', $scheme, $host);
}
$defaultPorts = [
'https' => 443,
'http' => 80,
];
if (isset($defaultPorts[$scheme]) && $port === $defaultPorts[$scheme]) {
return sprintf('%s://%s', $scheme, $host);
}
return sprintf('%s://%s:%d', $scheme, $host, $port);
}
private function isSubdomainOf(string $subdomain, string $domain): bool
{
return str_ends_with('.' . $subdomain, '.' . $domain);
}
private function getFacetId(
string $rpId,
AuthenticationExtensions $AuthenticationExtensions,
?AuthenticationExtensions $authenticationExtensionsClientOutputs
): string {
if ($authenticationExtensionsClientOutputs === null
|| ! $AuthenticationExtensions->has('appid')
|| ! $authenticationExtensionsClientOutputs->has('appid')) {
return $rpId;
}
$appId = $AuthenticationExtensions->get('appid')
->value;
$wasUsed = $authenticationExtensionsClientOutputs->get('appid')
->value;
return (is_string($appId) && $wasUsed === true) ? $appId : $rpId;
}
}

View file

@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CheckAttestationFormatIsKnownAndValid implements CeremonyStep
{
public function __construct(
private AttestationStatementSupportManager $attestationStatementSupportManager,
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$attestationObject = $authenticatorResponse->attestationObject;
if ($attestationObject === null) {
return;
}
$fmt = $attestationObject->attStmt
->fmt;
$this->attestationStatementSupportManager->has(
$fmt
) || throw AuthenticatorResponseVerificationException::create('Unsupported attestation statement format.');
$attestationStatementSupport = $this->attestationStatementSupportManager->get($fmt);
$clientDataJSONHash = hash('sha256', $authenticatorResponse->clientDataJSON->rawData, true);
$attestationStatementSupport->isValid(
$clientDataJSONHash,
$attestationObject->attStmt,
$attestationObject->authData
) || throw AuthenticatorResponseVerificationException::create('Invalid attestation statement.');
}
}

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final class CheckBackupBitsAreConsistent implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
if ($authData->isBackupEligible()) {
return;
}
! $authData->isBackedUp() || throw AuthenticatorResponseVerificationException::create(
'Backup up bit is set but the backup is not eligible.'
);
}
}

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final class CheckChallenge implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$publicKeyCredentialOptions->challenge !== '' || throw AuthenticatorResponseVerificationException::create(
'Invalid challenge.'
);
hash_equals(
$publicKeyCredentialOptions->challenge,
$authenticatorResponse->clientDataJSON->challenge
) || throw AuthenticatorResponseVerificationException::create('Invalid challenge.');
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\ClientDataCollector\ClientDataCollectorManager;
use Webauthn\ClientDataCollector\WebauthnAuthenticationCollector;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CheckClientDataCollectorType implements CeremonyStep
{
private ClientDataCollectorManager $clientDataCollectorManager;
public function __construct(null|ClientDataCollectorManager $clientDataCollectorManager = null)
{
$this->clientDataCollectorManager = $clientDataCollectorManager ?? new ClientDataCollectorManager([
new WebauthnAuthenticationCollector(),
]);
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$this->clientDataCollectorManager->collect(
$authenticatorResponse->clientDataJSON,
$publicKeyCredentialOptions,
$authenticatorResponse,
$host
);
}
}

View file

@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\Counter\CounterChecker;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CheckCounter implements CeremonyStep
{
public function __construct(
private CounterChecker $counterChecker
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$storedCounter = $credentialRecord->counter;
$responseCounter = $authData->signCount;
if ($responseCounter !== 0 || $storedCounter !== 0) {
$this->counterChecker->check($credentialRecord, $responseCounter);
}
$credentialRecord->counter = $responseCounter;
}
}

View file

@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function strlen;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
class CheckCredentialId implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$credentialId = $credentialRecord->publicKeyCredentialId;
strlen($credentialId) <= 1023 || throw new AuthenticatorResponseVerificationException(
'Credential ID too long.'
);
}
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CheckExtensions implements CeremonyStep
{
public function __construct(
private ExtensionOutputCheckerHandler $extensionOutputCheckerHandler,
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$extensionsClientOutputs = $authData->extensions;
if ($extensionsClientOutputs !== null) {
$this->extensionOutputCheckerHandler->check(
$publicKeyCredentialOptions->extensions,
$extensionsClientOutputs
);
}
}
}

View file

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final class CheckHasAttestedCredentialData implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$authData
->hasAttestedCredentialData() || throw AuthenticatorResponseVerificationException::create(
'There is no attested credential data.'
);
$authData->attestedCredentialData !== null || throw AuthenticatorResponseVerificationException::create(
'There is no attested credential data.'
);
}
}

View file

@ -0,0 +1,297 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function count;
use function in_array;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use function sprintf;
use function trigger_deprecation;
use Webauthn\AttestationStatement\AttestationStatement;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\MetadataService\CanLogData;
use Webauthn\MetadataService\CertificateChain\CertificateChainValidator;
use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
use Webauthn\MetadataService\MetadataStatementRepository;
use Webauthn\MetadataService\Statement\MetadataStatement;
use Webauthn\MetadataService\StatusReportRepository;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\TrustPath\CertificateTrustPath;
final class CheckMetadataStatement implements CeremonyStep, CanLogData
{
private LoggerInterface $logger;
private null|MetadataStatementRepository $metadataStatementRepository = null;
private null|StatusReportRepository $statusReportRepository = null;
private null|CertificateChainValidator $certificateChainValidator = null;
public function __construct()
{
$this->logger = new NullLogger();
}
public function enableMetadataStatementSupport(
MetadataStatementRepository $metadataStatementRepository,
StatusReportRepository $statusReportRepository,
CertificateChainValidator $certificateChainValidator
): void {
$this->metadataStatementRepository = $metadataStatementRepository;
$this->statusReportRepository = $statusReportRepository;
$this->certificateChainValidator = $certificateChainValidator;
}
public function enableCertificateChainValidator(CertificateChainValidator $certificateChainValidator): void
{
$this->certificateChainValidator = $certificateChainValidator;
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (
! $publicKeyCredentialOptions instanceof PublicKeyCredentialCreationOptions
|| ! $authenticatorResponse instanceof AuthenticatorAttestationResponse
) {
return;
}
$attestationStatement = $authenticatorResponse->attestationObject->attStmt;
$attestedCredentialData = $authenticatorResponse->attestationObject->authData
->attestedCredentialData;
$attestedCredentialData !== null || throw AuthenticatorResponseVerificationException::create(
'No attested credential data found'
);
if (! $this->isAttestationVerificationRequested($publicKeyCredentialOptions)) {
$this->logger->debug('No attestation verification requested by RP.');
return;
}
if ($attestationStatement->type === AttestationStatement::TYPE_NONE) {
$this->logger->debug('None attestation format. No metadata verification required.');
return;
}
$aaguid = $attestedCredentialData->aaguid
->__toString();
if ($this->isNullAaguid($aaguid)) {
$this->logger->debug('Null AAGUID detected. Skipping metadata verification.', [
'reason' => 'Privacy placeholder or U2F device',
]);
return;
}
if ($attestationStatement->type === AttestationStatement::TYPE_SELF) {
$this->logger->debug('Self attestation detected.', [
'aaguid' => $aaguid,
]);
$this->processSelfAttestation($aaguid);
return;
}
$this->logger->debug('Processing attestation with full metadata validation.', [
'type' => $attestationStatement->type,
'aaguid' => $aaguid,
]);
$this->processWithMetadata($attestationStatement, $aaguid);
}
/**
* Check if RP requested attestation verification.
* @see https://www.w3.org/TR/webauthn-3/#dom-attestationconveyancepreference-none
*/
private function isAttestationVerificationRequested(
PublicKeyCredentialCreationOptions $publicKeyCredentialOptions
): bool {
return ! in_array(
$publicKeyCredentialOptions->attestation,
[null, PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE],
true
);
}
/**
* Check if AAGUID is all-zeros (privacy placeholder or U2F device).
*
* All-zeros AAGUID: either privacy placeholder or U2F device (which predates AAGUID).
* 1) Privacy Placeholder indicates the authenticator does not provide detailed information.
* 2) U2F device cannot provide useful AAGUID.
*
* So Metadata Statement lookup by AAGUID not possible.
*
* @see https://www.w3.org/TR/webauthn-3/#sctn-createCredential
* @see https://fidoalliance.org/specs/fido-v2.2-ps-20250714/fido-client-to-authenticator-protocol-v2.2-ps-20250714.html#u2f-authenticatorMakeCredential-interoperability
*/
private function isNullAaguid(string $aaguid): bool
{
return $aaguid === '00000000-0000-0000-0000-000000000000';
}
/**
* Process self attestation: check MDS for compromised devices.
*
* Self attestation: authenticator uses credential key pair to sign attestation.
* No attestation certificate chain to validate, but we still check MDS for compromised devices.
*
* @see https://www.w3.org/TR/webauthn-3/#self
*/
private function processSelfAttestation(string $aaguid): void
{
$metadataStatement = $this->metadataStatementRepository?->findOneByAAGUID($aaguid);
if ($metadataStatement === null) {
$this->logger->info('No metadata statement found for self attestation. Skipping MDS verification.', [
'aaguid' => $aaguid,
]);
return;
}
$this->logger->debug('Metadata statement found for self attestation. Checking status reports.', [
'aaguid' => $aaguid,
]);
$this->checkStatusReport($aaguid);
// Note: We do NOT check attestationTypes for self attestation as the authenticator
// is using its credential key (not attestation certificate), which may differ from
// the declared attestation types in metadata (which describe certificate-based attestation).
}
/**
* Process attestation with full metadata validation (Basic, AttCA, AnonCA).
*/
private function processWithMetadata(AttestationStatement $attestationStatement, string $aaguid): void
{
$this->metadataStatementRepository !== null || throw AuthenticatorResponseVerificationException::create(
'The Metadata Statement Repository is mandatory when requesting attestation objects.'
);
$metadataStatement = $this->metadataStatementRepository->findOneByAAGUID($aaguid);
$metadataStatement !== null || throw AuthenticatorResponseVerificationException::create(
sprintf('The Metadata Statement for the AAGUID "%s" is missing', $aaguid)
);
$this->logger->debug('Metadata statement found. Starting validation.', [
'aaguid' => $aaguid,
'attestation_type' => $attestationStatement->type,
]);
$this->checkStatusReport($aaguid);
$this->logger->debug('Status report verification completed.');
$this->checkCertificateChain($attestationStatement, $metadataStatement);
$this->logger->debug('Certificate chain verification completed.');
$this->checkAttestationTypeIsAllowed($attestationStatement, $metadataStatement);
$this->logger->debug('Attestation type verification completed.');
}
/**
* Check if the attestation type is allowed for this authenticator.
*/
private function checkAttestationTypeIsAllowed(
AttestationStatement $attestationStatement,
MetadataStatement $metadataStatement
): void {
if (count($metadataStatement->attestationTypes) === 0) {
$this->logger->debug('No attestation types restrictions in metadata statement.');
return;
}
$type = $this->getAttestationType($attestationStatement);
$this->logger->debug('Checking attestation type.', [
'type' => $type,
'allowed_types' => $metadataStatement->attestationTypes,
]);
in_array(
$type,
$metadataStatement->attestationTypes,
true
) || throw AuthenticatorResponseVerificationException::create(
sprintf(
'Invalid attestation statement. The attestation type "%s" is not allowed for this authenticator.',
$type
)
);
}
private function getAttestationType(AttestationStatement $attestationStatement): string
{
return match ($attestationStatement->type) {
AttestationStatement::TYPE_BASIC => MetadataStatement::ATTESTATION_BASIC_FULL,
AttestationStatement::TYPE_SELF => MetadataStatement::ATTESTATION_BASIC_SURROGATE,
AttestationStatement::TYPE_ATTCA => MetadataStatement::ATTESTATION_ATTCA,
AttestationStatement::TYPE_ANONCA => MetadataStatement::ATTESTATION_ANONCA,
default => throw AuthenticatorResponseVerificationException::create('Invalid attestation type'),
};
}
private function checkStatusReport(string $aaguid): void
{
$statusReports = $this->statusReportRepository === null ? [] : $this->statusReportRepository->findStatusReportsByAAGUID(
$aaguid
);
if (count($statusReports) === 0) {
$this->logger->debug('No status reports found for authenticator.', [
'aaguid' => $aaguid,
]);
return;
}
$lastStatusReport = end($statusReports);
$this->logger->debug('Status report found.', [
'aaguid' => $aaguid,
'status' => $lastStatusReport->status,
]);
if ($lastStatusReport->isCompromised()) {
$this->logger->warning('Authenticator is marked as compromised in MDS.', [
'aaguid' => $aaguid,
'status' => $lastStatusReport->status,
]);
throw AuthenticatorResponseVerificationException::create(
'The authenticator is compromised and cannot be used'
);
}
}
private function checkCertificateChain(
AttestationStatement $attestationStatement,
MetadataStatement $metadataStatement
): void {
$trustPath = $attestationStatement->trustPath;
$trustPath instanceof CertificateTrustPath || throw AuthenticatorResponseVerificationException::create(
'Certificate trust path is required for attestation verification'
);
$authenticatorCertificates = $trustPath->certificates;
$trustedCertificates = CertificateToolbox::fixPEMStructures(
$metadataStatement->attestationRootCertificates
);
$this->certificateChainValidator?->check($authenticatorCertificates, $trustedCertificates);
}
}

View file

@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function in_array;
use function is_array;
use function is_string;
use function strlen;
use function trigger_deprecation;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
/**
* @deprecated since 5.2.0 and will be removed in 6.0.0. Will be replaced by CheckAllowedOrigins
*/
final readonly class CheckOrigin implements CeremonyStep
{
/**
* @param string[] $securedRelyingPartyId
*/
public function __construct(
private array $securedRelyingPartyId
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$C = $authenticatorResponse->clientDataJSON;
$rpId = $publicKeyCredentialOptions->rpId ?? $publicKeyCredentialOptions->rp->id ?? $host;
$facetId = $this->getFacetId($rpId, $publicKeyCredentialOptions->extensions, $authData->extensions);
$parsedRelyingPartyId = parse_url($C->origin);
is_array($parsedRelyingPartyId) || throw AuthenticatorResponseVerificationException::create(
'Invalid origin'
);
if (! in_array($facetId, $this->securedRelyingPartyId, true)) {
$scheme = $parsedRelyingPartyId['scheme'] ?? '';
$scheme === 'https' || throw AuthenticatorResponseVerificationException::create(
'Invalid scheme. HTTPS required.'
);
}
$clientDataRpId = $parsedRelyingPartyId['host'] ?? '';
$clientDataRpId !== '' || throw AuthenticatorResponseVerificationException::create('Invalid origin rpId.');
$rpIdLength = strlen($facetId);
substr(
'.' . $clientDataRpId,
-($rpIdLength + 1)
) === '.' . $facetId || throw AuthenticatorResponseVerificationException::create('rpId mismatch.');
}
private function getFacetId(
string $rpId,
AuthenticationExtensions $AuthenticationExtensions,
null|AuthenticationExtensions $authenticationExtensionsClientOutputs
): string {
if ($authenticationExtensionsClientOutputs === null || ! $AuthenticationExtensions->has(
'appid'
) || ! $authenticationExtensionsClientOutputs->has('appid')) {
return $rpId;
}
$appId = $AuthenticationExtensions->get('appid')
->value;
$wasUsed = $authenticationExtensionsClientOutputs->get('appid')
->value;
if (! is_string($appId) || $wasUsed !== true) {
return $rpId;
}
return $appId;
}
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function is_string;
use function trigger_deprecation;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\U2FPublicKey;
final class CheckRelyingPartyIdIdHash implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$C = $authenticatorResponse->clientDataJSON;
$attestedCredentialData = $credentialRecord->getAttestedCredentialData();
$credentialPublicKey = $attestedCredentialData->credentialPublicKey;
$credentialPublicKey !== null || throw AuthenticatorResponseVerificationException::create(
'No public key available.'
);
$isU2F = U2FPublicKey::isU2FKey($credentialPublicKey);
$rpId = $publicKeyCredentialOptions->rpId ?? $publicKeyCredentialOptions->rp->id ?? $host;
$facetId = $this->getFacetId($rpId, $publicKeyCredentialOptions->extensions, $authData->extensions);
$rpIdHash = hash('sha256', $isU2F ? $C->origin : $facetId, true);
hash_equals(
$rpIdHash,
$authData
->rpIdHash
) || throw AuthenticatorResponseVerificationException::create('rpId hash mismatch.');
}
private function getFacetId(
string $rpId,
AuthenticationExtensions $AuthenticationExtensions,
null|AuthenticationExtensions $authenticationExtensionsClientOutputs
): string {
if ($authenticationExtensionsClientOutputs === null || ! $AuthenticationExtensions->has(
'appid'
) || ! $authenticationExtensionsClientOutputs->has('appid')) {
return $rpId;
}
$appId = $AuthenticationExtensions->get('appid')
->value;
$wasUsed = $authenticationExtensionsClientOutputs->get('appid')
->value;
if (! is_string($appId) || $wasUsed !== true) {
return $rpId;
}
return $appId;
}
}

View file

@ -0,0 +1,99 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use CBOR\Decoder;
use CBOR\Normalizable;
use Cose\Algorithm\Manager;
use Cose\Algorithm\Signature\ECDSA\ES256;
use Cose\Algorithm\Signature\RSA\RS256;
use Cose\Algorithm\Signature\Signature;
use Cose\Key\Key;
use function is_array;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\StringStream;
use Webauthn\U2FPublicKey;
use Webauthn\Util\CoseSignatureFixer;
final readonly class CheckSignature implements CeremonyStep
{
private Manager $algorithmManager;
public function __construct(null|Manager $algorithmManager = null)
{
$this->algorithmManager = $algorithmManager ?? Manager::create()->add(ES256::create(), RS256::create());
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (! $authenticatorResponse instanceof AuthenticatorAssertionResponse) {
return;
}
$credentialPublicKey = $credentialRecord->getAttestedCredentialData()
->credentialPublicKey;
$credentialPublicKey !== null || throw AuthenticatorResponseVerificationException::create(
'No public key available.'
);
$coseKey = $this->getCoseKey($credentialPublicKey);
$getClientDataJSONHash = hash('sha256', $authenticatorResponse->clientDataJSON->rawData, true);
$dataToVerify = $authenticatorResponse->authenticatorData->authData . $getClientDataJSONHash;
$signature = $authenticatorResponse->signature;
$algorithm = $this->algorithmManager->get($coseKey->alg());
$algorithm instanceof Signature || throw AuthenticatorResponseVerificationException::create(
'Invalid algorithm identifier. Should refer to a signature algorithm'
);
$signature = CoseSignatureFixer::fix($signature, $algorithm);
$algorithm->verify(
$dataToVerify,
$coseKey,
$signature
) || throw AuthenticatorResponseVerificationException::create('Invalid signature.');
}
private function getCoseKey(string $credentialPublicKey): Key
{
$isU2F = U2FPublicKey::isU2FKey($credentialPublicKey);
if ($isU2F) {
$credentialPublicKey = U2FPublicKey::convertToCoseKey($credentialPublicKey);
}
$stream = new StringStream($credentialPublicKey);
$credentialPublicKeyStream = Decoder::create()->decode($stream);
$stream->isEOF() || throw AuthenticatorResponseVerificationException::create(
'Invalid key. Presence of extra bytes.'
);
$stream->close();
$credentialPublicKeyStream instanceof Normalizable || throw AuthenticatorResponseVerificationException::create(
'Invalid attestation object. Unexpected object.'
);
$normalizedData = $credentialPublicKeyStream->normalize();
is_array($normalizedData) || throw AuthenticatorResponseVerificationException::create(
'Invalid attestation object. Unexpected object.'
);
/** @var array<int|string, mixed> $normalizedData */
return Key::create($normalizedData);
}
}

View file

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
class CheckTopOrigin implements CeremonyStep
{
public function __construct(
private readonly null|TopOriginValidator $topOriginValidator = null
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
$topOrigin = $authenticatorResponse->clientDataJSON->topOrigin;
if ($topOrigin === null) {
return;
}
if (! $authenticatorResponse->clientDataJSON->crossOrigin) {
throw AuthenticatorResponseVerificationException::create('The response is not cross-origin.');
}
if ($this->topOriginValidator === null) {
throw AuthenticatorResponseVerificationException::create(
'A cross-origin response was received but no TopOriginValidator is configured. '
. 'Configure one via CeremonyStepManagerFactory::enableTopOriginValidator() '
. 'to opt in to cross-origin (iframe) ceremonies.'
);
}
$this->topOriginValidator->validate($topOrigin);
}
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\InvalidUserHandleException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final class CheckUserHandle implements CeremonyStep
{
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (! $authenticatorResponse instanceof AuthenticatorAssertionResponse) {
return;
}
$credentialUserHandle = $credentialRecord->userHandle;
$responseUserHandle = $authenticatorResponse->userHandle;
if ($userHandle !== null) { // If the user was identified before the authentication ceremony was initiated,
hash_equals($credentialUserHandle, $userHandle) || throw InvalidUserHandleException::create();
if ($responseUserHandle !== null && $responseUserHandle !== '') {
hash_equals($credentialUserHandle, $responseUserHandle) || throw InvalidUserHandleException::create();
}
} else {
($responseUserHandle !== null && $responseUserHandle !== '' && hash_equals(
$credentialUserHandle,
$responseUserHandle
))
|| throw InvalidUserHandleException::create();
}
}
}

View file

@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\AuthenticatorSelectionCriteria;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
final readonly class CheckUserVerification implements CeremonyStep
{
public function __construct(
private bool $requireUserVerification = true
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (! $this->isUserVerificationRequired($publicKeyCredentialOptions)) {
return;
}
$userVerification = $publicKeyCredentialOptions instanceof PublicKeyCredentialRequestOptions ? $publicKeyCredentialOptions->userVerification : $publicKeyCredentialOptions->authenticatorSelection?->userVerification;
if ($userVerification !== AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED) {
return;
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse ? $authenticatorResponse->authenticatorData : $authenticatorResponse->attestationObject->authData;
$authData->isUserVerified() || throw AuthenticatorResponseVerificationException::create(
'User authentication required.'
);
}
private function isUserVerificationRequired(
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions
): bool {
if (! $this->requireUserVerification) {
return false;
}
if ($publicKeyCredentialOptions instanceof PublicKeyCredentialCreationOptions
&& $publicKeyCredentialOptions->mediation === PublicKeyCredentialCreationOptions::MEDIATION_CONDITIONAL) {
return false;
}
return true;
}
}

View file

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use function trigger_deprecation;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
/**
* Conditional check for user presence.
*
* The User Presence (UP) bit MUST be set unless the ceremony explicitly opts out via the
* Conditional Create flow (e.g. SimpleWebAuthn `useAutoRegister: true`). The opt-out is
* controlled at runtime by `PublicKeyCredentialCreationOptions::$mediation`, which the
* options builder sets from the configured policy. The constructor flag remains a static
* fallback used by `CeremonyStepManagerFactory::conditionalCreateCeremony()`.
*
* @see https://github.com/w3c/webauthn/wiki/Explainer:-Conditional-Create
*/
final readonly class CheckUserWasPresent implements CeremonyStep
{
public function __construct(
private bool $requireUserPresence = true
) {
}
public function process(
CredentialRecord $credentialRecord,
AuthenticatorAssertionResponse|AuthenticatorAttestationResponse $authenticatorResponse,
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions,
?string $userHandle,
string $host
): void {
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::process()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
if (! $this->isUserPresenceRequired($publicKeyCredentialOptions)) {
return;
}
$authData = $authenticatorResponse instanceof AuthenticatorAssertionResponse
? $authenticatorResponse->authenticatorData
: $authenticatorResponse->attestationObject->authData;
$authData->isUserPresent() || throw AuthenticatorResponseVerificationException::create(
'User was not present'
);
}
private function isUserPresenceRequired(
PublicKeyCredentialRequestOptions|PublicKeyCredentialCreationOptions $publicKeyCredentialOptions
): bool {
if ($publicKeyCredentialOptions instanceof PublicKeyCredentialCreationOptions
&& $publicKeyCredentialOptions->mediation === PublicKeyCredentialCreationOptions::MEDIATION_CONDITIONAL) {
return false;
}
return $this->requireUserPresence;
}
}

View file

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
final readonly class HostTopOriginValidator implements TopOriginValidator
{
public function __construct(
private string $host
) {
}
public function validate(string $topOrigin): void
{
$topOrigin === $this->host || throw AuthenticatorResponseVerificationException::create(
'The top origin does not correspond to the host.'
);
}
}

View file

@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Webauthn\CeremonyStep;
interface TopOriginValidator
{
public function validate(string $topOrigin): void;
}

View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Webauthn\ClientDataCollector;
use Webauthn\AuthenticatorResponse;
use Webauthn\CollectedClientData;
use Webauthn\PublicKeyCredentialOptions;
interface ClientDataCollector
{
/**
* @return string[]
*/
public function supportedTypes(): array;
public function verifyCollectedClientData(
CollectedClientData $collectedClientData,
PublicKeyCredentialOptions $publicKeyCredentialOptions,
AuthenticatorResponse $authenticatorResponse,
string $host
): void;
}

View file

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Webauthn\ClientDataCollector;
use function in_array;
use Webauthn\AuthenticatorResponse;
use Webauthn\CollectedClientData;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialOptions;
final readonly class ClientDataCollectorManager
{
/**
* @param ClientDataCollector[] $clientDataCollectors
*/
public function __construct(
private iterable $clientDataCollectors,
) {
}
public function collect(
CollectedClientData $collectedClientData,
PublicKeyCredentialOptions $publicKeyCredentialOptions,
AuthenticatorResponse $authenticatorResponse,
string $host
): void {
foreach ($this->clientDataCollectors as $clientDataCollector) {
if (in_array($collectedClientData->type, $clientDataCollector->supportedTypes(), true)) {
$clientDataCollector->verifyCollectedClientData(
$collectedClientData,
$publicKeyCredentialOptions,
$authenticatorResponse,
$host
);
return;
}
}
throw AuthenticatorResponseVerificationException::create('No client data collector found.');
}
}

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace Webauthn\ClientDataCollector;
use function in_array;
use function sprintf;
use Webauthn\AuthenticatorResponse;
use Webauthn\CollectedClientData;
use Webauthn\Exception\AuthenticatorResponseVerificationException;
use Webauthn\PublicKeyCredentialOptions;
final class WebauthnAuthenticationCollector implements ClientDataCollector
{
public function supportedTypes(): array
{
return ['webauthn.get', 'webauthn.create'];
}
public function verifyCollectedClientData(
CollectedClientData $collectedClientData,
PublicKeyCredentialOptions $publicKeyCredentialOptions,
AuthenticatorResponse $authenticatorResponse,
string $host
): void {
in_array(
$collectedClientData->type,
$this->supportedTypes(),
true
) || throw AuthenticatorResponseVerificationException::create(
sprintf('The client data type is not "%s" supported.', implode('", "', $this->supportedTypes()))
);
}
}

View file

@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use function array_key_exists;
use function is_array;
use function is_string;
use const JSON_THROW_ON_ERROR;
use ParagonIE\ConstantTime\Base64UrlSafe;
use function sprintf;
use Webauthn\Exception\InvalidDataException;
class CollectedClientData
{
/**
* @var mixed[]
*/
public readonly array $data;
public readonly string $type;
public readonly string $challenge;
public readonly string $origin;
public readonly null|string $topOrigin;
public readonly bool $crossOrigin;
/**
* @param mixed[] $data
*/
public function __construct(
public readonly string $rawData,
array $data
) {
$type = $data['type'] ?? '';
(is_string($type) && $type !== '') || throw InvalidDataException::create(
$data,
'Invalid parameter "type". Shall be a non-empty string.'
);
$this->type = $type;
$challenge = $data['challenge'] ?? '';
is_string($challenge) || throw InvalidDataException::create(
$data,
'Invalid parameter "challenge". Shall be a string.'
);
$challenge = Base64UrlSafe::decodeNoPadding($challenge);
$challenge !== '' || throw InvalidDataException::create(
$data,
'Invalid parameter "challenge". Shall not be empty.'
);
$this->challenge = $challenge;
$origin = $data['origin'] ?? '';
(is_string($origin) && $origin !== '') || throw InvalidDataException::create(
$data,
'Invalid parameter "origin". Shall be a non-empty string.'
);
$this->origin = $origin;
/** @var string|null $topOrigin */
$topOrigin = $data['topOrigin'] ?? null;
$this->topOrigin = $topOrigin;
/** @var bool $crossOrigin */
$crossOrigin = $data['crossOrigin'] ?? false;
$this->crossOrigin = $crossOrigin;
$this->data = $data;
}
/**
* @param mixed[] $data
*/
public static function create(string $rawData, array $data): self
{
return new self($rawData, $data);
}
/**
* @deprecated Since 5.3.0 and will be removed in 6.0.0. No replacement as not used anymore.
*/
public static function createFormJson(string $data): self
{
$rawData = Base64UrlSafe::decodeNoPadding($data);
$json = json_decode($rawData, true, flags: JSON_THROW_ON_ERROR);
is_array($json) || throw InvalidDataException::create($data, 'Invalid JSON data.');
return self::create($rawData, $json);
}
/**
* @return string[]
*/
public function all(): array
{
return array_keys($this->data);
}
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
}
public function get(string $key): mixed
{
if (! $this->has($key)) {
throw InvalidDataException::create($this->data, sprintf('The key "%s" is missing', $key));
}
return $this->data[$key];
}
}

View file

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Webauthn\Counter;
use Webauthn\CredentialRecord;
interface CounterChecker
{
public function check(CredentialRecord $credentialRecord, int $currentCounter): void;
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Webauthn\Counter;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use function trigger_deprecation;
use Webauthn\CredentialRecord;
use Webauthn\Exception\CounterException;
use Webauthn\MetadataService\CanLogData;
use Webauthn\PublicKeyCredentialSource;
final class ThrowExceptionIfInvalid implements CounterChecker, CanLogData
{
public function __construct(
private LoggerInterface $logger = new NullLogger()
) {
}
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
public function check(CredentialRecord $credentialRecord, int $currentCounter): void
{
if ($credentialRecord instanceof PublicKeyCredentialSource) {
trigger_deprecation(
'web-auth/webauthn-lib',
'5.3',
'Passing a PublicKeyCredentialSource to "%s::check()" is deprecated, pass a CredentialRecord instead.',
self::class
);
}
try {
$currentCounter > $credentialRecord->counter || throw CounterException::create(
$currentCounter,
$credentialRecord->counter,
'Invalid counter.'
);
} catch (CounterException $throwable) {
$this->logger->error('The counter is invalid', [
'current' => $currentCounter,
'new' => $credentialRecord->counter,
]);
throw $throwable;
}
}
}

View file

@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Webauthn;
/**
* @see https://w3c.github.io/webappsec-credential-management/#credential
*/
abstract class Credential
{
public function __construct(
public readonly string $type,
public readonly string $rawId,
) {
}
}

View file

@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace Webauthn;
use Symfony\Component\Uid\Uuid;
use Webauthn\TrustPath\TrustPath;
/**
* Credential Record represents a stored credential on the server side.
* It contains all the necessary data for validating authentication assertions.
*
* @see https://www.w3.org/TR/webauthn-3/#credential-record
*/
class CredentialRecord
{
/**
* @param string[] $transports
* @param array<string, mixed>|null $otherUI
*/
public function __construct(
public string $publicKeyCredentialId,
public string $type,
public array $transports,
public string $attestationType,
public TrustPath $trustPath,
public Uuid $aaguid,
public string $credentialPublicKey,
public string $userHandle,
public int $counter,
public ?array $otherUI = null,
public ?bool $backupEligible = null,
public ?bool $backupStatus = null,
public ?bool $uvInitialized = null,
) {
}
/**
* @param string[] $transports
* @param array<string, mixed>|null $otherUI
*/
public static function create(
string $publicKeyCredentialId,
string $type,
array $transports,
string $attestationType,
TrustPath $trustPath,
Uuid $aaguid,
string $credentialPublicKey,
string $userHandle,
int $counter,
?array $otherUI = null,
?bool $backupEligible = null,
?bool $backupStatus = null,
?bool $uvInitialized = null,
): self {
return new self(
$publicKeyCredentialId,
$type,
$transports,
$attestationType,
$trustPath,
$aaguid,
$credentialPublicKey,
$userHandle,
$counter,
$otherUI,
$backupEligible,
$backupStatus,
$uvInitialized
);
}
public function getPublicKeyCredentialDescriptor(): PublicKeyCredentialDescriptor
{
return PublicKeyCredentialDescriptor::create($this->type, $this->publicKeyCredentialId, $this->transports);
}
public function getAttestedCredentialData(): AttestedCredentialData
{
return AttestedCredentialData::create($this->aaguid, $this->publicKeyCredentialId, $this->credentialPublicKey);
}
}

View file

@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use CBOR\Decoder;
use CBOR\Normalizable;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\AttestationStatement\AttestationObject;
use Webauthn\AttestationStatement\AttestationStatement;
use Webauthn\AuthenticatorData;
use Webauthn\Exception\InvalidDataException;
use Webauthn\StringStream;
final class AttestationObjectDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var string $data */
$stream = new StringStream($data);
$parsed = Decoder::create()->decode($stream);
$parsed instanceof Normalizable || throw InvalidDataException::create(
$parsed,
'Invalid attestation object. Unexpected object.'
);
/** @var array<string, mixed> $attestationObject */
$attestationObject = $parsed->normalize();
$stream->isEOF() || throw InvalidDataException::create(
null,
'Invalid attestation object. Presence of extra bytes.'
);
$stream->close();
$authData = $attestationObject['authData'] ?? throw InvalidDataException::create(
$attestationObject,
'Invalid attestation object. Missing "authData" field.'
);
return AttestationObject::create(
$data,
$this->denormalizer->denormalize($attestationObject, AttestationStatement::class, $format, $context),
$this->denormalizer->denormalize($authData, AuthenticatorData::class, $format, $context),
);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AttestationObject::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AttestationObject::class => true,
];
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\AttestationStatement\AttestationStatement;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
use Webauthn\Exception\InvalidDataException;
final readonly class AttestationStatementDenormalizer implements DenormalizerInterface
{
public function __construct(
private AttestationStatementSupportManager $attestationStatementSupportManager
) {
}
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{fmt: string, attStmt: array<string, mixed>, authData: string} $data */
$attestationStatementSupport = $this->attestationStatementSupportManager->get($data['fmt']);
return $attestationStatementSupport->load($data);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AttestationStatement::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AttestationStatement::class => true,
];
}
}

View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\AttestedCredentialData;
final class AttestedCredentialDataNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof AttestedCredentialData);
$result = [
'aaguid' => $this->normalizer->normalize($data->aaguid, $format, $context),
'credentialId' => base64_encode($data->credentialId),
];
if ($data->credentialPublicKey !== null) {
$result['credentialPublicKey'] = base64_encode($data->credentialPublicKey);
}
return $result;
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AttestedCredentialData;
}
public function getSupportedTypes(?string $format): array
{
return [
AttestedCredentialData::class => true,
];
}
}

View file

@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\AuthenticationExtensions\AuthenticationExtension;
final class AuthenticationExtensionNormalizer implements NormalizerInterface
{
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AuthenticationExtension::class => true,
];
}
/**
* @return array<mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
assert($object instanceof AuthenticationExtension);
/** @var array<mixed> $value */
$value = $object->value;
return $value;
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AuthenticationExtension;
}
}

View file

@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use function is_array;
use function is_string;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\AuthenticationExtensions\AuthenticationExtension;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
final class AuthenticationExtensionsDenormalizer implements DenormalizerInterface, NormalizerInterface
{
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
if ($data instanceof AuthenticationExtensions) {
return AuthenticationExtensions::create($data->extensions);
}
assert(is_array($data), 'The data should be an array.');
foreach ($data as $key => $value) {
if (! is_string($key)) {
continue;
}
$data[$key] = AuthenticationExtension::create($key, $value);
}
/** @var array<string, AuthenticationExtension> $data */
return AuthenticationExtensions::create($data);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AuthenticationExtensions::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AuthenticationExtensions::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof AuthenticationExtensions);
$extensions = [];
foreach ($data->extensions as $extension) {
$extensions[$extension->name] = $extension->value;
}
return $extensions;
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AuthenticationExtensions;
}
}

View file

@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\AttestationStatement\AttestationObject;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorData;
use Webauthn\CollectedClientData;
use Webauthn\Exception\InvalidDataException;
use Webauthn\Util\Base64;
final class AuthenticatorAssertionResponseDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{authenticatorData: string, signature: string, clientDataJSON: string, userHandle?: ?string, attestationObject?: string} $data */
$data['authenticatorData'] = Base64::decode($data['authenticatorData']);
$data['signature'] = Base64::decode($data['signature']);
$data['clientDataJSON'] = Base64UrlSafe::decodeNoPadding($data['clientDataJSON']);
$userHandle = $data['userHandle'] ?? null;
if ($userHandle !== '' && $userHandle !== null) {
$userHandle = Base64::decode($userHandle);
}
/** @var CollectedClientData $clientDataJSON */
$clientDataJSON = $this->denormalizer->denormalize(
$data['clientDataJSON'],
CollectedClientData::class,
$format,
$context
);
/** @var AuthenticatorData $authenticatorData */
$authenticatorData = $this->denormalizer->denormalize(
$data['authenticatorData'],
AuthenticatorData::class,
$format,
$context
);
return AuthenticatorAssertionResponse::create(
$clientDataJSON,
$authenticatorData,
$data['signature'],
$userHandle ?? null,
! isset($data['attestationObject']) ? null : $this->denormalizer->denormalize(
$data['attestationObject'],
AttestationObject::class,
$format,
$context
),
);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AuthenticatorAssertionResponse::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AuthenticatorAssertionResponse::class => true,
];
}
}

View file

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\AttestationStatement\AttestationObject;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CollectedClientData;
use Webauthn\Exception\InvalidDataException;
use Webauthn\Util\Base64;
final class AuthenticatorAttestationResponseDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{clientDataJSON: string, attestationObject: string, transports?: string[]} $data */
$data['clientDataJSON'] = Base64UrlSafe::decodeNoPadding($data['clientDataJSON']);
$data['attestationObject'] = Base64::decode($data['attestationObject']);
/** @var CollectedClientData $clientDataJSON */
$clientDataJSON = $this->denormalizer->denormalize(
$data['clientDataJSON'],
CollectedClientData::class,
$format,
$context
);
/** @var AttestationObject $attestationObject */
$attestationObject = $this->denormalizer->denormalize(
$data['attestationObject'],
AttestationObject::class,
$format,
$context
);
return AuthenticatorAttestationResponse::create(
$clientDataJSON,
$attestationObject,
$data['transports'] ?? [],
);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AuthenticatorAttestationResponse::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AuthenticatorAttestationResponse::class => true,
];
}
}

View file

@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use CBOR\ByteStringObject;
use CBOR\Decoder;
use CBOR\ListObject;
use CBOR\MapObject;
use CBOR\NegativeIntegerObject;
use CBOR\TextStringObject;
use CBOR\UnsignedIntegerObject;
use function chr;
use function is_string;
use function ord;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Uid\Uuid;
use Webauthn\AttestedCredentialData;
use Webauthn\AuthenticationExtensions\AuthenticationExtensionLoader;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
use Webauthn\AuthenticatorData;
use Webauthn\Exception\InvalidDataException;
use Webauthn\StringStream;
final class AuthenticatorDataDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
private readonly Decoder $decoder;
public function __construct()
{
$this->decoder = Decoder::create();
}
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
assert(is_string($data));
$authData = $this->fixIncorrectEdDSAKey($data);
$authDataStream = new StringStream($authData);
$rp_id_hash = $authDataStream->read(32);
$flags = $authDataStream->read(1);
$signCount = $authDataStream->read(4);
/** @var array{1: int} $signCount */
$signCount = unpack('N', $signCount);
$attestedCredentialData = null;
if (0 !== (ord($flags) & AuthenticatorData::FLAG_AT)) {
$aaguid = Uuid::fromBinary($authDataStream->read(16));
$credentialLength = $authDataStream->read(2);
/** @var array{1: int} $credentialLength */
$credentialLength = unpack('n', $credentialLength);
$credentialId = $authDataStream->read($credentialLength[1]);
$credentialPublicKey = $this->decoder->decode($authDataStream);
$credentialPublicKey instanceof MapObject || throw InvalidDataException::create(
$authData,
'The data does not contain a valid credential public key.'
);
$attestedCredentialData = AttestedCredentialData::create(
$aaguid,
$credentialId,
(string) $credentialPublicKey,
);
}
$extension = null;
if (0 !== (ord($flags) & AuthenticatorData::FLAG_ED)) {
$extension = $this->decoder->decode($authDataStream);
$extension = AuthenticationExtensionLoader::load($extension);
}
$authDataStream->isEOF() || throw InvalidDataException::create(
$authData,
'Invalid authentication data. Presence of extra bytes.'
);
$authDataStream->close();
return AuthenticatorData::create(
$authData,
$rp_id_hash,
$flags,
$signCount[1],
$attestedCredentialData,
$extension === null ? null : $this->denormalizer->denormalize(
$extension,
AuthenticationExtensions::class,
$format,
$context
),
);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AuthenticatorData::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AuthenticatorData::class => true,
];
}
private function fixIncorrectEdDSAKey(string $data): string
{
/** @var string $needle */
$needle = hex2bin('a301634f4b500327206745643235353139');
/** @var string $correct */
$correct = hex2bin('a401634f4b500327206745643235353139');
$position = strpos($data, $needle);
if ($position === false) {
return $data;
}
$begin = substr($data, 0, $position);
$end = substr($data, $position);
$end = str_replace($needle, $correct, $end);
$cbor = new StringStream($end);
$badKey = $this->decoder->decode($cbor);
($badKey instanceof MapObject && $cbor->isEOF()) || throw InvalidDataException::create(
$end,
'Invalid authentication data. Presence of extra bytes.'
);
$badX = $badKey->get(-2);
$badX instanceof ListObject || throw InvalidDataException::create($end, 'Invalid authentication data.');
/** @var list<string> $normalizedBadX */
$normalizedBadX = $badX->normalize();
$keyBytes = array_reduce(
$normalizedBadX,
static fn (string $carry, string $item): string => $carry . chr((int) $item),
''
);
$correctX = ByteStringObject::create($keyBytes);
$correctKey = MapObject::create()
->add(UnsignedIntegerObject::create(1), TextStringObject::create('OKP'))
->add(UnsignedIntegerObject::create(3), NegativeIntegerObject::create(-8))
->add(NegativeIntegerObject::create(-1), TextStringObject::create('Ed25519'))
->add(NegativeIntegerObject::create(-2), $correctX);
return $begin . $correctKey;
}
}

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\AuthenticatorResponse;
use Webauthn\Exception\InvalidDataException;
final class AuthenticatorResponseDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array<string, mixed> $data */
$realType = match (true) {
array_key_exists('attestationObject', $data) => AuthenticatorAttestationResponse::class,
array_key_exists('signature', $data) => AuthenticatorAssertionResponse::class,
default => throw InvalidDataException::create($data, 'Unable to create the response object'),
};
return $this->denormalizer->denormalize($data, $realType, $format, $context);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === AuthenticatorResponse::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AuthenticatorResponse::class => true,
];
}
}

View file

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use const JSON_THROW_ON_ERROR;
use JsonException;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\CollectedClientData;
final class CollectedClientDataDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* @throws JsonException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var string $data */
/** @var array<string, mixed> $decoded */
$decoded = json_decode($data, true, flags: JSON_THROW_ON_ERROR);
return CollectedClientData::create($data, $decoded);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === CollectedClientData::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
CollectedClientData::class => true,
];
}
}

View file

@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use function assert;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Uid\Uuid;
use Webauthn\CredentialRecord;
use Webauthn\Exception\InvalidDataException;
use Webauthn\TrustPath\TrustPath;
use Webauthn\Util\Base64;
/**
* @final
*/
class CredentialRecordDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface, NormalizerInterface, NormalizerAwareInterface
{
use DenormalizerAwareTrait;
use NormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{publicKeyCredentialId: string, credentialPublicKey: string, userHandle: string, type: string, transports: string[], attestationType: string, trustPath: array<string, mixed>, aaguid: string, counter: int, otherUI?: ?array<string, mixed>, backupEligible?: ?bool, backupStatus?: ?bool, uvInitialized?: ?bool} $data */
$keys = ['publicKeyCredentialId', 'credentialPublicKey', 'userHandle'];
foreach ($keys as $key) {
array_key_exists($key, $data) || throw InvalidDataException::create($data, 'Missing ' . $key);
$data[$key] = Base64::decode($data[$key]);
}
return CredentialRecord::create(
$data['publicKeyCredentialId'],
$data['type'],
$data['transports'],
$data['attestationType'],
$this->denormalizer->denormalize($data['trustPath'], TrustPath::class, $format, $context),
Uuid::fromString($data['aaguid']),
$data['credentialPublicKey'],
$data['userHandle'],
$data['counter'],
$data['otherUI'] ?? null,
$data['backupEligible'] ?? null,
$data['backupStatus'] ?? null,
$data['uvInitialized'] ?? null,
);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === CredentialRecord::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
CredentialRecord::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof CredentialRecord);
$result = [
'publicKeyCredentialId' => Base64UrlSafe::encodeUnpadded($data->publicKeyCredentialId),
'type' => $data->type,
'transports' => $data->transports,
'attestationType' => $data->attestationType,
'trustPath' => $this->normalizer->normalize($data->trustPath, $format, $context),
'aaguid' => $this->normalizer->normalize($data->aaguid, $format, $context),
'credentialPublicKey' => Base64UrlSafe::encodeUnpadded($data->credentialPublicKey),
'userHandle' => Base64UrlSafe::encodeUnpadded($data->userHandle),
'counter' => $data->counter,
'otherUI' => $data->otherUI,
'backupEligible' => $data->backupEligible,
'backupStatus' => $data->backupStatus,
'uvInitialized' => $data->uvInitialized,
];
return array_filter($result, static fn ($value): bool => $value !== null);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof CredentialRecord;
}
}

View file

@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\MetadataService\Statement\ExtensionDescriptor;
final class ExtensionDescriptorDenormalizer implements DenormalizerInterface
{
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{id: string, tag?: ?int, data?: ?string, failIfUnknown?: bool, fail_if_unknown?: bool} $data */
if (array_key_exists('fail_if_unknown', $data)) {
$data['failIfUnknown'] = $data['fail_if_unknown'];
unset($data['fail_if_unknown']);
}
return ExtensionDescriptor::create(...$data);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === ExtensionDescriptor::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
ExtensionDescriptor::class => true,
];
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\AuthenticatorResponse;
use Webauthn\Exception\InvalidDataException;
use Webauthn\PublicKeyCredential;
use Webauthn\Util\Base64;
final class PublicKeyCredentialDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface
{
use DenormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{id?: string, rawId: string, type: string, response: array<string, mixed>} $data */
if (! array_key_exists('id', $data)) {
return $data;
}
$id = Base64UrlSafe::decodeNoPadding($data['id']);
$rawId = Base64::decode($data['rawId']);
hash_equals($id, $rawId) || throw InvalidDataException::create($data, 'Invalid ID');
$data['rawId'] = $rawId;
/** @var AuthenticatorResponse $response */
$response = $this->denormalizer->denormalize(
$data['response'],
AuthenticatorResponse::class,
$format,
$context
);
return PublicKeyCredential::create($data['type'], $data['rawId'], $response);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === PublicKeyCredential::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredential::class => true,
];
}
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use function count;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\PublicKeyCredentialDescriptor;
final class PublicKeyCredentialDescriptorNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof PublicKeyCredentialDescriptor);
$result = [
'type' => $data->type,
'id' => Base64UrlSafe::encodeUnpadded($data->id),
];
if (count($data->transports) !== 0) {
$result['transports'] = $data->transports;
}
return $result;
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof PublicKeyCredentialDescriptor;
}
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredentialDescriptor::class => true,
];
}
}

View file

@ -0,0 +1,216 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use function assert;
use function count;
use function in_array;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Exception\BadMethodCallException;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\AuthenticationExtensions\AuthenticationExtensions;
use Webauthn\AuthenticatorSelectionCriteria;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialDescriptor;
use Webauthn\PublicKeyCredentialParameters;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialRpEntity;
use Webauthn\PublicKeyCredentialUserEntity;
final class PublicKeyCredentialOptionsDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface, NormalizerInterface, NormalizerAwareInterface
{
use DenormalizerAwareTrait;
use NormalizerAwareTrait;
/**
* @throws BadMethodCallException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{challenge?: string, rp?: array<string, mixed>, user?: array<string, mixed>, pubKeyCredParams?: list<array<string, mixed>>, authenticatorSelection?: array<string, mixed>, attestation?: string, excludeCredentials?: list<array{id: string, type?: string, transports?: list<string>}>, allowCredentials?: list<array{id: string, type?: string, transports?: list<string>}>, timeout?: int<1, max>, extensions?: array<string, mixed>, hints?: list<string>, rpId?: string, userVerification?: string} $data */
if (array_key_exists('challenge', $data)) {
$data['challenge'] = Base64UrlSafe::decodeNoPadding($data['challenge']);
}
foreach (['allowCredentials', 'excludeCredentials'] as $key) {
if (array_key_exists($key, $data)) {
/** @var list<array{id: string, type?: string, transports?: list<string>}> $credentials */
$credentials = $data[$key] ?? [];
foreach ($credentials as $item => $allowCredential) {
$data[$key][$item]['id'] = Base64UrlSafe::decodeNoPadding($allowCredential['id']);
}
}
}
if ($type === PublicKeyCredentialCreationOptions::class) {
/** @var PublicKeyCredentialRpEntity $rp */
$rp = ! isset($data['rp']) ? PublicKeyCredentialRpEntity::create() : $this->denormalizer->denormalize(
$data['rp'],
PublicKeyCredentialRpEntity::class,
$format,
$context
);
/** @var PublicKeyCredentialUserEntity $user */
$user = $this->denormalizer->denormalize(
$data['user'] ?? [],
PublicKeyCredentialUserEntity::class,
$format,
$context
);
/** @var list<PublicKeyCredentialParameters> $pubKeyCredParams */
$pubKeyCredParams = ! isset($data['pubKeyCredParams']) ? [] : $this->denormalizer->denormalize(
$data['pubKeyCredParams'],
PublicKeyCredentialParameters::class . '[]',
$format,
$context
);
/** @var ?AuthenticatorSelectionCriteria $authenticatorSelection */
$authenticatorSelection = ! isset($data['authenticatorSelection']) ? null : $this->denormalizer->denormalize(
$data['authenticatorSelection'],
AuthenticatorSelectionCriteria::class,
$format,
$context
);
/** @var list<PublicKeyCredentialDescriptor> $excludeCredentials */
$excludeCredentials = ! isset($data['excludeCredentials']) ? [] : $this->denormalizer->denormalize(
$data['excludeCredentials'],
PublicKeyCredentialDescriptor::class . '[]',
$format,
$context
);
/** @var ?AuthenticationExtensions $extensions */
$extensions = ! isset($data['extensions']) ? null : $this->denormalizer->denormalize(
$data['extensions'],
AuthenticationExtensions::class,
$format,
$context
);
return PublicKeyCredentialCreationOptions::create(
$rp,
$user,
$data['challenge'] ?? '',
$pubKeyCredParams,
$authenticatorSelection,
$data['attestation'] ?? null,
$excludeCredentials,
$data['timeout'] ?? null,
$extensions,
$data['hints'] ?? [],
);
}
if ($type === PublicKeyCredentialRequestOptions::class) {
/** @var list<PublicKeyCredentialDescriptor> $allowCredentials */
$allowCredentials = ! isset($data['allowCredentials']) ? [] : $this->denormalizer->denormalize(
$data['allowCredentials'],
PublicKeyCredentialDescriptor::class . '[]',
$format,
$context
);
/** @var ?AuthenticationExtensions $extensions */
$extensions = ! isset($data['extensions']) ? null : $this->denormalizer->denormalize(
$data['extensions'],
AuthenticationExtensions::class,
$format,
$context
);
return PublicKeyCredentialRequestOptions::create(
$data['challenge'] ?? '',
$data['rpId'] ?? null,
$allowCredentials,
$data['userVerification'] ?? null,
$data['timeout'] ?? null,
$extensions,
$data['hints'] ?? [],
);
}
throw new BadMethodCallException('Unsupported type');
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return in_array(
$type,
[PublicKeyCredentialCreationOptions::class, PublicKeyCredentialRequestOptions::class],
true
);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof PublicKeyCredentialCreationOptions || $data instanceof PublicKeyCredentialRequestOptions;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredentialCreationOptions::class => true,
PublicKeyCredentialRequestOptions::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
assert(
$object instanceof PublicKeyCredentialCreationOptions || $object instanceof PublicKeyCredentialRequestOptions
);
$json = [
'challenge' => Base64UrlSafe::encodeUnpadded($object->challenge),
'timeout' => $object->timeout,
'extensions' => $object->extensions->count() === 0 ? null : $this->normalizer->normalize(
$object->extensions,
$format,
$context
),
'hints' => count($object->hints) === 0 ? null : $object->hints,
];
if ($object instanceof PublicKeyCredentialCreationOptions) {
$json = [
...$json,
'rp' => $this->normalizer->normalize($object->rp, $format, $context),
'user' => $this->normalizer->normalize($object->user, $format, $context),
'pubKeyCredParams' => $this->normalizer->normalize(
$object->pubKeyCredParams,
PublicKeyCredentialParameters::class . '[]',
$context
),
'authenticatorSelection' => $object->authenticatorSelection === null ? null : $this->normalizer->normalize(
$object->authenticatorSelection,
$format,
$context
),
'attestation' => $object->attestation,
'excludeCredentials' => $this->normalizer->normalize($object->excludeCredentials, $format, $context),
];
}
if ($object instanceof PublicKeyCredentialRequestOptions) {
$json = [
...$json,
'rpId' => $object->rpId,
'allowCredentials' => $this->normalizer->normalize($object->allowCredentials, $format, $context),
'userVerification' => $object->userVerification,
];
}
return array_filter($json, static fn ($value): bool => $value !== null);
}
}

View file

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Webauthn\Exception\InvalidDataException;
use Webauthn\PublicKeyCredentialParameters;
final class PublicKeyCredentialParametersDenormalizer implements DenormalizerInterface
{
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{type?: string, alg?: int} $data */
if (! array_key_exists('type', $data) || ! array_key_exists('alg', $data)) {
throw new InvalidDataException($data, 'Missing type or alg');
}
return PublicKeyCredentialParameters::create($data['type'], $data['alg']);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === PublicKeyCredentialParameters::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredentialParameters::class => true,
];
}
}

View file

@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\PublicKeyCredentialRpEntity;
final class PublicKeyCredentialRpEntityDenormalizer implements NormalizerInterface
{
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredentialRpEntity::class => true,
];
}
/**
* Per W3C IDL, `PublicKeyCredentialEntity.name` is required. `PublicKeyCredentialRpEntity::$name` is deprecated
* and removed in 6.0.0, so the name is defaulted to the Relying Party ID when it is left empty: the payload stays
* well-formed for the clients that refuse to start a ceremony without it, and callers no longer have to set the
* deprecated field themselves.
*
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): ?array
{
assert($object instanceof PublicKeyCredentialRpEntity);
$name = $object->name;
$data = array_filter(
[
'id' => $object->id,
'name' => $name === '' ? $object->id : $name,
'icon' => $object->icon,
],
static fn (?string $value): bool => ($value !== null && $value !== ''),
);
return $data === [] ? null : $data;
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof PublicKeyCredentialRpEntity;
}
}

View file

@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use function assert;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Uid\Uuid;
use Webauthn\Exception\InvalidDataException;
use Webauthn\PublicKeyCredentialSource;
use Webauthn\TrustPath\TrustPath;
use Webauthn\Util\Base64;
final class PublicKeyCredentialSourceDenormalizer implements DenormalizerInterface, DenormalizerAwareInterface, NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
use DenormalizerAwareTrait;
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{publicKeyCredentialId: string, credentialPublicKey: string, userHandle: string, type: string, transports: string[], attestationType: string, trustPath: array<string, mixed>, aaguid: string, counter: int, otherUI?: ?array<string, mixed>, backupEligible?: ?bool, backupStatus?: ?bool, uvInitialized?: ?bool} $data */
$keys = ['publicKeyCredentialId', 'credentialPublicKey', 'userHandle'];
foreach ($keys as $key) {
array_key_exists($key, $data) || throw InvalidDataException::create($data, 'Missing ' . $key);
$data[$key] = Base64::decode($data[$key]);
}
return PublicKeyCredentialSource::create(
$data['publicKeyCredentialId'],
$data['type'],
$data['transports'],
$data['attestationType'],
$this->denormalizer->denormalize($data['trustPath'], TrustPath::class, $format, $context),
Uuid::fromString($data['aaguid']),
$data['credentialPublicKey'],
$data['userHandle'],
$data['counter'],
$data['otherUI'] ?? null,
$data['backupEligible'] ?? null,
$data['backupStatus'] ?? null,
$data['uvInitialized'] ?? null,
);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === PublicKeyCredentialSource::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredentialSource::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof PublicKeyCredentialSource);
$result = [
'publicKeyCredentialId' => Base64UrlSafe::encodeUnpadded($data->publicKeyCredentialId),
'type' => $data->type,
'transports' => $data->transports,
'attestationType' => $data->attestationType,
'trustPath' => $this->normalizer->normalize($data->trustPath, $format, $context),
'aaguid' => $this->normalizer->normalize($data->aaguid, $format, $context),
'credentialPublicKey' => Base64UrlSafe::encodeUnpadded($data->credentialPublicKey),
'userHandle' => Base64UrlSafe::encodeUnpadded($data->userHandle),
'counter' => $data->counter,
'otherUI' => $data->otherUI,
'backupEligible' => $data->backupEligible,
'backupStatus' => $data->backupStatus,
'uvInitialized' => $data->uvInitialized,
];
return array_filter($result, static fn ($value): bool => $value !== null);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof PublicKeyCredentialSource;
}
}

View file

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use function assert;
use ParagonIE\ConstantTime\Base64UrlSafe;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\Exception\InvalidDataException;
use Webauthn\PublicKeyCredentialUserEntity;
use Webauthn\Util\Base64;
final class PublicKeyCredentialUserEntityDenormalizer implements DenormalizerInterface, NormalizerInterface
{
/**
* @throws InvalidDataException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{id?: string, name: string, displayName: string} $data */
if (! array_key_exists('id', $data)) {
return $data;
}
$data['id'] = Base64::decode($data['id']);
return PublicKeyCredentialUserEntity::create($data['name'], $data['id'], $data['displayName']);
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === PublicKeyCredentialUserEntity::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
PublicKeyCredentialUserEntity::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $object, ?string $format = null, array $context = []): array
{
assert($object instanceof PublicKeyCredentialUserEntity);
return [
'id' => Base64UrlSafe::encodeUnpadded($object->id),
'name' => $object->name,
'displayName' => $object->displayName,
];
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof PublicKeyCredentialUserEntity;
}
}

View file

@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\PublicKeyCredentialDescriptor;
use Webauthn\Signal\AllAcceptedCredentials;
class SignalAllAcceptedCredentialsDenormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
AllAcceptedCredentials::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof AllAcceptedCredentials);
/** @var array<string, mixed> $normalized_rp */
$normalized_rp = $this->normalizer->normalize($data->rp, $format, $context);
/** @var array<string, mixed> $normalized_user */
$normalized_user = $this->normalizer->normalize($data->user, $format, $context);
/** @var array<int, array{id: string, type: string}> $normalized_credentials */
$normalized_credentials = array_map(
fn (PublicKeyCredentialDescriptor $credential) => $this->normalizer->normalize(
$credential,
$format,
$context
),
$data->allAcceptedCredentials
);
return [
'rpId' => $normalized_rp['id'],
'userId' => $normalized_user['id'],
'allAcceptedCredentialIds' => array_map(
static fn (array $credential): string => $credential['id'],
$normalized_credentials
),
];
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof AllAcceptedCredentials;
}
}

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\Signal\CurrentUserDetails;
class SignalCurrentUserDetailsDenormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
CurrentUserDetails::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof CurrentUserDetails);
/** @var array<string, mixed> $normalized_rp */
$normalized_rp = $this->normalizer->normalize($data->rp, $format, $context);
/** @var array<string, mixed> $normalized_user */
$normalized_user = $this->normalizer->normalize($data->user, $format, $context);
return [
'rpId' => $normalized_rp['id'],
'userId' => $normalized_user['id'],
'name' => $normalized_user['name'],
'displayName' => $normalized_user['displayName'],
];
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof CurrentUserDetails;
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\Signal\UnknownCredential;
class SignalUnknownCredentialDenormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
UnknownCredential::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof UnknownCredential);
/** @var array<string, mixed> $normalized_rp */
$normalized_rp = $this->normalizer->normalize($data->rp, $format, $context);
/** @var array<string, mixed> $normalized_credential */
$normalized_credential = $this->normalizer->normalize($data->credential, $format, $context);
return [
'rpId' => $normalized_rp['id'],
'credentialId' => $normalized_credential['id'],
];
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof UnknownCredential;
}
}

View file

@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function array_key_exists;
use function assert;
use function is_array;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\Exception\InvalidTrustPathException;
use Webauthn\TrustPath\CertificateTrustPath;
use Webauthn\TrustPath\EmptyTrustPath;
use Webauthn\TrustPath\TrustPath;
final class TrustPathDenormalizer implements DenormalizerInterface, NormalizerInterface
{
/**
* @throws InvalidTrustPathException
*/
public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
{
/** @var array{x5c?: list<string>, type?: string} $data */
return match (true) {
array_key_exists('x5c', $data) && is_array($data['x5c']) => CertificateTrustPath::create($data['x5c']),
$data === [], isset($data['type']) && $data['type'] === EmptyTrustPath::class => EmptyTrustPath::create(),
default => throw new InvalidTrustPathException('Unsupported trust path type'),
};
}
public function supportsDenormalization(
mixed $data,
string $type,
?string $format = null,
array $context = []
): bool {
return $type === TrustPath::class;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
TrustPath::class => true,
];
}
/**
* @return array<string, mixed>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof TrustPath);
return match (true) {
$data instanceof CertificateTrustPath => [
'x5c' => $data->certificates,
],
$data instanceof EmptyTrustPath => [],
default => throw new InvalidTrustPathException('Unsupported trust path type'),
};
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof TrustPath;
}
}

View file

@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use const FILTER_VALIDATE_URL;
use function filter_var;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Throwable;
use Webauthn\Url;
/**
* Normalizes Url objects to absolute HTTPS URLs.
* Either returns the URL directly if already absolute, or generates it from a Symfony route.
*/
final readonly class UrlNormalizer implements NormalizerInterface
{
public function __construct(
private ?UrlGeneratorInterface $urlGenerator = null,
) {
}
public function normalize(mixed $data, ?string $format = null, array $context = []): string
{
assert($data instanceof Url);
// If no URL generator available, return the path as-is
if ($this->urlGenerator === null) {
return $data->path;
}
// If the path is already a valid absolute URL (https://...), return it directly
if (filter_var($data->path, FILTER_VALIDATE_URL) !== false) {
return $data->path;
}
// Otherwise, try to generate an absolute URL from a Symfony route name
try {
return $this->urlGenerator->generate($data->path, $data->params, UrlGeneratorInterface::ABSOLUTE_URL);
} catch (Throwable) {
// If the URL cannot be generated, return the path as is
return $data->path;
}
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof Url;
}
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
Url::class => true,
];
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use function assert;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Webauthn\MetadataService\Statement\VerificationMethodANDCombinations;
use Webauthn\MetadataService\Statement\VerificationMethodDescriptor;
final class VerificationMethodANDCombinationsDenormalizer implements NormalizerInterface, NormalizerAwareInterface
{
use NormalizerAwareTrait;
/**
* @return array<class-string, bool>
*/
public function getSupportedTypes(?string $format): array
{
return [
VerificationMethodANDCombinations::class => true,
];
}
/**
* @return array<array<string, mixed>>
*/
public function normalize(mixed $data, ?string $format = null, array $context = []): array
{
assert($data instanceof VerificationMethodANDCombinations);
/** @var array<array<string, mixed>> */
return array_map(
fn (VerificationMethodDescriptor $verificationMethod) => $this->normalizer->normalize(
$verificationMethod,
$format,
$context
),
$data->verificationMethods
);
}
public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
{
return $data instanceof VerificationMethodANDCombinations;
}
}

View file

@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace Webauthn\Denormalizer;
use RuntimeException;
use function sprintf;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\UidNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Webauthn\AttestationStatement\AttestationStatementSupportManager;
final readonly class WebauthnSerializerFactory
{
private const PACKAGE_SYMFONY_PROPERTY_INFO = 'symfony/property-info';
private const PACKAGE_SYMFONY_SERIALIZER = 'symfony/serializer';
private const PACKAGE_PHPDOCUMENTOR_REFLECTION_DOCBLOCK = 'phpdocumentor/reflection-docblock';
public function __construct(
private AttestationStatementSupportManager $attestationStatementSupportManager
) {
}
public function create(): SerializerInterface
{
foreach (self::getRequiredSerializerClasses() as $class => $package) {
if (! class_exists($class)) {
throw new RuntimeException(sprintf(
'The class "%s" is required. Please install the package "%s" to use this feature.',
$class,
$package
));
}
}
$denormalizers = [
new ExtensionDescriptorDenormalizer(),
new VerificationMethodANDCombinationsDenormalizer(),
new AuthenticationExtensionNormalizer(),
new PublicKeyCredentialDescriptorNormalizer(),
new AttestedCredentialDataNormalizer(),
new UrlNormalizer(),
new AttestationObjectDenormalizer(),
new AttestationStatementDenormalizer($this->attestationStatementSupportManager),
new AuthenticationExtensionsDenormalizer(),
new AuthenticatorAssertionResponseDenormalizer(),
new AuthenticatorAttestationResponseDenormalizer(),
new AuthenticatorDataDenormalizer(),
new AuthenticatorResponseDenormalizer(),
new CollectedClientDataDenormalizer(),
new PublicKeyCredentialDenormalizer(),
new PublicKeyCredentialOptionsDenormalizer(),
new CredentialRecordDenormalizer(),
new PublicKeyCredentialSourceDenormalizer(),
new PublicKeyCredentialRpEntityDenormalizer(),
new PublicKeyCredentialUserEntityDenormalizer(),
new SignalAllAcceptedCredentialsDenormalizer(),
new SignalCurrentUserDetailsDenormalizer(),
new SignalUnknownCredentialDenormalizer(),
new TrustPathDenormalizer(),
new UidNormalizer(),
new ArrayDenormalizer(),
new ObjectNormalizer(
propertyTypeExtractor: new PropertyInfoExtractor(typeExtractors: [
new PhpDocExtractor(),
new ReflectionExtractor(),
])
),
];
return new Serializer($denormalizers, [new JsonEncoder()]);
}
/**
* @return array<class-string, string>
*/
private static function getRequiredSerializerClasses(): array
{
return [
UidNormalizer::class => self::PACKAGE_SYMFONY_SERIALIZER,
ArrayDenormalizer::class => self::PACKAGE_SYMFONY_SERIALIZER,
AbstractNormalizer::class => self::PACKAGE_SYMFONY_SERIALIZER,
PropertyInfoExtractor::class => self::PACKAGE_SYMFONY_PROPERTY_INFO,
PhpDocExtractor::class => self::PACKAGE_PHPDOCUMENTOR_REFLECTION_DOCBLOCK,
ReflectionExtractor::class => self::PACKAGE_SYMFONY_PROPERTY_INFO,
JsonEncoder::class => self::PACKAGE_SYMFONY_SERIALIZER,
Serializer::class => self::PACKAGE_SYMFONY_SERIALIZER,
];
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Webauthn\Event;
use Webauthn\AttestationStatement\AttestationObject;
class AttestationObjectLoaded implements WebauthnEvent
{
public function __construct(
public readonly AttestationObject $attestationObject
) {
}
public static function create(AttestationObject $attestationObject): self
{
return new self($attestationObject);
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Webauthn\Event;
use Webauthn\AttestationStatement\AttestationStatement;
class AttestationStatementLoaded implements WebauthnEvent
{
public function __construct(
public readonly AttestationStatement $attestationStatement
) {
}
public static function create(AttestationStatement $attestationStatement): self
{
return new self($attestationStatement);
}
}

View file

@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace Webauthn\Event;
use LogicException;
use function sprintf;
use Throwable;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
class AuthenticatorAssertionResponseValidationFailedEvent
{
public function __construct(
public readonly CredentialRecord $credentialRecord,
public readonly AuthenticatorAssertionResponse $authenticatorAssertionResponse,
public readonly PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions,
public readonly string $host,
public readonly ?string $userHandle,
public readonly Throwable $throwable
) {
}
/**
* @deprecated since 5.3, use credentialRecord instead. Will be removed in 6.0.
*/
public function __get(string $name): mixed
{
if ($name === 'credentialSource') {
return $this->getPublicKeyCredentialSource();
}
throw new LogicException(sprintf('Undefined property: %s::$%s', self::class, $name));
}
/**
* @deprecated since 5.3, use credentialRecord instead. Will be removed in 6.0.
*/
public function getPublicKeyCredentialSource(): PublicKeyCredentialSource
{
if ($this->credentialRecord instanceof PublicKeyCredentialSource) {
return $this->credentialRecord;
}
return new PublicKeyCredentialSource(
$this->credentialRecord->publicKeyCredentialId,
$this->credentialRecord->type,
$this->credentialRecord->transports,
$this->credentialRecord->attestationType,
$this->credentialRecord->trustPath,
$this->credentialRecord->aaguid,
$this->credentialRecord->credentialPublicKey,
$this->credentialRecord->userHandle,
$this->credentialRecord->counter,
$this->credentialRecord->otherUI,
$this->credentialRecord->backupEligible,
$this->credentialRecord->backupStatus,
$this->credentialRecord->uvInitialized,
);
}
}

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace Webauthn\Event;
use LogicException;
use function sprintf;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialRequestOptions;
use Webauthn\PublicKeyCredentialSource;
class AuthenticatorAssertionResponseValidationSucceededEvent
{
public function __construct(
public readonly AuthenticatorAssertionResponse $authenticatorAssertionResponse,
public readonly PublicKeyCredentialRequestOptions $publicKeyCredentialRequestOptions,
public readonly string $host,
public readonly ?string $userHandle,
public readonly CredentialRecord $credentialRecord
) {
}
/**
* @deprecated since 5.3, use credentialRecord instead. Will be removed in 6.0.
*/
public function __get(string $name): mixed
{
if ($name === 'publicKeyCredentialSource') {
return $this->getPublicKeyCredentialSource();
}
throw new LogicException(sprintf('Undefined property: %s::$%s', self::class, $name));
}
/**
* @deprecated since 5.3, use credentialRecord instead. Will be removed in 6.0.
*/
public function getPublicKeyCredentialSource(): PublicKeyCredentialSource
{
if ($this->credentialRecord instanceof PublicKeyCredentialSource) {
return $this->credentialRecord;
}
return new PublicKeyCredentialSource(
$this->credentialRecord->publicKeyCredentialId,
$this->credentialRecord->type,
$this->credentialRecord->transports,
$this->credentialRecord->attestationType,
$this->credentialRecord->trustPath,
$this->credentialRecord->aaguid,
$this->credentialRecord->credentialPublicKey,
$this->credentialRecord->userHandle,
$this->credentialRecord->counter,
$this->credentialRecord->otherUI,
$this->credentialRecord->backupEligible,
$this->credentialRecord->backupStatus,
$this->credentialRecord->uvInitialized,
);
}
}

View file

@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace Webauthn\Event;
use Throwable;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\PublicKeyCredentialCreationOptions;
readonly class AuthenticatorAttestationResponseValidationFailedEvent
{
public function __construct(
public AuthenticatorAttestationResponse $authenticatorAttestationResponse,
public PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions,
public string $host,
public Throwable $throwable
) {
}
}

View file

@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Webauthn\Event;
use LogicException;
use function sprintf;
use Webauthn\AuthenticatorAttestationResponse;
use Webauthn\CredentialRecord;
use Webauthn\PublicKeyCredentialCreationOptions;
use Webauthn\PublicKeyCredentialSource;
class AuthenticatorAttestationResponseValidationSucceededEvent
{
public function __construct(
public readonly AuthenticatorAttestationResponse $authenticatorAttestationResponse,
public readonly PublicKeyCredentialCreationOptions $publicKeyCredentialCreationOptions,
public readonly string $host,
public readonly CredentialRecord $credentialRecord
) {
}
/**
* @deprecated since 5.3, use credentialRecord instead. Will be removed in 6.0.
*/
public function __get(string $name): mixed
{
if ($name === 'publicKeyCredentialSource') {
return $this->getPublicKeyCredentialSource();
}
throw new LogicException(sprintf('Undefined property: %s::$%s', self::class, $name));
}
/**
* @deprecated since 5.3, use credentialRecord instead. Will be removed in 6.0.
*/
public function getPublicKeyCredentialSource(): PublicKeyCredentialSource
{
if ($this->credentialRecord instanceof PublicKeyCredentialSource) {
return $this->credentialRecord;
}
return new PublicKeyCredentialSource(
$this->credentialRecord->publicKeyCredentialId,
$this->credentialRecord->type,
$this->credentialRecord->transports,
$this->credentialRecord->attestationType,
$this->credentialRecord->trustPath,
$this->credentialRecord->aaguid,
$this->credentialRecord->credentialPublicKey,
$this->credentialRecord->userHandle,
$this->credentialRecord->counter,
$this->credentialRecord->otherUI,
$this->credentialRecord->backupEligible,
$this->credentialRecord->backupStatus,
$this->credentialRecord->uvInitialized,
);
}
}

Some files were not shown because too many files have changed in this diff Show more