AndroidKeyAttestationVerifier::verify()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 39
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.9157

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 6
eloc 16
c 2
b 1
f 0
nc 6
nop 3
dl 0
loc 39
ccs 12
cts 17
cp 0.7059
crap 6.9157
rs 9.1111
1
<?php
2
3
namespace MadWizard\WebAuthn\Attestation\Verifier;
4
5
use MadWizard\WebAuthn\Attestation\Android\AndroidAttestationExtension;
6
use MadWizard\WebAuthn\Attestation\Android\AndroidExtensionParser;
7
use MadWizard\WebAuthn\Attestation\Android\AuthorizationList;
8
use MadWizard\WebAuthn\Attestation\AttestationType;
9
use MadWizard\WebAuthn\Attestation\AuthenticatorData;
10
use MadWizard\WebAuthn\Attestation\Registry\AttestationFormatInterface;
11
use MadWizard\WebAuthn\Attestation\Registry\BuiltInAttestationFormat;
12
use MadWizard\WebAuthn\Attestation\Statement\AndroidKeyAttestationStatement;
13
use MadWizard\WebAuthn\Attestation\Statement\AttestationStatementInterface;
14
use MadWizard\WebAuthn\Attestation\TrustPath\CertificateTrustPath;
15
use MadWizard\WebAuthn\Crypto\CoseKeyInterface;
16
use MadWizard\WebAuthn\Exception\VerificationException;
17
use MadWizard\WebAuthn\Exception\WebAuthnException;
18
use MadWizard\WebAuthn\Pki\CertificateDetails;
19
use MadWizard\WebAuthn\Pki\CertificateDetailsInterface;
20
21
final class AndroidKeyAttestationVerifier implements AttestationVerifierInterface
22
{
23 1
    public function verify(AttestationStatementInterface $attStmt, AuthenticatorData $authenticatorData, string $clientDataHash): VerificationResult
24
    {
25 1
        if (!($attStmt instanceof AndroidKeyAttestationStatement)) {
26
            throw new VerificationException('Expecting AndroidKeyAttestationStatement');
27
        }
28
29
        // Verify that attStmt is valid CBOR conforming to the syntax defined above and perform
30
        // CBOR decoding on it to extract the contained fields.
31
        // -> this is done in AndroidKeyAttestationStatement
32
33 1
        $x5c = $attStmt->getCertificates();
34 1
        if (count($x5c) === 0) {
35
            throw new VerificationException('No certificates in chain');
36
        }
37 1
        $cert = CertificateDetails::fromCertificate($x5c[0]);
38
39
        // Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash using
40
        // the public key in the first certificate in x5c with the algorithm specified in alg.
41 1
        if (!$this->verifySignature($cert, $attStmt, $authenticatorData, $clientDataHash)) {
42
            throw new VerificationException('Signature invalid');
43
        }
44
45
        // Verify that the public key in the first certificate in x5c matches the credentialPublicKey in the
46
        // attestedCredentialData in authenticatorData.
47
48 1
        if (!$this->certificateKeyMatches($cert, $authenticatorData->getKey())) {
49
            throw new VerificationException('Public key of first certificate in chain does not match the public key from the authenticator data.');
50
        }
51
52 1
        $extension = $cert->getExtensionData(AndroidAttestationExtension::OID);
53 1
        if ($extension === null) {
54
            throw new VerificationException('Missing Android attestation extension.');
55
        }
56 1
        $ext = AndroidExtensionParser::parseAttestationExtension($extension->getValue());
57
58 1
        $this->checkAndroidKeyExtension($ext, $clientDataHash);
59
60
        //  If successful, return implementation-specific values representing attestation type Basic and attestation trust path x5c.
61 1
        return new VerificationResult(AttestationType::BASIC, new CertificateTrustPath(...$x5c));
62
    }
63
64 1
    private function checkAndroidKeyExtension(AndroidAttestationExtension $ext, string $clientDataHash): void
65
    {
66
        // Verify that the attestationChallenge field in the attestation certificate extension data is identical to clientDataHash.
67
68 1
        if (!\hash_equals($ext->getChallenge()->getBinaryString(), $clientDataHash)) {
69
            throw new VerificationException('AttestationChallenge in Android attestation extension does not match clientDataHash.');
70
        }
71
72
        //  Verify the following using the appropriate authorization list from the attestation certificate extension data:
73
        //   The AuthorizationList.allApplications field is not present on either authorization list (softwareEnforced nor teeEnforced), since PublicKeyCredential MUST be scoped to the RP ID.
74 1
        $seAuth = $ext->getSoftwareEnforcedAuthList();
75 1
        $teeAuth = $ext->getTeeEnforcedAuthList();
76 1
        if ($seAuth->hasAllApplications() || $teeAuth->hasAllApplications()) {
77
            throw new VerificationException('Invalid Android attestation extension: allApplication fields cannot be present in softwareEnforced or teeEnforced authorization list.');
78
        }
79
80
        //  For the following, use only the teeEnforced authorization list if the RP wants to accept only keys from a trusted execution environment, otherwise use the union of teeEnforced and softwareEnforced.
81
82
        //  - The value in the AuthorizationList.origin field is equal to KM_ORIGIN_GENERATED.
83
        //  - The value in the AuthorizationList.purpose field is equal to KM_PURPOSE_SIGN.
84
85 1
        $seValid = ($seAuth->hasPurpose(AuthorizationList::KM_PURPOSE_SIGN) && $seAuth->getOrigin() === AuthorizationList::KM_ORIGIN_GENERATED);
86 1
        $teeValid = ($teeAuth->hasPurpose(AuthorizationList::KM_PURPOSE_SIGN) && $teeAuth->getOrigin() === AuthorizationList::KM_ORIGIN_GENERATED);
87
88
        // TODO:LOW how to provide this as an option?
89 1
        if (!($seValid || $teeValid)) {
90
            throw new VerificationException('Invalid Android attestation extension: no acceptable authorization lists.');
91
        }
92 1
    }
93
94 1
    private function verifySignature(CertificateDetailsInterface $cert, AndroidKeyAttestationStatement $attStmt, AuthenticatorData $authenticatorData, string $clientDataHash): bool
95
    {
96
        try {
97 1
            $verificationData = $authenticatorData->getRaw()->getBinaryString() . $clientDataHash;
98 1
            return $cert->verifySignature($verificationData, $attStmt->getSignature()->getBinaryString(), $attStmt->getAlgorithm());
99
        } catch (WebAuthnException $e) {
100
            throw new VerificationException('Failed to verify signature', 0, $e);
101
        }
102
    }
103
104 1
    private function certificateKeyMatches(CertificateDetailsInterface $cert, CoseKeyInterface $key): bool
105
    {
106
        // Compare DER encodings of both keys to ensure they are equal.
107
        // By definition there is always only one exact DER encoding for a public key.
108 1
        $certKeyDer = $cert->getPublicKeyDer();
109 1
        $keyDer = $key->asDer();
110 1
        return hash_equals($certKeyDer, $keyDer);
111
    }
112
113 19
    public function getSupportedFormat(): AttestationFormatInterface
114
    {
115 19
        return new BuiltInAttestationFormat(
116 19
            AndroidKeyAttestationStatement::FORMAT_ID,
117 19
            AndroidKeyAttestationStatement::class,
118
            $this
119
        );
120
    }
121
}
122