U2F::fixSignatureUnusedBits()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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

179
        $regData = array_values(/** @scrutinizer ignore-type */ unpack('C*', $rawReg));
Loading history...
180
        $clientData = $this->base64u_decode($response->clientData);
181
        $cli = json_decode($clientData);
182
183
        if($cli->challenge !== $request->challenge) {
184
            throw new Error('Registration challenge does not match', ERR_UNMATCHED_CHALLENGE );
185
        }
186
187
        if(isset($cli->typ) && $cli->typ !== REQUEST_TYPE_REGISTER) {
188
            throw new Error('ClientData type is invalid', ERR_BAD_TYPE);
189
        }
190
191
        if(isset($cli->origin) && !in_array($cli->origin, $this->facetIds, true)) {
192
            throw new Error('App ID does not match the origin', ERR_NO_MATCHING_ORIGIN);
193
        }
194
195
        $registration = new Registration();
196
        $offs = 1;
197
        $pubKey = substr($rawReg, $offs, PUBKEY_LEN);
198
        $offs += PUBKEY_LEN;
199
        // decode the pubKey to make sure it's good
200
        $tmpKey = $this->pubkey_to_pem($pubKey);
201
        if($tmpKey === null) {
202
            throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
203
        }
204
        $registration->publicKey = base64_encode($pubKey);
205
        $khLen = $regData[$offs++];
206
        $kh = substr($rawReg, $offs, $khLen);
207
        $offs += $khLen;
208
        $registration->keyHandle = $this->base64u_encode($kh);
209
210
        // length of certificate is stored in byte 3 and 4 (excluding the first 4 bytes)
211
        $certLen = 4;
212
        $certLen += ($regData[$offs + 2] << 8);
213
        $certLen += $regData[$offs + 3];
214
215
        $rawCert = $this->fixSignatureUnusedBits(substr($rawReg, $offs, $certLen));
216
        $offs += $certLen;
217
        $pemCert  = "-----BEGIN CERTIFICATE-----\r\n";
218
        $pemCert .= chunk_split(base64_encode($rawCert), 64);
219
        $pemCert .= "-----END CERTIFICATE-----";
220
        if($includeCert) {
221
            $registration->certificate = base64_encode($rawCert);
222
        }
223
        if($this->attestDir) {
224
            if(openssl_x509_checkpurpose($pemCert, -1, $this->get_certs()) !== true) {
225
                throw new Error('Attestation certificate can not be validated', ERR_ATTESTATION_VERIFICATION );
226
            }
227
        }
228
229
        if(!openssl_pkey_get_public($pemCert)) {
230
            throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
231
        }
232
        $signature = substr($rawReg, $offs);
233
234
        $dataToVerify  = pack('C', 0);
235
        $dataToVerify .= hash('sha256', $request->appId, true);
236
        $dataToVerify .= hash('sha256', $clientData, true);
237
        $dataToVerify .= $kh;
238
        $dataToVerify .= $pubKey;
239
240
        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

240
        if(openssl_verify($dataToVerify, $signature, $pemCert, /** @scrutinizer ignore-type */ 'sha256') === 1) {
Loading history...
241
            return $registration;
242
        } else {
243
            throw new Error('Attestation signature does not match', ERR_ATTESTATION_SIGNATURE );
244
        }
245
    }
246
247
    /**
248
     * Called to get an authentication request.
249
     *
250
     * @param array $registrations An array of the registrations to create authentication requests for.
251
     * @return array An array of SignRequest
252
     * @throws Error
253
     */
254
    public function getAuthenticateData(array $registrations)
255
    {
256
        $sigs = array();
257
        $challenge = $this->createChallenge();
258
        foreach ($registrations as $reg) {
259
            if( !is_object( $reg ) ) {
260
                throw new \InvalidArgumentException('$registrations of getAuthenticateData() method only accepts array of object.');
261
            }
262
            /** @var Registration $reg */
263
264
            $sig = new SignRequest();
265
            $sig->appId = $this->appId;
266
            $sig->keyHandle = $reg->keyHandle;
267
            $sig->challenge = $challenge;
268
            $sigs[] = $sig;
269
        }
270
        return $sigs;
271
    }
