Completed
Push — master ( f297ff...80937c )
by Paul
12:37 queued 05:41
created

U2F::getAuthenticateData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.4286
cc 3
eloc 11
nc 3
nop 1
1
<?php
2
/**
3
 *
4
 * @copyrigt (c) 2015, Paul Sohier
5
 * @copyright (c) 2014 Yubico AB
6
 * @license BSD-2-Clause
7
 *
8
 *
9
 * Orignal Copyright:
10
 * Copyright (c) 2014 Yubico AB
11
 * All rights reserved.
12
 *
13
 * Redistribution and use in source and binary forms, with or without
14
 * modification, are permitted provided that the following conditions are
15
 * met:
16
 *
17
 *   * Redistributions of source code must retain the above copyright
18
 *     notice, this list of conditions and the following disclaimer.
19
 *
20
 *   * Redistributions in binary form must reproduce the above
21
 *     copyright notice, this list of conditions and the following
22
 *     disclaimer in the documentation and/or other materials provided
23
 *     with the distribution.
24
 *
25
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
29
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
31
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
 */
37
38
namespace paul999\u2f;
39
40
/** Constant for the version of the u2f protocol */
41
use paul999\u2f\Exceptions\U2fError;
42
43
44
class U2F implements U2F_interface
45
{
46
    /** @var string */
47
    private $appId;
48
49
    /** @var null|string */
50
    private $attestDir;
51
52
    /** @internal */
53
    private $FIXCERTS = array(
54
        '349bca1031f8c82c4ceca38b9cebf1a69df9fb3b94eed99eb3fb9aa3822d26e8',
55
        'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f',
56
        '1d8764f0f7cd1352df6150045c8f638e517270e8b5dda1c63ade9c2280240cae',
57
        'd0edc9a91a1677435a953390865d208c55b3183c6759c9b5a7ff494c322558eb',
58
        '6073c436dcd064a48127ddbf6032ac1a66fd59a0c24434f070d4e564c124c897',
59
        'ca993121846c464d666096d35f13bf44c1b05af205f9b4a1e00cf6cc10c5e511'
60
    );
61
62
    /**
63
     * @param string $appId Application id for the running application
64
     * @param string|null $attestDir Directory where trusted attestation roots may be found
65
     * @throws U2fError If OpenSSL older than 1.0.0 is used
66
     */
67
    public function __construct($appId, $attestDir = null)
68
    {
69
        if (OPENSSL_VERSION_NUMBER < 0x10000000) {
70
            throw new U2fError('OpenSSL has to be at least version 1.0.0, this is ' . OPENSSL_VERSION_TEXT, U2fError::ERR_OLD_OPENSSL);
71
        }
72
        $this->appId = $appId;
73
        $this->attestDir = $attestDir;
74
    }
75
76
    public function getRegisterData(array $registrations = array())
77
    {
78
        $challenge = $this->createChallenge();
79
        $request = new RegisterRequest($challenge, $this->appId);
80
        $signs = $this->getAuthenticateData($registrations);
81
        return array($request, $signs);
82
    }
83
84
    public function doRegister($request, $response, $includeCert = true)
85
    {
86
        if (!is_object($request)) {
87
            throw new \InvalidArgumentException('$request of doRegister() method only accepts object.');
88
        }
89
90
        if (!is_object($response)) {
91
            throw new \InvalidArgumentException('$response of doRegister() method only accepts object.');
92
        }
93
94
        if (property_exists($response, 'errorCode')) {
95
            throw new U2fError('User-agent returned error. Error code: ' . $response->errorCode, U2fError::ERR_BAD_UA_RETURNING);
96
        }
97
98
        if (!is_bool($includeCert)) {
99
            throw new \InvalidArgumentException('$include_cert of doRegister() method only accepts boolean.');
100
        }
101
102
        $rawReg = $this->base64u_decode($response->registrationData);
103
        $regData = array_values(unpack('C*', $rawReg));
104
        $clientData = $this->base64u_decode($response->clientData);
105
        $cli = json_decode($clientData);
106
107
        if ($cli->challenge !== $request->challenge) {
108
            throw new U2fError('Registration challenge does not match', U2fError::ERR_UNMATCHED_CHALLENGE);
109
        }
110
111
        $registration = new Registration();
112
        $offs = 1;
113
        $pubKey = substr($rawReg, $offs, self::PUBKEY_LEN);
114
        $offs += self::PUBKEY_LEN;
115
        // decode the pubKey to make sure it's good
116
        $tmpKey = $this->pubkey_to_pem($pubKey);
117
        if ($tmpKey === null) {
118
            throw new U2fError('Decoding of public key failed', U2fError::ERR_PUBKEY_DECODE);
119
        }
120
        $registration->publicKey = base64_encode($pubKey);
121
        $khLen = $regData[$offs++];
122
        $kh = substr($rawReg, $offs, $khLen);
123
        $offs += $khLen;
124
        $registration->keyHandle = $this->base64u_encode($kh);
125
126
        // length of certificate is stored in byte 3 and 4 (excluding the first 4 bytes)
127
        $certLen = 4;
128
        $certLen += ($regData[$offs + 2] << 8);
129
        $certLen += $regData[$offs + 3];
130
131
        $rawCert = $this->fixSignatureUnusedBits(substr($rawReg, $offs, $certLen));
132
        $offs += $certLen;
133
        $pemCert = "-----BEGIN CERTIFICATE-----\r\n";
134
        $pemCert .= chunk_split(base64_encode($rawCert), 64);
135
        $pemCert .= "-----END CERTIFICATE-----";
136
        if ($includeCert) {
137
            $registration->certificate = base64_encode($rawCert);
138
        }
139
        if ($this->attestDir) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->attestDir of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
140
            if (openssl_x509_checkpurpose($pemCert, -1, $this->get_certs()) !== true) {
141
                throw new U2fError('Attestation certificate can not be validated', U2fError::ERR_ATTESTATION_VERIFICATION);
142
            }
143
        }
144
145
        if (!openssl_pkey_get_public($pemCert)) {
146
            throw new U2fError('Decoding of public key failed', U2fError::ERR_PUBKEY_DECODE);
147
        }
148
        $signature = substr($rawReg, $offs);
149
150
        $dataToVerify = chr(0);
151
        $dataToVerify .= hash('sha256', $request->appId, true);
152
        $dataToVerify .= hash('sha256', $clientData, true);
153
        $dataToVerify .= $kh;
154
        $dataToVerify .= $pubKey;
155
156
        if (openssl_verify($dataToVerify, $signature, $pemCert, 'sha256') === 1) {
157
            return $registration;
158
        } else {
159
            throw new U2fError('Attestation signature does not match', U2fError::ERR_ATTESTATION_SIGNATURE);
160
        }
161
    }
