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'
);
}
}
}