Passed
Branch fix/style (e01aa8)
by Thomas
01:47
created

U2F::getCerts()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 10
nc 3
nop 0
dl 0
loc 15
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace u2flib_server;
4
5
/* Copyright (c) 2014 Yubico AB
6
 * All rights reserved.
7
 *
8
 * Redistribution and use in source and binary forms, with or without
9
 * modification, are permitted provided that the following conditions are
10
 * met:
11
 *
12
 *   * Redistributions of source code must retain the above copyright
13
 *     notice, this list of conditions and the following disclaimer.
14
 *
15
 *   * Redistributions in binary form must reproduce the above
16
 *     copyright notice, this list of conditions and the following
17
 *     disclaimer in the documentation and/or other materials provided
18
 *     with the distribution.
19
 *
20
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
 */
32
33
use Exception;
34
use InvalidArgumentException;
35
36
/**
37
 * Constant for the version of the u2f protocol
38
 */
39
const U2F_VERSION = 'U2F_V2';
40
41
/**
42
 * Constant for the type value in registration clientData
43
 */
44
const REQUEST_TYPE_REGISTER = 'navigator.id.finishEnrollment';
45
46
/**
47
 * Constant for the type value in authentication clientData
48
 */
49
const REQUEST_TYPE_AUTHENTICATE = 'navigator.id.getAssertion';
50
51
/**
52
 * Error for the authentication message not matching any outstanding
53
 * authentication request
54
 */
55
const ERR_NO_MATCHING_REQUEST = 1;
56
57
/**
58
 * Error for the authentication message not matching any registration
59
 */
60
const ERR_NO_MATCHING_REGISTRATION = 2;
61
62
/**
63
 * Error for the signature on the authentication message not verifying with
64
 * the correct key
65
 */
66
const ERR_AUTHENTICATION_FAILURE = 3;
67
68
/**
69
 * Error for the challenge in the registration message not matching the
70
 * registration challenge
71
 */
72
const ERR_UNMATCHED_CHALLENGE = 4;
73
74
/**
75
 * Error for the attestation signature on the registration message not
76
 * verifying
77
 */
78
const ERR_ATTESTATION_SIGNATURE = 5;
79
80
/**
81
 * Error for the attestation verification not verifying
82
 */
83
const ERR_ATTESTATION_VERIFICATION = 6;
84
85
/**
86
 * Error for not getting good random from the system
87
 */
88
const ERR_BAD_RANDOM = 7;
89
90
/**
91
 * Error when the counter is lower than expected
92
 */
93
const ERR_COUNTER_TOO_LOW = 8;
94
95
/**
96
 * Error decoding public key
97
 */
98
const ERR_PUBKEY_DECODE = 9;
99
100
/**
101
 * Error user-agent returned error
102
 */
103
const ERR_BAD_UA_RETURNING = 10;
104
105
/**
106
 * Error old OpenSSL version
107
 */
108
const ERR_OLD_OPENSSL = 11;
109
110
/**
111
 * Error for the origin not matching the appId
112
 */
113
const ERR_NO_MATCHING_ORIGIN = 12;
114
115
/**
116
 * Error for the type in clientData being invalid
117
 */
118
const ERR_BAD_TYPE = 13;
119
120
/**
121
 * Error for bad user presence byte value
122
 */
123
const ERR_BAD_USER_PRESENCE = 14;
124
125
/**
126
 * @internal
127
 */