272
273
    /**
274
     * Called to verify an authentication response.
275
     *
276
     * @param array $requests An array of outstanding authentication requests
277
     * @param array $registrations An array of current registrations
278
     * @param object $response A response from the authenticator
279
     * @return Registration
280
     * @throws Error
281
     *
282
     * The Registration object returned on success contains an updated counter
283
     * that should be saved for future authentications.
284
     * If the Error returned is ERR_COUNTER_TOO_LOW this is an indication of
285
     * token cloning or similar and appropriate action should be taken.
286
     */
287
    public function doAuthenticate(array $requests, array $registrations, $response)
288
    {
289
        if( !is_object( $response ) ) {
290
            throw new \InvalidArgumentException('$response of doAuthenticate() method only accepts object.');
291
        }
292
293
        if( property_exists( $response, 'errorCode') && $response->errorCode !== 0 ) {
294
            throw new Error('User-agent returned error. Error code: ' . $response->errorCode, ERR_BAD_UA_RETURNING );
295
        }
296
297
        /** @var object|null $req */
298
        $req = null;
299
300
        /** @var object|null $reg */
301
        $reg = null;
302
303
        $clientData = $this->base64u_decode($response->clientData);
304
        $decodedClient = json_decode($clientData);
305
306
        if(isset($decodedClient->typ) && $decodedClient->typ !== REQUEST_TYPE_AUTHENTICATE) {
307
            throw new Error('ClientData type is invalid', ERR_BAD_TYPE);
308
        }
309
310
        foreach ($requests as $req) {
311
            if( !is_object( $req ) ) {
312
                throw new \InvalidArgumentException('$requests of doAuthenticate() method only accepts array of object.');
313
            }
314
315
            if($req->keyHandle === $response->keyHandle && $req->challenge === $decodedClient->challenge) {
316
                break;
317
            }
318
319
            $req = null;
320
        }
321
        if($req === null) {
322
            throw new Error('No matching request found', ERR_NO_MATCHING_REQUEST );
323
        }
324
        if(isset($decodedClient->origin) && !in_array($decodedClient->origin, $this->facetIds, true)) {
325
            throw new Error('App ID does not match the origin', ERR_NO_MATCHING_ORIGIN);
326
        }
327
        foreach ($registrations as $reg) {
328
            if( !is_object( $reg ) ) {
329
                throw new \InvalidArgumentException('$registrations of doAuthenticate() method only accepts array of object.');
330
            }
331
332
            if($reg->keyHandle === $response->keyHandle) {
333
                break;
334
            }
335
            $reg = null;
336
        }
337
        if($reg === null) {
338
            throw new Error('No matching registration found', ERR_NO_MATCHING_REGISTRATION );
339
        }
340
        $pemKey = $this->pubkey_to_pem($this->base64u_decode($reg->publicKey));
341
        if($pemKey === null) {
342
            throw new Error('Decoding of public key failed', ERR_PUBKEY_DECODE );
343
        }
344
345
        $signData = $this->base64u_decode($response->signatureData);
346
        $dataToVerify  = hash('sha256', $req->appId, true);
347
        $dataToVerify .= substr($signData, 0, 5);
348
        $dataToVerify .= hash('sha256', $clientData, true);
349
        $signature = substr($signData, 5);
350
351
        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

351
        if(openssl_verify($dataToVerify, $signature, $pemKey, /** @scrutinizer ignore-type */ 'sha256') === 1) {
Loading history...
352
            $upb = unpack("Cupb", substr($signData, 0, 1));
353
            if($upb['upb'] !== 1) {
354
                throw new Error('User presence byte value is invalid', ERR_BAD_USER_PRESENCE );
355
            }
356
            $ctr = unpack("Nctr", substr($signData, 1, 4));
357
            $counter = $ctr['ctr'];
358
            /* TODO: wrap-around should be handled somehow.. */
359
            if($counter > $reg->counter) {
360
                $reg->counter = $counter;
361
                return self::castObjectToRegistration($reg);
362
            } else {
363
                throw new Error('Counter too low.', ERR_COUNTER_TOO_LOW );
364
            }
365
        } else {
366
            throw new Error('Authentication failed', ERR_AUTHENTICATION_FAILURE );
367
        }
368
    }