162
163
    public function getAuthenticateData(array $registrations)
164
    {
165
        $sigs = array();
166
        foreach ($registrations as $reg) {
167
            if (!is_object($reg)) {
168
                throw new \InvalidArgumentException('$registrations of getAuthenticateData() method only accepts array of object.');
169
            }
170
171
            $sig = new SignRequest();
172
            $sig->appId = $this->appId;
173
            $sig->keyHandle = $reg->keyHandle;
174
            $sig->challenge = $this->createChallenge();
175
            $sigs[] = $sig;
176
        }
177
        return $sigs;
178
    }
179
180
    public function doAuthenticate(array $requests, array $registrations, $response)
181
    {
182
        if (!is_object($response)) {
183
            throw new \InvalidArgumentException('$response of doAuthenticate() method only accepts object.');
184
        }
185
186
        if (property_exists($response, 'errorCode')) {
187
            throw new U2fError('User-agent returned error. Error code: ' . $response->errorCode, U2fError::ERR_BAD_UA_RETURNING);
188
        }
189
190
        /** @var object|null $req */
191
        $req = null;
192
193
        /** @var object|null $reg */
194
        $reg = null;
195
196
        $clientData = $this->base64u_decode($response->clientData);
197
        $decodedClient = json_decode($clientData);
198
        foreach ($requests as $req) {
199
            if (!is_object($req)) {
200
                throw new \InvalidArgumentException('$requests of doAuthenticate() method only accepts array of object.');
201
            }
202
203
            if ($req->keyHandle === $response->keyHandle && $req->challenge === $decodedClient->challenge) {
204
                break;
205
            }
206
207
            $req = null;
208
        }
209
        if ($req === null) {
210
            throw new U2fError('No matching request found', U2fError::ERR_NO_MATCHING_REQUEST);
211
        }
212
        foreach ($registrations as $reg) {
213
            if (!is_object($reg)) {
214
                throw new \InvalidArgumentException('$registrations of doAuthenticate() method only accepts array of object.');
215
            }
216
217
            if ($reg->keyHandle === $response->keyHandle) {
218
                break;
219
            }
220
            $reg = null;
221
        }
222
        if ($reg === null) {
223
            throw new U2fError('No matching registration found', U2fError::ERR_NO_MATCHING_REGISTRATION);
224
        }
225
        $pemKey = $this->pubkey_to_pem($this->base64u_decode($reg->publicKey));
226
        if ($pemKey === null) {
227
            throw new U2fError('Decoding of public key failed', U2fError::ERR_PUBKEY_DECODE);
228
        }
229
230
        $signData = $this->base64u_decode($response->signatureData);
231
        $dataToVerify = hash('sha256', $req->appId, true);
232
        $dataToVerify .= substr($signData, 0, 5);
233
        $dataToVerify .= hash('sha256', $clientData, true);
234
        $signature = substr($signData, 5);
235
236
        if (openssl_verify($dataToVerify, $signature, $pemKey, 'sha256') === 1) {
237
            $ctr = unpack("Nctr", substr($signData, 1, 4));
238
            $counter = $ctr['ctr'];
239
            /* TODO: wrap-around should be handled somehow.. */
240
            if ($counter > $reg->counter) {
241
                $reg->counter = $counter;
242
                return $reg;
243
            } else {
244
                throw new U2fError('Counter too low.', U2fError::ERR_COUNTER_TOO_LOW);
245
            }
246
        } else {
247
            throw new U2fError('Authentication failed', U2fError::ERR_AUTHENTICATION_FAILURE);
248
        }
249
    }