128
const PUBKEY_LEN = 65;
129
130
class U2F
131
{
132
    /**
133
     * @var string
134
     */
135
    private $appId;
136
137
    /**
138
     * @var string|null
139
     */
140
    private $attestDir;
141
142
    /**
143
     * @var array
144
     */
145
    private $facetIds;
146
147
    /**
148
     * @internal
149
     */
150
    private const FIXCERTS = [
151
        '349bca1031f8c82c4ceca38b9cebf1a69df9fb3b94eed99eb3fb9aa3822d26e8',
152
        'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f',
153
        '1d8764f0f7cd1352df6150045c8f638e517270e8b5dda1c63ade9c2280240cae',
154
        'd0edc9a91a1677435a953390865d208c55b3183c6759c9b5a7ff494c322558eb',
155
        '6073c436dcd064a48127ddbf6032ac1a66fd59a0c24434f070d4e564c124c897',
156
        'ca993121846c464d666096d35f13bf44c1b05af205f9b4a1e00cf6cc10c5e511',
157
    ];
158
159
    /**
160
     * @param string      $appId     Application id for the running application
161
     * @param string|null $attestDir Directory where trusted attestation roots may be found
162
     * @param array|null  $facetIds  List of trusted Facet IDs
163
     * @throws Error If OpenSSL older than 1.0.0 is used
164
     */
165
    public function __construct($appId, $attestDir = null, $facetIds = null)
166
    {
167
        if (OPENSSL_VERSION_NUMBER < 0x10000000) {
168
            throw new Error(
169
                'OpenSSL has to be at least version 1.0.0, this is ' . OPENSSL_VERSION_TEXT,
170
                ERR_OLD_OPENSSL
171
            );
172
        }
173
        $this->appId = $appId;
174
        $this->attestDir = $attestDir;
175
176
        if (!is_array($facetIds)) {
177
            $facetIds = [$appId];
178
        }
179
        $this->facetIds = $facetIds;
180
    }
181
182
    /**
183
     * Called to get a registration request to send to a user.
184
     * Returns an array of one registration request and a array of sign requests.
185
     *
186
     * @param array $registrations  List of current registrations for this
187
     *                              user, to prevent the user from registering the same authenticator several
188
     *                              times.
189
     * @return array An array of two elements, the first containing a
190
     *                              RegisterRequest the second being an array of SignRequest
191
     * @throws Exception
192
     */
193
    public function getRegisterData(array $registrations = []): array
194
    {
195
        $challenge = $this->createChallenge();
196
        $request = new RegisterRequest($challenge, $this->appId);
197
        $signs = $this->getAuthenticateData($registrations);
198
        return [$request, $signs];
199
    }
200
201
    /**
202
     * Called to verify and unpack a registration message.
203
     *
204
     * @param RegisterRequest $request      this is a reply to
205
     * @param object          $response     response from a user
206
     * @param bool            $includeCert  set to true if the attestation certificate should be
207
     *                                      included in the returned Registration object
208
     * @return Registration
209
     * @throws Error
210
     */
211
    public function doRegister($request, $response, $includeCert = true): ?Registration
212
    {
213
        if (!is_object($request)) {
214
            throw new InvalidArgumentException('$request of doRegister() method only accepts object.');
215
        }
216
217
        if (!is_object($response)) {
218
            throw new InvalidArgumentException('$response of doRegister() method only accepts object.');
219
        }
220
221
        if (property_exists($response, 'errorCode') && $response->errorCode !== 0) {
222
            throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING);
223
        }
224
225
        if (!is_bool($includeCert)) {
0 ignored issues
show
introduced by
The condition is_bool($includeCert) is always true.
Loading history...
226
            throw new InvalidArgumentException('$include_cert of doRegister() method only accepts boolean.');
227
        }
228
229
        $rawReg = $this->base64uDecode($response->registrationData);
230
        $regData = array_values(unpack('C*', $rawReg));
0 ignored issues
show
Bug introduced by
It seems like unpack('C*', $rawReg) can also be of type false; however, parameter $input of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

230
        $regData = array_values(/** @scrutinizer ignore-type */ unpack('C*', $rawReg));
Loading history...
231
        $clientData = $this->base64uDecode($response->clientData);
232
        $cli = json_decode($clientData, false);
233
234
        if ($cli->challenge !== $request->challenge) {
235
            throw new Error('Registration challenge does not match', ERR_UNMATCHED_CHALLENGE);
236
        }
237
238
        if (isset($cli->typ) && $cli->typ !== REQUEST_TYPE_REGISTER) {
239
            throw new Error('ClientData type is invalid', ERR_BAD_TYPE);
240
        }
241
242
        if (isset($cli->origin) && !in_array($cli->origin, $this->facetIds, true)) {
243
            throw new Error('App ID does not match the origin', ERR_NO_MATCHING_ORIGIN);
244
        }
245
246
        $registration = new Registration();
247
        $offs = 1;
248
        $pubKey = substr($rawReg, $offs, PUBKEY_LEN);
249
        $offs += PUBKEY_LEN;
250
        // decode the pubKey to make sure it's good
251
        $tmpKey = $this->pubkeyToPem($pubKey);
252
        if ($tmpKey === null) {
253
            throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE);
254
        }