369
370
    /**
371
     * @param object $object
372
     * @return Registration
373
     */
374
    protected static function castObjectToRegistration($object)
375
    {
376
        $reg = new Registration();
377
        if (isset($object->publicKey)) {
378
            $reg->publicKey = $object->publicKey;
379
        }
380
        if (isset($object->certificate)) {
381
            $reg->certificate = $object->certificate;
382
        }
383
        if (isset($object->counter)) {
384
            $reg->counter = $object->counter;
385
        }
386
        if (isset($object->keyHandle)) {
387
            $reg->keyHandle = $object->keyHandle;
388
        }
389
        return $reg;
390
    }
391
392
    /**
393
     * @return array
394
     */
395
    private function get_certs()
396
    {
397
        $files = array();
398
        $dir = $this->attestDir;
399
        if($dir !== null && is_dir($dir) && $handle = opendir($dir)) {
400
            while(false !== ($entry = readdir($handle))) {
401
                if(is_file("$dir/$entry")) {
402
                    $files[] = "$dir/$entry";
403
                }
404
            }
405
            closedir($handle);
406
        } elseif (is_file("$dir")) {
407
            $files[] = "$dir";
408
        }
409
        return $files;
410
    }
411
412
    /**
413
     * Retrieves the challenge from a raw response.
414
     * @param object $response A response from the authenticator
415
     * @return mixed the decoded client data
416
     */
417
    public function extractChallenge($response)
418
    {
419
        $clientData = $this->base64u_decode($response->clientData);
420
        $cli = json_decode($clientData);
421
422
        return $cli->challenge;
423
    }
424
425
    /**
426
     * @param string $data
427
     * @return string
428
     */
429
    private function base64u_encode($data)
430
    {
431
        return trim(strtr(base64_encode($data), '+/', '-_'), '=');
432
    }
433
434
    /**
435
     * @param string $data
436
     * @return string
437
     */
438
    private function base64u_decode($data)
439
    {
440
        return base64_decode(strtr($data, '-_', '+/'));
441
    }
442
443
    /**
444
     * @param string $key
445
     * @return null|string
446
     */
447
    private function pubkey_to_pem($key)
448
    {
449
        if(strlen($key) !== PUBKEY_LEN || $key[0] !== "\x04") {
450
            return null;
451
        }
452
453
        /*
454
         * Convert the public key to binary DER format first
455
         * Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
456
         *
457
         *  SEQUENCE(2 elem)                        30 59
458
         *   SEQUENCE(2 elem)                       30 13
459
         *    OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
460
         *    OID1.2.840.10045.3.1.7 (secp256r1)    06 08 2a 86 48 ce 3d 03 01 07
461
         *   BIT STRING(520 bit)                    03 42 ..key..
462
         */
463
        $der  = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
464
        $der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
465
        $der .= "\0".$key;
466
467
        $pem  = "-----BEGIN PUBLIC KEY-----\r\n";
468
        $pem .= chunk_split(base64_encode($der), 64);
469
        $pem .= "-----END PUBLIC KEY-----";
470
471
        return $pem;
472
    }
473
474
    /**
475
     * called to create a challenge. For testing purposes, the U2F class can be inherited,
476
     * and this method overridden to always return the same challenge.
477
     *
478
     * @return string the challenge
479
     * @throws Error if openssl doesn't have cryptographically strong source
480
     */
481
    protected function createChallenge()
482
    {
483
        $challenge = random_bytes(32);
484
        $challenge = $this->base64u_encode( $challenge );
485
486
        return $challenge;
487
    }
488
489
    /**
490
     * Fixes a certificate where the signature contains unused bits.
491
     *
492
     * @param string $cert
493
     * @return mixed
494
     */
495
    private function fixSignatureUnusedBits($cert)
496
    {
497
        if(in_array(hash('sha256', $cert), $this->FIXCERTS, true)) {
498
            $cert[strlen($cert) - 257] = "\0";
499
        }
500
        return $cert;
501
    }
502
}
503