250
251
    /**
252
     * @return array
253
     */
254
    private function get_certs()
255
    {
256
        $files = array();
257
        $dir = $this->attestDir;
258
        if ($dir && $handle = opendir($dir)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $dir of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
259
            while (false !== ($entry = readdir($handle))) {
260
                if (is_file("$dir/$entry")) {
261
                    $files[] = "$dir/$entry";
262
                }
263
            }
264
            closedir($handle);
265
        }
266
        return $files;
267
    }
268
269
    /**
270
     * @param string $data
271
     * @return string
272
     */
273
    private function base64u_encode($data)
274
    {
275
        return trim(strtr(base64_encode($data), '+/', '-_'), '=');
276
    }
277
278
    /**
279
     * @param string $data
280
     * @return string
281
     */
282
    private function base64u_decode($data)
283
    {
284
        return base64_decode(strtr($data, '-_', '+/'));
285
    }
286
287
    /**
288
     * @param string $key
289
     * @return null|string
290
     */
291
    private function pubkey_to_pem($key)
292
    {
293
        if (strlen($key) !== self::PUBKEY_LEN || $key[0] !== "\x04") {
294
            return null;
295
        }
296
297
        /*
298
         * Convert the public key to binary DER format first
299
         * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
300
         *
301
         *  SEQUENCE(2 elem)                        30 59
302
         *   SEQUENCE(2 elem)                       30 13
303
         *    OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
304
         *    OID1.2.840.10045.3.1.7 (secp256r1)    06 08 2a 86 48 ce 3d 03 01 07
305
         *   BIT STRING(520 bit)                    03 42 ..key..
306
         */
307
        $der = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
308
        $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
309
        $der .= "\0" . $key;
310
311
        $pem = "-----BEGIN PUBLIC KEY-----\r\n";
312
        $pem .= chunk_split(base64_encode($der), 64);
313
        $pem .= "-----END PUBLIC KEY-----";
314
315
        return $pem;
316
    }
317
318
    /**
319
     * @return string
320
     * @throws U2fError
321
     */
322
    private function createChallenge()
323
    {
324
        $challenge = openssl_random_pseudo_bytes(32, $crypto_strong);
325
        if ($crypto_strong !== true) {
326
            throw new U2fError('Unable to obtain a good source of randomness', U2fError::ERR_BAD_RANDOM);
327
        }
328
329
        $challenge = $this->base64u_encode($challenge);
330
331
        return $challenge;
332
    }
333
334
    /**
335
     * Fixes a certificate where the signature contains unused bits.
336
     *
337
     * @param string $cert
338
     * @return mixed
339
     */
340
    private function fixSignatureUnusedBits($cert)
341
    {
342
        if (in_array(hash('sha256', $cert), $this->FIXCERTS)) {
343
            $cert[strlen($cert) - 257] = "\0";
344
        }
345
        return $cert;
346
    }
347
}
348