255
        $registration->publicKey = base64_encode($pubKey);
256
        $khLen = $regData[$offs++];
257
        $kh = substr($rawReg, $offs, $khLen);
258
        $offs += $khLen;
259
        $registration->keyHandle = $this->base64uEncode($kh);
260
261
        // length of certificate is stored in byte 3 and 4 (excluding the first 4 bytes)
262
        $certLen = 4;
263
        $certLen += ($regData[$offs + 2] << 8);
264
        $certLen += $regData[$offs + 3];
265
266
        $rawCert = $this->fixSignatureUnusedBits(substr($rawReg, $offs, $certLen));
267
        $offs += $certLen;
268
        $pemCert = "-----BEGIN CERTIFICATE-----\r\n";
269
        $pemCert .= chunk_split(base64_encode($rawCert), 64);
270
        $pemCert .= '-----END CERTIFICATE-----';
271
        if ($includeCert) {
272
            $registration->certificate = base64_encode($rawCert);
273
        }
274
        if ($this->attestDir) {
275
            if (openssl_x509_checkpurpose($pemCert, -1, $this->getCerts()) !== true) {
276
                throw new Error('Attestation certificate can not be validated', ERR_ATTESTATION_VERIFICATION);
277
            }
278
        }
279
280
        if (!openssl_pkey_get_public($pemCert)) {
281
            throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE);
282
        }
283
        $signature = substr($rawReg, $offs);
284
285
        $dataToVerify = pack('C', 0);
286
        $dataToVerify .= hash('sha256', $request->appId, true);
287
        $dataToVerify .= hash('sha256', $clientData, true);
288
        $dataToVerify .= $kh;
289
        $dataToVerify .= $pubKey;
