FidoU2F   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 141
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 61
c 1
b 0
f 0
dl 0
loc 141
rs 10
wmc 16

4 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 39 9
A validateAttestation() 0 33 3
A validateRootCertificate() 0 22 3
A getCertificatePem() 0 7 1
1
<?php
2
3
/**
4
 * Platine Webauth
5
 *
6
 * Platine Webauthn is the implementation of webauthn specifications
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Webauth
11
 * Copyright (c) Jakob Bennemann <[email protected]>
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
declare(strict_types=1);
33
34
namespace Platine\Webauthn\Attestation\Format;
35
36
use Platine\Webauthn\Attestation\AuthenticatorData;
37
use Platine\Webauthn\Exception\WebauthnException;
38
use Platine\Webauthn\Helper\ByteBuffer;
39
40
/**
41
 * @class FidoU2F
42
 * @package Platine\Webauthn\Attestation\Format
43
 */
44
class FidoU2F extends BaseFormat
45
{
46
    /**
47
     * The algorithm used
48
     * @var int
49
     */
50
    protected int $algo = -7;
51
52
    /**
53
     * The signature
54
     * @var string
55
     */
56
    protected string $signature;
57
58
    /**
59
     * The X5C information
60
     * @var string
61
     */
62
    protected string $x5c;
63
64
    /**
65
     * Create new instance
66
     * @param array<string|int, mixed> $attestationData
67
     * @param AuthenticatorData $authenticatorData
68
     */
69
    public function __construct(
70
        array $attestationData,
71
        AuthenticatorData $authenticatorData
72
    ) {
73
        parent::__construct($attestationData, $authenticatorData);
74
75
        // check u2f data
76
        $attestationStatement = $this->attestationData['attStmt'];
77
        if (
78
            array_key_exists('alg', $attestationStatement) &&
79
            $attestationStatement['alg'] !== $this->algo
80
        ) {
81
            throw new WebauthnException(sprintf(
82
                'U2F only accepts algorithm -7 ("ES256"), got [%d]',
83
                $attestationStatement['alg']
84
            ));
85
        }
86
87
        if (
88
            ! array_key_exists('sig', $attestationStatement) ||
89
            ! $attestationStatement['sig'] instanceof ByteBuffer
90
        ) {
91
            throw new WebauthnException('No signature found');
92
        }
93
94
        if (
95
            ! array_key_exists('x5c', $attestationStatement) ||
96
            ! is_array($attestationStatement['x5c']) ||
97
            count($attestationStatement['x5c']) !== 1
98
        ) {
99
            throw new WebauthnException('Invalid X5C certificate');
100
        }
101
102
        if (! $attestationStatement['x5c'][0] instanceof ByteBuffer) {
103
            throw new WebauthnException('Invalid X5C certificate must be Byte Buffer)');
104
        }
105
106
        $this->signature = $attestationStatement['sig']->getBinaryString();
107
        $this->x5c = $attestationStatement['x5c'][0]->getBinaryString();
108
    }
109
110
    /**
111
    * {@inheritdoc}
112
    */
113
    public function getCertificatePem(): string
114
    {
115
        $pem = '-----BEGIN CERTIFICATE-----' . "\n";
116
        $pem .= chunk_split(base64_encode($this->x5c), 64, "\n");
117
        $pem .= '-----END CERTIFICATE-----' . "\n";
118
119
        return $pem;
120
    }
121
122
    /**
123
    * {@inheritdoc}
124
    */
125
    public function validateAttestation(string $clientData): bool
126
    {
127
        $publicKey = openssl_pkey_get_public($this->getCertificatePem());
128
129
        if ($publicKey === false) {
130
            throw new WebauthnException(sprintf(
131
                'Invalid public key used, error: [%s]',
132
                openssl_error_string()
133
            ));
134
        }
135
136
        // Let verificationData be the concatenation of
137
        // (0x00 || rpIdHash || clientDataHash || credentialId || publicKeyU2F)
138
        $dataToVerify = "\x00";
139
        $dataToVerify .= $this->authenticatorData->getRelyingPartyIdHash();
140
        $dataToVerify .= $clientData;
141
        $dataToVerify .= $this->authenticatorData->getCredentialId();
142
        $dataToVerify .= $this->authenticatorData->getPublicKeyU2F();
143
144
        $coseAlgo = $this->getCoseAlgorithm($this->algo);
145
        if ($coseAlgo === null) {
146
            throw new WebauthnException(sprintf(
147
                'Invalid algorithm [%d]',
148
                $this->algo
149
            ));
150
        }
151
152
        return openssl_verify(
153
            $dataToVerify,
154
            $this->signature,
155
            $publicKey,
156
            $coseAlgo['openssl']
157
        ) === 1;
158
    }
159
160
    /**
161
    * {@inheritdoc}
162
    */
163
    public function validateRootCertificate(array $rootCertificates): bool
164
    {
165
        $chain = $this->createX5cChainFile();
166
        if ($chain !== null) {
167
            $rootCertificates[] = $chain;
168
        }
169
170
        $value = openssl_x509_checkpurpose(
171
            $this->getCertificatePem(),
172
            -1,
173
            $rootCertificates
174
        );
175
176
        if ($value === -1) {
177
            throw new WebauthnException(sprintf(
178
                'Error when validate root certificate, error message: [%s]',
179
                openssl_error_string()
180
            ));
181
        }
182
183
        // TODO phpstan complains so cast to bool
184
        return (bool) $value;
185
    }
186
}
187