Debian Codegraph @

lib/3rdParty/composer/web-auth/webauthn-lib/src/AttestationStatement/AndroidKeyAttestationStatementSupport.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Webauthn\AttestationStatement;
6
7 use function array_key_exists;
8 use CBOR\Decoder;
9 use CBOR\Normalizable;
10 use Cose\Algorithms;
11 use Cose\Key\Ec2Key;
12 use Cose\Key\Key;
13 use Cose\Key\RsaKey;
14 use function count;
15 use function openssl_verify;
16 use Psr\EventDispatcher\EventDispatcherInterface;
17 use SpomkyLabs\Pki\ASN1\Type\Constructed\Sequence;
18 use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
19 use SpomkyLabs\Pki\ASN1\Type\Tagged\ExplicitTagging;
20 use SpomkyLabs\Pki\CryptoEncoding\PEM;
21 use SpomkyLabs\Pki\X509\Certificate\Certificate;
22 use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
23 use function sprintf;
24 use Webauthn\AuthenticatorData;
25 use Webauthn\Event\AttestationStatementLoaded;
26 use Webauthn\Event\CanDispatchEvents;
27 use Webauthn\Event\NullEventDispatcher;
28 use Webauthn\Exception\AttestationStatementLoadingException;
29 use Webauthn\Exception\AttestationStatementVerificationException;
30 use Webauthn\Exception\InvalidAttestationStatementException;
31 use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
32 use Webauthn\StringStream;
33 use Webauthn\TrustPath\CertificateTrustPath;
34
35 final class AndroidKeyAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
36 {
37 private const OID_ANDROID = '1.3.6.1.4.1.11129.2.1.17';
38
39 /**
40 * Tag 600 (allApplications)
41 * @see https://source.android.com/docs/security/features/keystore/attestation#version-1
42 */
43 private const ANDROID_TAG_ALL_APPLICATIONS = 600;
44
45 private readonly Decoder $decoder;
46
47 private EventDispatcherInterface $dispatcher;
48
49 public function __construct()
50 {
51 $this->decoder = Decoder::create();
52 $this->dispatcher = new NullEventDispatcher();
53 }
54
55 public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
56 {
57 $this->dispatcher = $eventDispatcher;
58 }
59
60 public static function create(): self
61 {
62 return new self();
63 }
64
65 public function name(): string
66 {
67 return 'android-key';
68 }
69
70 /**
71 * @param array<string, mixed> $attestation
72 */
73 public function load(array $attestation): AttestationStatement
74 {
75 array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create($attestation);
76 /** @var array<string, mixed> $attStmt */
77 $attStmt = $attestation['attStmt'];
78 foreach (['sig', 'x5c', 'alg'] as $key) {
79 array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
80 $attestation,
81 sprintf('The attestation statement value "%s" is missing.', $key)
82 );
83 }
84 /** @var array<string> $certificates */
85 $certificates = $attStmt['x5c'];
86 (is_countable($certificates) ? count(
87 $certificates
88 ) : 0) > 0 || throw AttestationStatementLoadingException::create(
89 $attestation,
90 'The attestation statement value "x5c" must be a list with at least one certificate.'
91 );
92 $certificates = CertificateToolbox::convertAllDERToPEM($certificates);
93
94 /** @var string $fmt */
95 $fmt = $attestation['fmt'];
96 $attestationStatement = AttestationStatement::createBasic(
97 $fmt,
98 $attStmt,
99 CertificateTrustPath::create($certificates)
100 );
101 $this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
102
103 return $attestationStatement;
104 }
105
106 public function isValid(
107 string $clientDataJSONHash,
108 AttestationStatement $attestationStatement,
109 AuthenticatorData $authenticatorData
110 ): bool {
111 $trustPath = $attestationStatement->trustPath;
112 $trustPath instanceof CertificateTrustPath || throw InvalidAttestationStatementException::create(
113 $attestationStatement,
114 'Invalid trust path. Shall contain certificates.'
115 );
116
117 $certificates = $trustPath->certificates;
118
119 //Decode leaf attestation certificate
120 $leaf = $certificates[0];
121 $this->checkCertificate($leaf, $clientDataJSONHash, $authenticatorData);
122
123 $signedData = $authenticatorData->authData . $clientDataJSONHash;
124 /** @var int|string $algRaw */
125 $algRaw = $attestationStatement->get('alg');
126 $alg = (int) $algRaw;
127 /** @var string $sig */
128 $sig = $attestationStatement->get('sig');
129
130 return openssl_verify($signedData, $sig, $leaf, Algorithms::getOpensslAlgorithmFor($alg)) === 1;
131 }
132
133 /**
134 * @see https://www.w3.org/TR/webauthn-3/#sctn-android-key-attestation
135 */
136 private function checkCertificate(
137 string $certificate,
138 string $clientDataHash,
139 AuthenticatorData $authenticatorData
140 ): void {
141 //Check that authData publicKey matches the public key in the attestation certificate
142 $attestedCredentialData = $authenticatorData->attestedCredentialData;
143 $attestedCredentialData !== null || throw AttestationStatementVerificationException::create(
144 'No attested credential data found'
145 );
146 $publicKeyData = $attestedCredentialData->credentialPublicKey;
147 $publicKeyData !== null || throw AttestationStatementVerificationException::create(
148 'No attested public key found'
149 );
150 $publicDataStream = new StringStream($publicKeyData);
151 $coseKey = $this->decoder->decode($publicDataStream);
152 $coseKey instanceof Normalizable || throw AttestationStatementVerificationException::create(
153 'Invalid attested public key found'
154 );
155
156 $publicDataStream->isEOF() || throw AttestationStatementVerificationException::create(
157 'Invalid public key data. Presence of extra bytes.'
158 );
159 $publicDataStream->close();
160 /** @var array<int, mixed> $coseKeyData */
161 $coseKeyData = $coseKey->normalize();
162 $publicKey = Key::createFromData($coseKeyData);
163 ($publicKey instanceof Ec2Key) || ($publicKey instanceof RsaKey) || throw AttestationStatementVerificationException::create(
164 'Unsupported key type'
165 );
166
167 /*---------------------------*/
168 /**
169 * @see https://w3c.github.io/webauthn/#sctn-key-attstn-cert-requirements
170 * @see https://source.android.com/docs/security/features/keystore/attestation#attestation-certificate
171 */
172 $cert = Certificate::fromPEM(PEM::fromString($certificate));
173 //We check the attested key corresponds to the key in the certificate
174 PEM::fromString($publicKey->asPEM())->string() === $cert->tbsCertificate()
175 ->subjectPublicKeyInfo()
176 ->toPEM()
177 ->string() || throw AttestationStatementVerificationException::create('Invalid key');
178
179 $extensions = $cert->tbsCertificate()
180 ->extensions();
181
182 //Find Android KeyStore Extension with OID self::OID_ANDROID in certificate extensions
183 $extensions->has(self::OID_ANDROID) || throw AttestationStatementVerificationException::create(
184 'The certificate extension "' . self::OID_ANDROID . '" is missing'
185 );
186 /** @var UnknownExtension $androidExtension */
187 $androidExtension = $extensions->get(self::OID_ANDROID);
188 /**
189 * Parse the Android extension value structure
190 * @see https://source.android.com/docs/security/features/keystore/attestation#attestation-extension
191 */
192 $extensionAsAsn1 = Sequence::fromDER($androidExtension->extensionValue());
193
194 //Check that attestationChallenge is set to the clientDataHash.
195 $extensionAsAsn1->has(4) || throw AttestationStatementVerificationException::create(
196 'The attestationChallenge field is missing'
197 );
198 $ext = $extensionAsAsn1->at(4)
199 ->asElement();
200 $ext instanceof OctetString || throw AttestationStatementVerificationException::create(
201 'The attestationChallenge field must be an OctetString'
202 );
203 $clientDataHash === $ext->string() || throw AttestationStatementVerificationException::create(
204 'The client data hash is not valid'
205 );
206
207 //Check that both teeEnforced and softwareEnforced structures don't contain allApplications(600) tag.
208 $extensionAsAsn1->has(6) || throw AttestationStatementVerificationException::create(
209 'The softwareEnforced field is missing'
210 );
211
212 $softwareEnforcedFlags = $extensionAsAsn1->at(6)
213 ->asElement();
214 $softwareEnforcedFlags instanceof Sequence || throw AttestationStatementVerificationException::create(
215 'The softwareEnforced field must be a Sequence'
216 );
217 $this->checkAbsenceOfAllApplicationsTag($softwareEnforcedFlags);
218
219 $extensionAsAsn1->has(7) || throw AttestationStatementVerificationException::create(
220 'The teeEnforced field is missing'
221 );
222 $teeEnforcedFlags = $extensionAsAsn1->at(7)
223 ->asElement();
224 $teeEnforcedFlags instanceof Sequence || throw AttestationStatementVerificationException::create(
225 'The teeEnforced field must be a Sequence'
226 );
227 $this->checkAbsenceOfAllApplicationsTag($teeEnforcedFlags);
228 }
229
230 private function checkAbsenceOfAllApplicationsTag(Sequence $sequence): void
231 {
232 foreach ($sequence->elements() as $tag) {
233 $element = $tag->asElement();
234 $element instanceof ExplicitTagging || throw AttestationStatementVerificationException::create(
235 'Invalid tag'
236 );
237 $element->tag() !== self::ANDROID_TAG_ALL_APPLICATIONS || throw AttestationStatementVerificationException::create(
238 'The allApplications tag (' . self::ANDROID_TAG_ALL_APPLICATIONS . ') is forbidden - key must be bound to specific application'
239 );
240 }
241 }
242 }