290
291
        if (openssl_verify($dataToVerify, $signature, $pemCert, 'sha256') === 1) {
0 ignored issues
show
Bug introduced by
'sha256' of type string is incompatible with the type integer expected by parameter $signature_alg of openssl_verify(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

291
        if (openssl_verify($dataToVerify, $signature, $pemCert, /** @scrutinizer ignore-type */ 'sha256') === 1) {
Loading history...
292
            return $registration;
293
        }
294
295
        throw new Error('Attestation signature does not match', ERR_ATTESTATION_SIGNATURE);
296
    }
297
298
    /**
299
     * Called to get an authentication request.
300
     *
301
     * @param array $registrations An array of the registrations to create authentication requests for.
302
     * @return array An array of SignRequest
303
     * @throws Exception
304
     */
305
    public function getAuthenticateData(array $registrations): array
306
    {
307
        $sigs = [];
308
        $challenge = $this->createChallenge();
309
        foreach ($registrations as $reg) {
310
            if (!is_object($reg)) {
311
                throw new InvalidArgumentException(
312
                    '$registrations of getAuthenticateData() method only accepts array of object.'
313
                );
314
            }
315
            /**
316
             * @var Registration $reg
317
             */
318
319
            $sig = new SignRequest();
320
            $sig->appId = $this->appId;
321
            $sig->keyHandle = $reg->keyHandle;
322
            $sig->challenge = $challenge;
323
            $sigs[] = $sig;
324
        }
325
        return $sigs;
326
    }
327
328
    /**
329
     * Called to verify an authentication response.
330
     *
331
     * The Registration object returned on success contains an updated counter
332
     * that should be saved for future authentications.
333
     * If the Error returned is ERR_COUNTER_TOO_LOW this is an indication of
334
     * token cloning or similar and appropriate action should be taken.
335
     *
336
     * @param array  $requests      An array of outstanding authentication requests
337
     * @param array  $registrations An array of current registrations
338
     * @param object $response      A response from the authenticator
339
     * @return Registration
340
     * @throws Error
341
     */
342
    public function doAuthenticate(array $requests, array $registrations, $response): ?Registration
343
    {
344
        if (!is_object($response)) {
345
            throw new InvalidArgumentException('$response of doAuthenticate() method only accepts object.');
346
        }
347
348
        if (property_exists($response, 'errorCode') && $response->errorCode !== 0) {
349
            throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING);
350
        }
351
352
        /**
353
         * @var object|null $req
354
         */
355
        $req = null;
356
357
        /**
358
         * @var object|null $reg
359
         */
360
        $reg = null;
361
362
        $clientData = $this->base64uDecode($response->clientData);
363
        $decodedClient = json_decode($clientData, false);
364
365
        if (isset($decodedClient->typ) && $decodedClient->typ !== REQUEST_TYPE_AUTHENTICATE) {
366
            throw new Error('ClientData type is invalid', ERR_BAD_TYPE);
367
        }
368
369
        foreach ($requests as $req) {
370
            if (!is_object($req)) {
371
                throw new InvalidArgumentException(
372
                    '$requests of doAuthenticate() method only accepts array of object.'
373
                );
374
            }
375
376
            if ($req->keyHandle === $response->keyHandle && $req->challenge === $decodedClient->challenge) {
377
                break;
378
            }
379
380
            $req = null;
381
        }
382
        if ($req === null) {
383
            throw new Error('No matching request found', ERR_NO_MATCHING_REQUEST);
384
        }
385
        if (isset($decodedClient->origin) && !in_array($decodedClient->origin, $this->facetIds, true)) {
386
            throw new Error('App ID does not match the origin', ERR_NO_MATCHING_ORIGIN);
387
        }
388
        foreach ($registrations as $reg) {
389
            if (!is_object($reg)) {
390
                throw new InvalidArgumentException(
391
                    '$registrations of doAuthenticate() method only accepts array of object.'
392
                );
393
            }
394
395
            if ($reg->keyHandle === $response->keyHandle) {
396
                break;
397
            }
398
            $reg = null;
399
        }
400
        if ($reg === null) {
401
            throw new Error('No matching registration found', ERR_NO_MATCHING_REGISTRATION);
402
        }
403
        $pemKey = $this->pubkeyToPem($this->base64uDecode($reg->publicKey));
404
        if ($pemKey === null) {
405
            throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE);
406
        }
407
408
        $signData = $this->base64uDecode($response->signatureData);
409
        $dataToVerify = hash('sha256', $req->appId, true);
410
        $dataToVerify .= substr($signData, 0, 5);
411
        $dataToVerify .= hash('sha256', $clientData, true);
412
        $signature = substr($signData, 5);
