Debian Codegraph @

lib/3rdParty/composer/web-auth/webauthn-lib/src/AttestationStatement/TPMAttestationStatementSupport.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\MapObject;
10 use Cose\Algorithms;
11 use Cose\Key\Ec2Key;
12 use Cose\Key\Key;
13 use Cose\Key\OkpKey;
14 use Cose\Key\RsaKey;
15 use function count;
16 use DateTimeImmutable;
17 use function openssl_verify;
18 use ParagonIE\ConstantTime\Base64UrlSafe;
19 use Psr\Clock\ClockInterface;
20 use Psr\EventDispatcher\EventDispatcherInterface;
21 use SpomkyLabs\Pki\ASN1\Type\Primitive\OctetString;
22 use SpomkyLabs\Pki\ASN1\Type\UnspecifiedType;
23 use SpomkyLabs\Pki\CryptoEncoding\PEM;
24 use SpomkyLabs\Pki\X509\Certificate\Certificate;
25 use SpomkyLabs\Pki\X509\Certificate\Extension\UnknownExtension;
26 use SpomkyLabs\Pki\X509\Certificate\TBSCertificate;
27 use function sprintf;
28 use Symfony\Component\Clock\NativeClock;
29 use function unpack;
30 use Webauthn\AuthenticatorData;
31 use Webauthn\Event\AttestationStatementLoaded;
32 use Webauthn\Event\CanDispatchEvents;
33 use Webauthn\Event\NullEventDispatcher;
34 use Webauthn\Exception\AttestationStatementLoadingException;
35 use Webauthn\Exception\AttestationStatementVerificationException;
36 use Webauthn\Exception\InvalidAttestationStatementException;
37 use Webauthn\MetadataService\CertificateChain\CertificateToolbox;
38 use Webauthn\StringStream;
39 use Webauthn\TrustPath\CertificateTrustPath;
40
41 final class TPMAttestationStatementSupport implements AttestationStatementSupport, CanDispatchEvents
42 {
43 private const OID_FIDO_GEN_CE_AAGUID = '1.3.6.1.4.1.45724.1.1.4';
44
45 private const OID_AIK_CERTIFICATE = '2.23.133.8.3';
46
47 private EventDispatcherInterface $dispatcher;
48
49 private readonly ClockInterface $clock;
50
51 public function __construct(null|ClockInterface $clock = null)
52 {
53 $this->clock = $clock ?? new NativeClock();
54 $this->dispatcher = new NullEventDispatcher();
55 }
56
57 public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): void
58 {
59 $this->dispatcher = $eventDispatcher;
60 }
61
62 public static function create(null|ClockInterface $clock = null): self
63 {
64 return new self($clock);
65 }
66
67 public function name(): string
68 {
69 return 'tpm';
70 }
71
72 /**
73 * @param array<string, mixed> $attestation
74 */
75 public function load(array $attestation): AttestationStatement
76 {
77 array_key_exists('attStmt', $attestation) || throw AttestationStatementLoadingException::create(
78 $attestation,
79 'Invalid attestation object'
80 );
81 /** @var array<string, mixed> $attStmt */
82 $attStmt = $attestation['attStmt'];
83 foreach (['ver', 'ver', 'sig', 'alg', 'certInfo', 'pubArea'] as $key) {
84 array_key_exists($key, $attStmt) || throw AttestationStatementLoadingException::create(
85 $attestation,
86 sprintf('The attestation statement value "%s" is missing.', $key)
87 );
88 }
89 $attStmt['ver'] === '2.0' || throw AttestationStatementLoadingException::create(
90 $attestation,
91 'Invalid attestation object'
92 );
93
94 /** @var string $certInfoData */
95 $certInfoData = $attStmt['certInfo'];
96 $certInfo = $this->checkCertInfo($certInfoData);
97 bin2hex($certInfo['type']) === '8017' || throw AttestationStatementLoadingException::create(
98 $attestation,
99 'Invalid attestation object'
100 );
101
102 /** @var string $pubAreaData */
103 $pubAreaData = $attStmt['pubArea'];
104 $pubArea = $this->checkPubArea($pubAreaData);
105 $pubAreaAttestedNameAlg = substr($certInfo['attestedName'], 0, 2);
106 /** @var string $pubAreaRaw */
107 $pubAreaRaw = $attStmt['pubArea'];
108 $pubAreaHash = hash($this->getTPMHash($pubAreaAttestedNameAlg), $pubAreaRaw, true);
109 $attestedName = $pubAreaAttestedNameAlg . $pubAreaHash;
110 $attestedName === $certInfo['attestedName'] || throw AttestationStatementLoadingException::create(
111 $attestation,
112 'Invalid attested name'
113 );
114
115 $attStmt['parsedCertInfo'] = $certInfo;
116 $attStmt['parsedPubArea'] = $pubArea;
117
118 /** @var array<string> $x5c */
119 $x5c = $attStmt['x5c'];
120 $certificates = CertificateToolbox::convertAllDERToPEM($x5c);
121 count($certificates) > 0 || throw AttestationStatementLoadingException::create(
122 $attestation,
123 'The attestation statement value "x5c" must be a list with at least one certificate.'
124 );
125
126 $attestationStatement = AttestationStatement::createAttCA(
127 $this->name(),
128 $attStmt,
129 CertificateTrustPath::create($certificates)
130 );
131 $this->dispatcher->dispatch(AttestationStatementLoaded::create($attestationStatement));
132
133 return $attestationStatement;
134 }
135
136 public function isValid(
137 string $clientDataJSONHash,
138 AttestationStatement $attestationStatement,
139 AuthenticatorData $authenticatorData
140 ): bool {
141 $attToBeSigned = $authenticatorData->authData . $clientDataJSONHash;
142 /** @var int|string $algRaw */
143 $algRaw = $attestationStatement->get('alg');
144 $alg = (int) $algRaw;
145 $attToBeSignedHash = hash(Algorithms::getHashAlgorithmFor($alg), $attToBeSigned, true);
146 /** @var array{extraData: string} $parsedCertInfo */
147 $parsedCertInfo = $attestationStatement->get('parsedCertInfo');
148 $parsedCertInfo['extraData'] === $attToBeSignedHash || throw InvalidAttestationStatementException::create(
149 $attestationStatement,
150 'Invalid attestation hash'
151 );
152 $credentialPublicKey = $authenticatorData->attestedCredentialData?->credentialPublicKey;
153 $credentialPublicKey !== null || throw InvalidAttestationStatementException::create(
154 $attestationStatement,
155 'Not credential public key available in the attested credential data'
156 );
157 /** @var array{unique: string} $parsedPubArea */
158 $parsedPubArea = $attestationStatement->get('parsedPubArea');
159 $this->checkUniquePublicKey($parsedPubArea['unique'], $credentialPublicKey);
160
161 return match (true) {
162 $attestationStatement->trustPath instanceof CertificateTrustPath => $this->processWithCertificate(
163 $attestationStatement,
164 $authenticatorData
165 ),
166 default => throw InvalidAttestationStatementException::create(
167 $attestationStatement,
168 'Unsupported attestation statement'
169 ),
170 };
171 }
172
173 private function checkUniquePublicKey(string $unique, string $cborPublicKey): void
174 {
175 $cborDecoder = Decoder::create();
176 $publicKey = $cborDecoder->decode(new StringStream($cborPublicKey));
177 $publicKey instanceof MapObject || throw AttestationStatementVerificationException::create(
178 'Invalid public key'
179 );
180 $key = Key::create($publicKey->normalize());
181
182 switch ($key->type()) {
183 case Key::TYPE_OKP:
184 $uniqueFromKey = (new OkpKey($key->getData()))->x();
185 break;
186 case Key::TYPE_EC2:
187 $ec2Key = new Ec2Key($key->getData());
188 $uniqueFromKey = "\x04" . $ec2Key->x() . $ec2Key->y();
189 break;
190 case Key::TYPE_RSA:
191 $uniqueFromKey = (new RsaKey($key->getData()))->n();
192 break;
193 default:
194 throw AttestationStatementVerificationException::create('Invalid or unsupported key type.');
195 }
196
197 $unique === $uniqueFromKey || throw AttestationStatementVerificationException::create(
198 'Invalid pubArea.unique value'
199 );
200 }
201
202 /**
203 * @return mixed[]
204 */
205 /**
206 * @return array{magic: string, type: string, qualifiedSigner: string, extraData: string, clockInfo: string, firmwareVersion: string, attestedName: string, attestedQualifiedName: string}
207 */
208 private function checkCertInfo(string $data): array
209 {
210 $certInfo = new StringStream($data);
211
212 $magic = $certInfo->read(4);
213 bin2hex($magic) === 'ff544347' || throw AttestationStatementVerificationException::create(
214 'Invalid attestation object'
215 );
216
217 $type = $certInfo->read(2);
218
219 /** @var array{1: int} $qualifiedSignerLengthData */
220 $qualifiedSignerLengthData = unpack('n', $certInfo->read(2));
221 $qualifiedSigner = $certInfo->read($qualifiedSignerLengthData[1]); //Ignored
222
223 /** @var array{1: int} $extraDataLengthData */
224 $extraDataLengthData = unpack('n', $certInfo->read(2));
225 $extraData = $certInfo->read($extraDataLengthData[1]);
226
227 $clockInfo = $certInfo->read(17); //Ignore
228
229 $firmwareVersion = $certInfo->read(8);
230
231 /** @var array{1: int} $attestedNameLengthData */
232 $attestedNameLengthData = unpack('n', $certInfo->read(2));
233 $attestedName = $certInfo->read($attestedNameLengthData[1]);
234
235 /** @var array{1: int} $attestedQualifiedNameLengthData */
236 $attestedQualifiedNameLengthData = unpack('n', $certInfo->read(2));
237 $attestedQualifiedName = $certInfo->read($attestedQualifiedNameLengthData[1]); //Ignore
238 $certInfo->isEOF() || throw AttestationStatementVerificationException::create(
239 'Invalid certificate information. Presence of extra bytes.'
240 );
241 $certInfo->close();
242
243 return [
244 'magic' => $magic,
245 'type' => $type,
246 'qualifiedSigner' => $qualifiedSigner,
247 'extraData' => $extraData,
248 'clockInfo' => $clockInfo,
249 'firmwareVersion' => $firmwareVersion,
250 'attestedName' => $attestedName,
251 'attestedQualifiedName' => $attestedQualifiedName,
252 ];
253 }
254
255 /**
256 * @return mixed[]
257 */
258 private function checkPubArea(string $data): array
259 {
260 $pubArea = new StringStream($data);
261
262 $type = $pubArea->read(2);
263
264 $nameAlg = $pubArea->read(2);
265
266 $objectAttributes = $pubArea->read(4);
267
268 /** @var array{1: int} $authPolicyLengthData */
269 $authPolicyLengthData = unpack('n', $pubArea->read(2));
270 $authPolicy = $pubArea->read($authPolicyLengthData[1]);
271
272 $parameters = $this->getParameters($type, $pubArea);
273
274 $unique = $this->getUnique($type, $pubArea);
275 $pubArea->isEOF() || throw AttestationStatementVerificationException::create(
276 'Invalid public area. Presence of extra bytes.'
277 );
278 $pubArea->close();
279
280 return [
281 'type' => $type,
282 'nameAlg' => $nameAlg,
283 'objectAttributes' => $objectAttributes,
284 'authPolicy' => $authPolicy,
285 'parameters' => $parameters,
286 'unique' => $unique,
287 ];
288 }
289
290 /**
291 * @return mixed[]
292 */
293 private function getParameters(string $type, StringStream $stream): array
294 {
295 return match (bin2hex($type)) {
296 '0001' => $this->getRsaParameters($stream),
297 '0023' => [
298 'symmetric' => $stream->read(2),
299 'scheme' => $stream->read(2),
300 'curveId' => $stream->read(2),
301 'kdf' => $stream->read(2),
302 ],
303 default => throw AttestationStatementVerificationException::create('Unsupported type'),
304 };
305 }
306
307 private function getUnique(string $type, StringStream $stream): string
308 {
309 switch (bin2hex($type)) {
310 case '0001':
311 /** @var array{1: int} $uniqueLengthData */
312 $uniqueLengthData = unpack('n', $stream->read(2));
313 return $stream->read($uniqueLengthData[1]);
314 case '0023':
315 /** @var array{1: int} $xLenData */
316 $xLenData = unpack('n', $stream->read(2));
317 $x = $stream->read($xLenData[1]);
318 /** @var array{1: int} $yLenData */
319 $yLenData = unpack('n', $stream->read(2));
320 $y = $stream->read($yLenData[1]);
321 return "\04" . $x . $y;
322 default:
323 throw AttestationStatementVerificationException::create('Unsupported type');
324 }
325 }
326
327 /**
328 * @return array{symmetric: string, scheme: string, keyBits: int, exponent: string}
329 */
330 private function getRsaParameters(StringStream $stream): array
331 {
332 $symmetric = $stream->read(2);
333 $scheme = $stream->read(2);
334 /** @var array{1: int} $keyBitsData */
335 $keyBitsData = unpack('n', $stream->read(2));
336
337 return [
338 'symmetric' => $symmetric,
339 'scheme' => $scheme,
340 'keyBits' => $keyBitsData[1],
341 'exponent' => $this->getExponent($stream->read(4)),
342 ];
343 }
344
345 private function getExponent(string $exponent): string
346 {
347 return bin2hex($exponent) === '00000000' ? Base64UrlSafe::decodeNoPadding('AQAB') : $exponent;
348 }
349
350 private function getTPMHash(string $nameAlg): string
351 {
352 return match (bin2hex($nameAlg)) {
353 '0004' => 'sha1',
354 '000b' => 'sha256',
355 '000c' => 'sha384',
356 '000d' => 'sha512',
357 default => throw AttestationStatementVerificationException::create('Unsupported hash algorithm'),
358 };
359 }
360
361 private function processWithCertificate(
362 AttestationStatement $attestationStatement,
363 AuthenticatorData $authenticatorData
364 ): bool {
365 $trustPath = $attestationStatement->trustPath;
366 $trustPath instanceof CertificateTrustPath || throw AttestationStatementVerificationException::create(
367 'Invalid trust path'
368 );
369
370 $certificates = $trustPath->certificates;
371
372 // Check certificate CA chain and returns the Attestation Certificate
373 $this->checkCertificate($certificates[0], $authenticatorData);
374
375 // Get the COSE algorithm identifier and the corresponding OpenSSL one
376 /** @var int|string $algRaw */
377 $algRaw = $attestationStatement->get('alg');
378 $coseAlgorithmIdentifier = (int) $algRaw;
379 $opensslAlgorithmIdentifier = Algorithms::getOpensslAlgorithmFor($coseAlgorithmIdentifier);
380
381 /** @var string $certInfo */
382 $certInfo = $attestationStatement->get('certInfo');
383 /** @var string $sig */
384 $sig = $attestationStatement->get('sig');
385 $result = openssl_verify($certInfo, $sig, $certificates[0], $opensslAlgorithmIdentifier);
386
387 return $result === 1;
388 }
389
390 // https://www.w3.org/TR/webauthn-3/#sctn-tpm-cert-requirements
391 private function checkCertificate(string $attestnCert, AuthenticatorData $authenticatorData): void
392 {
393 $certificate = Certificate::fromPEM(PEM::fromString($attestnCert));
394 $tbsCertificate = $certificate->tbsCertificate();
395
396 // Version MUST be set to 3 (X.509 version 3 is encoded as 2)
397 $tbsCertificate->version() === TBSCertificate::VERSION_3 || throw AttestationStatementVerificationException::create(
398 'Invalid certificate version'
399 );
400
401 // Subject field MUST be set to empty
402 $tbsCertificate->subject()
403 ->count() === 0 || throw AttestationStatementVerificationException::create(
404 'Invalid certificate name. The Subject should be empty'
405 );
406
407 // Check period of validity
408 $validity = $tbsCertificate->validity();
409 $startDate = DateTimeImmutable::createFromInterface($validity->notBefore()->dateTime());
410 $startDate < $this->clock->now() || throw AttestationStatementVerificationException::create(
411 'Invalid certificate start date.'
412 );
413
414 $endDate = DateTimeImmutable::createFromInterface($validity->notAfter()->dateTime());
415 $endDate > $this->clock->now() || throw AttestationStatementVerificationException::create(
416 'Invalid certificate end date.'
417 );
418
419 // Check extensions
420 $extensions = $tbsCertificate->extensions();
421
422 // Check Subject Alternative Name extension
423 $extensions->hasSubjectAlternativeName() || throw AttestationStatementVerificationException::create(
424 'The Subject Alternative Name extension must be set'
425 );
426
427 // Check Extended Key Usage extension MUST contain the OID 2.23.133.8.3
428 $extensions->hasExtendedKeyUsage() || throw AttestationStatementVerificationException::create(
429 'The Extended Key Usage extensions must contain ' . self::OID_AIK_CERTIFICATE,
430 );
431 $extendedKeyUsage = $extensions->extendedKeyUsage();
432 $extendedKeyUsage->has(self::OID_AIK_CERTIFICATE) || throw AttestationStatementVerificationException::create(
433 'The Extended Key Usage extensions must contain ' . self::OID_AIK_CERTIFICATE,
434 );
435
436 // The Basic Constraints extension MUST have the CA component set to false.
437 $extensions->basicConstraints()
438 ->isCA() === false || throw AttestationStatementVerificationException::create(
439 'The Basic Constraints extension must have the CA component set to false'
440 );
441
442 // id-fido-gen-ce-aaguid OID check
443 if ($extensions->has(self::OID_FIDO_GEN_CE_AAGUID)) {
444 /** @var UnknownExtension $aaguidExtension */
445 $aaguidExtension = $extensions->get(self::OID_FIDO_GEN_CE_AAGUID);
446 $aaguidElement = UnspecifiedType::fromDER($aaguidExtension->extensionValue())->asElement();
447 $aaguidElement instanceof OctetString || throw AttestationStatementVerificationException::create(
448 'Invalid ' . self::OID_FIDO_GEN_CE_AAGUID . ' extension format'
449 );
450 $aaguidValue = $aaguidElement->string();
451 hash_equals(
452 $authenticatorData->attestedCredentialData
453 ?->aaguid
454 ->toBinary() ?? '',
455 $aaguidValue
456 ) || throw AttestationStatementVerificationException::create(
457 'The value of the "aaguid" does not match with the certificate'
458 );
459 }
460 }
461 }