413
414
        if (openssl_verify($dataToVerify, $signature, $pemKey, 'sha256') === 1) {
0 ignored issues
show
Bug introduced by
'sha256' of type string is incompatible with the type integer expected by parameter $signature_alg of openssl_verify(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

414
        if (openssl_verify($dataToVerify, $signature, $pemKey, /** @scrutinizer ignore-type */ 'sha256') === 1) {
Loading history...
415
            $upb = unpack('Cupb', substr($signData, 0, 1));
416
            if ($upb['upb'] !== 1) {
417
                throw new Error('User presence byte value is invalid', ERR_BAD_USER_PRESENCE);
418
            }
419
            $ctr = unpack('Nctr', substr($signData, 1, 4));
420
            $counter = $ctr['ctr'];
421
            /* TODO: wrap-around should be handled somehow.. */
422
            if ($counter > $reg->counter) {
423
                $reg->counter = $counter;
424
                return self::castObjectToRegistration($reg);
425
            }
426
427
            throw new Error('Counter too low.', ERR_COUNTER_TOO_LOW);
428
        }
429
430
        throw new Error('Authentication failed', ERR_AUTHENTICATION_FAILURE);
431
    }
432
433
    /**
434
     * @param object $object
435
     * @return Registration
436
     */
437
    protected static function castObjectToRegistration($object): Registration
438
    {
439
        $reg = new Registration();
440
        if (isset($object->publicKey)) {
441
            $reg->publicKey = $object->publicKey;
442
        }
443
        if (isset($object->certificate)) {
444
            $reg->certificate = $object->certificate;
445
        }
446
        if (isset($object->counter)) {
447
            $reg->counter = $object->counter;
448
        }
449
        if (isset($object->keyHandle)) {
450
            $reg->keyHandle = $object->keyHandle;
451
        }
452
        return $reg;
453
    }
454
455
    /**
456
     * @return array
457
     */
458
    private function getCerts(): array
459
    {
460
        $files = [];
461
        $dir = $this->attestDir;
462
        if ($dir !== null && is_dir($dir) && $handle = opendir($dir)) {
463
            while (false !== ($entry = readdir($handle))) {
464
                if (is_file("$dir/$entry")) {
465
                    $files[] = "$dir/$entry";
466
                }
467
            }
468
            closedir($handle);
469
        } elseif (is_file((string) $dir)) {
470
            $files[] = (string) $dir;
471
        }
472
        return $files;
473
    }
474
475
    /**
476
     * Retrieves the challenge from a raw response.
477
     *
478
     * @param object $response A response from the authenticator
479
     * @return mixed the decoded client data
480
     */
481
    public function extractChallenge($response)
482
    {
483
        $clientData = $this->base64uDecode($response->clientData);
484
        return json_decode($clientData, false)->challenge;
485
    }
486
487
    /**
488
     * @param string $data
489
     * @return string
490
     */
491
    private function base64uEncode($data): string
492
    {
493
        return trim(strtr(base64_encode($data), '+/', '-_'), '=');
494
    }
495
496
    /**
497
     * @param string $data
498
     * @return string
499
     */
500
    private function base64uDecode($data): string
501
    {
502
        return base64_decode(strtr($data, '-_', '+/'));
503
    }
504
505
    /**
506
     * @param string $key
507
     * @return string|null
508
     */
509
    private function pubkeyToPem($key): ?string
510
    {
511
        if (strlen($key) !== PUBKEY_LEN || $key[0] !== "\x04") {
512
            return null;
513
        }
514
515
        /*
516
         * Convert the public key to binary DER format first
517
         * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
518
         *
519
         *  SEQUENCE(2 elem)                        30 59
520
         *   SEQUENCE(2 elem)                       30 13
521
         *    OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
522
         *    OID1.2.840.10045.3.1.7 (secp256r1)    06 08 2a 86 48 ce 3d 03 01 07
523
         *   BIT STRING(520 bit)                    03 42 ..key..
524
         */
525
        $der = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
526
        $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
527
        $der .= "\0" . $key;
528
529
        $pem = "-----BEGIN PUBLIC KEY-----\r\n";
530
        $pem .= chunk_split(base64_encode($der), 64);
531
        $pem .= '-----END PUBLIC KEY-----';
532
533
        return $pem;
534
    }
535
536
    /**
537
     * called to create a challenge. For testing purposes, the U2F class can be inherited,
538
     * and this method overridden to always return the same challenge.
539
     *
540
     * @return string the challenge
541
     * @throws Exception if openssl doesn't have cryptographically strong source
542
     */
543
    protected function createChallenge(): string
544
    {
545
        $challenge = random_bytes(32);
546
        $challenge = $this->base64uEncode($challenge);
547
548
        return $challenge;
549
    }
550
551
    /**
552
     * Fixes a certificate where the signature contains unused bits.
553
     *
554
     * @param string $cert
555
     * @return mixed
556
     */
557
    private function fixSignatureUnusedBits($cert)
558
    {
559
        if (in_array(hash('sha256', $cert), static::FIXCERTS, true)) {
560
            $cert[strlen($cert) - 257] = "\0";
561
        }
562
        return $cert;
563
    }
564
}
565