Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
namespace lbuchs\WebAuthn\Attestation;
4
use lbuchs\WebAuthn\WebAuthnException;
5
use lbuchs\WebAuthn\CBOR\CborDecoder;
6
use lbuchs\WebAuthn\Binary\ByteBuffer;
7
 
8
/**
9
 * @author Lukas Buchs
10
 * @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
11
 */
12
class AuthenticatorData {
13
    protected $_binary;
14
    protected $_rpIdHash;
15
    protected $_flags;
16
    protected $_signCount;
17
    protected $_attestedCredentialData;
18
    protected $_extensionData;
19
 
20
 
21
 
22
    // Cose encoded keys
23
    private static $_COSE_KTY = 1;
24
    private static $_COSE_ALG = 3;
25
 
26
    // Cose curve
27
    private static $_COSE_CRV = -1;
28
    private static $_COSE_X = -2;
29
    private static $_COSE_Y = -3;
30
 
31
    // Cose RSA PS256
32
    private static $_COSE_N = -1;
33
    private static $_COSE_E = -2;
34
 
35
    // EC2 key type
36
    private static $_EC2_TYPE = 2;
37
    private static $_EC2_ES256 = -7;
38
    private static $_EC2_P256 = 1;
39
 
40
    // RSA key type
41
    private static $_RSA_TYPE = 3;
42
    private static $_RSA_RS256 = -257;
43
 
44
    // OKP key type
45
    private static $_OKP_TYPE = 1;
46
    private static $_OKP_ED25519 = 6;
47
    private static $_OKP_EDDSA = -8;
48
 
49
    /**
50
     * Parsing the authenticatorData binary.
51
     * @param string $binary
52
     * @throws WebAuthnException
53
     */
54
    public function __construct($binary) {
55
        if (!\is_string($binary) || \strlen($binary) < 37) {
56
            throw new WebAuthnException('Invalid authenticatorData input', WebAuthnException::INVALID_DATA);
57
        }
58
        $this->_binary = $binary;
59
 
60
        // Read infos from binary
61
        // https://www.w3.org/TR/webauthn/#sec-authenticator-data
62
 
63
        // RP ID
64
        $this->_rpIdHash = \substr($binary, 0, 32);
65
 
66
        // flags (1 byte)
67
        $flags = \unpack('Cflags', \substr($binary, 32, 1))['flags'];
68
        $this->_flags = $this->_readFlags($flags);
69
 
70
        // signature counter: 32-bit unsigned big-endian integer.
71
        $this->_signCount = \unpack('Nsigncount', \substr($binary, 33, 4))['signcount'];
72
 
73
        $offset = 37;
74
        // https://www.w3.org/TR/webauthn/#sec-attested-credential-data
75
        if ($this->_flags->attestedDataIncluded) {
76
            $this->_attestedCredentialData = $this->_readAttestData($binary, $offset);
77
        }
78
 
79
        if ($this->_flags->extensionDataIncluded) {
80
            $this->_readExtensionData(\substr($binary, $offset));
81
        }
82
    }
83
 
84
    /**
85
     * Authenticator Attestation Globally Unique Identifier, a unique number
86
     * that identifies the model of the authenticator (not the specific instance
87
     * of the authenticator)
88
     * The aaguid may be 0 if the user is using a old u2f device and/or if
89
     * the browser is using the fido-u2f format.
90
     * @return string
91
     * @throws WebAuthnException
92
     */
93
    public function getAAGUID() {
94
        if (!($this->_attestedCredentialData instanceof \stdClass)) {
95
            throw  new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
96
        }
97
        return $this->_attestedCredentialData->aaguid;
98
    }
99
 
100
    /**
101
     * returns the authenticatorData as binary
102
     * @return string
103
     */
104
    public function getBinary() {
105
        return $this->_binary;
106
    }
107
 
108
    /**
109
     * returns the credentialId
110
     * @return string
111
     * @throws WebAuthnException
112
     */
113
    public function getCredentialId() {
114
        if (!($this->_attestedCredentialData instanceof \stdClass)) {
115
            throw  new WebAuthnException('credential id not included in authenticator data', WebAuthnException::INVALID_DATA);
116
        }
117
        return $this->_attestedCredentialData->credentialId;
118
    }
119
 
120
    /**
121
     * returns the public key in PEM format
122
     * @return string
123
     */
124
    public function getPublicKeyPem() {
125
        if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
126
            throw  new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
127
        }
128
 
129
        $der = null;
130
        switch ($this->_attestedCredentialData->credentialPublicKey->kty ?? null) {
131
            case self::$_EC2_TYPE: $der = $this->_getEc2Der(); break;
132
            case self::$_RSA_TYPE: $der = $this->_getRsaDer(); break;
133
            case self::$_OKP_TYPE: $der = $this->_getOkpDer(); break;
134
            default: throw new WebAuthnException('invalid key type', WebAuthnException::INVALID_DATA);
135
        }
136
 
137
        $pem = '-----BEGIN PUBLIC KEY-----' . "\n";
138
        $pem .= \chunk_split(\base64_encode($der), 64, "\n");
139
        $pem .= '-----END PUBLIC KEY-----' . "\n";
140
        return $pem;
141
    }
142
 
143
    /**
144
     * returns the public key in U2F format
145
     * @return string
146
     * @throws WebAuthnException
147
     */
148
    public function getPublicKeyU2F() {
149
        if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
150
            throw  new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
151
        }
152
        if (($this->_attestedCredentialData->credentialPublicKey->kty ?? null) !== self::$_EC2_TYPE) {
153
            throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
154
        }
155
        return "\x04" . // ECC uncompressed
156
                $this->_attestedCredentialData->credentialPublicKey->x .
157
                $this->_attestedCredentialData->credentialPublicKey->y;
158
    }
159
 
160
    /**
161
     * returns the SHA256 hash of the relying party id (=hostname)
162
     * @return string
163
     */
164
    public function getRpIdHash() {
165
        return $this->_rpIdHash;
166
    }
167
 
168
    /**
169
     * returns the sign counter
170
     * @return int
171
     */
172
    public function getSignCount() {
173
        return $this->_signCount;
174
    }
175
 
176
    /**
177
     * returns true if the user is present
178
     * @return boolean
179
     */
180
    public function getUserPresent() {
181
        return $this->_flags->userPresent;
182
    }
183
 
184
    /**
185
     * returns true if the user is verified
186
     * @return boolean
187
     */
188
    public function getUserVerified() {
189
        return $this->_flags->userVerified;
190
    }
191
 
1441 ariadna 192
    /**
193
     * returns true if the backup is eligible
194
     * @return boolean
195
     */
196
    public function getIsBackupEligible()
197
    {
198
        return $this->_flags->isBackupEligible;
199
    }
200
 
201
    /**
202
     * returns true if the current credential is backed up
203
     * @return boolean
204
     */
205
    public function getIsBackup()
206
    {
207
        return $this->_flags->isBackup;
208
    }
209
 
1 efrain 210
    // -----------------------------------------------
211
    // PRIVATE
212
    // -----------------------------------------------
213
 
214
    /**
215
     * Returns DER encoded EC2 key
216
     * @return string
217
     */
218
    private function _getEc2Der() {
219
        return $this->_der_sequence(
220
            $this->_der_sequence(
221
                $this->_der_oid("\x2A\x86\x48\xCE\x3D\x02\x01") . // OID 1.2.840.10045.2.1 ecPublicKey
222
                $this->_der_oid("\x2A\x86\x48\xCE\x3D\x03\x01\x07")  // 1.2.840.10045.3.1.7 prime256v1
223
            ) .
224
            $this->_der_bitString($this->getPublicKeyU2F())
225
        );
226
    }
227
 
228
    /**
229
     * Returns DER encoded EdDSA key
230
     * @return string
231
     */
232
    private function _getOkpDer() {
233
        return $this->_der_sequence(
234
            $this->_der_sequence(
235
                $this->_der_oid("\x2B\x65\x70") // OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
236
            ) .
237
            $this->_der_bitString($this->_attestedCredentialData->credentialPublicKey->x)
238
        );
239
    }
240
 
241
    /**
242
     * Returns DER encoded RSA key
243
     * @return string
244
     */
245
    private function _getRsaDer() {
246
        return $this->_der_sequence(
247
            $this->_der_sequence(
248
                $this->_der_oid("\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01") . // OID 1.2.840.113549.1.1.1 rsaEncryption
249
                $this->_der_nullValue()
250
            ) .
251
            $this->_der_bitString(
252
                $this->_der_sequence(
253
                    $this->_der_unsignedInteger($this->_attestedCredentialData->credentialPublicKey->n) .
254
                    $this->_der_unsignedInteger($this->_attestedCredentialData->credentialPublicKey->e)
255
                )
256
            )
257
        );
258
    }
259
 
260
    /**
261
     * reads the flags from flag byte
262
     * @param string $binFlag
263
     * @return \stdClass
264
     */
265
    private function _readFlags($binFlag) {
266
        $flags = new \stdClass();
267
 
268
        $flags->bit_0 = !!($binFlag & 1);
269
        $flags->bit_1 = !!($binFlag & 2);
270
        $flags->bit_2 = !!($binFlag & 4);
271
        $flags->bit_3 = !!($binFlag & 8);
272
        $flags->bit_4 = !!($binFlag & 16);
273
        $flags->bit_5 = !!($binFlag & 32);
274
        $flags->bit_6 = !!($binFlag & 64);
275
        $flags->bit_7 = !!($binFlag & 128);
276
 
277
        // named flags
278
        $flags->userPresent = $flags->bit_0;
279
        $flags->userVerified = $flags->bit_2;
1441 ariadna 280
        $flags->isBackupEligible = $flags->bit_3;
281
        $flags->isBackup = $flags->bit_4;
1 efrain 282
        $flags->attestedDataIncluded = $flags->bit_6;
283
        $flags->extensionDataIncluded = $flags->bit_7;
284
        return $flags;
285
    }
286
 
287
    /**
288
     * read attested data
289
     * @param string $binary
290
     * @param int $endOffset
291
     * @return \stdClass
292
     * @throws WebAuthnException
293
     */
294
    private function _readAttestData($binary, &$endOffset) {
295
        $attestedCData = new \stdClass();
296
        if (\strlen($binary) <= 55) {
297
            throw new WebAuthnException('Attested data should be present but is missing', WebAuthnException::INVALID_DATA);
298
        }
299
 
300
        // The AAGUID of the authenticator
301
        $attestedCData->aaguid = \substr($binary, 37, 16);
302
 
303
        //Byte length L of Credential ID, 16-bit unsigned big-endian integer.
304
        $length = \unpack('nlength', \substr($binary, 53, 2))['length'];
305
        $attestedCData->credentialId = \substr($binary, 55, $length);
306
 
307
        // set end offset
308
        $endOffset = 55 + $length;
309
 
310
        // extract public key
311
        $attestedCData->credentialPublicKey = $this->_readCredentialPublicKey($binary, 55 + $length, $endOffset);
312
 
313
        return $attestedCData;
314
    }
315
 
316
    /**
317
     * reads COSE key-encoded elliptic curve public key in EC2 format
318
     * @param string $binary
319
     * @param int $endOffset
320
     * @return \stdClass
321
     * @throws WebAuthnException
322
     */
323
    private function _readCredentialPublicKey($binary, $offset, &$endOffset) {
324
        $enc = CborDecoder::decodeInPlace($binary, $offset, $endOffset);
325
 
326
        // COSE key-encoded elliptic curve public key in EC2 format
327
        $credPKey = new \stdClass();
328
        $credPKey->kty = $enc[self::$_COSE_KTY];
329
        $credPKey->alg = $enc[self::$_COSE_ALG];
330
 
331
        switch ($credPKey->alg) {
332
            case self::$_EC2_ES256: $this->_readCredentialPublicKeyES256($credPKey, $enc); break;
333
            case self::$_RSA_RS256: $this->_readCredentialPublicKeyRS256($credPKey, $enc); break;
334
            case self::$_OKP_EDDSA: $this->_readCredentialPublicKeyEDDSA($credPKey, $enc); break;
335
        }
336
 
337
        return $credPKey;
338
    }
339
 
340
    /**
341
     * extract EDDSA informations from cose
342
     * @param \stdClass $credPKey
343
     * @param \stdClass $enc
344
     * @throws WebAuthnException
345
     */
346
    private function _readCredentialPublicKeyEDDSA(&$credPKey, $enc) {
347
        $credPKey->crv = $enc[self::$_COSE_CRV];
348
        $credPKey->x   = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
349
        unset ($enc);
350
 
351
        // Validation
352
        if ($credPKey->kty !== self::$_OKP_TYPE) {
353
            throw new WebAuthnException('public key not in OKP format', WebAuthnException::INVALID_PUBLIC_KEY);
354
        }
355
 
356
        if ($credPKey->alg !== self::$_OKP_EDDSA) {
357
            throw new WebAuthnException('signature algorithm not EdDSA', WebAuthnException::INVALID_PUBLIC_KEY);
358
        }
359
 
360
        if ($credPKey->crv !== self::$_OKP_ED25519) {
361
            throw new WebAuthnException('curve not Ed25519', WebAuthnException::INVALID_PUBLIC_KEY);
362
        }
363
 
364
        if (\strlen($credPKey->x) !== 32) {
365
            throw new WebAuthnException('Invalid X-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
366
        }
367
    }
368
 
369
    /**
370
     * extract ES256 informations from cose
371
     * @param \stdClass $credPKey
372
     * @param \stdClass $enc
373
     * @throws WebAuthnException
374
     */
375
    private function _readCredentialPublicKeyES256(&$credPKey, $enc) {
376
        $credPKey->crv = $enc[self::$_COSE_CRV];
377
        $credPKey->x   = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
378
        $credPKey->y   = $enc[self::$_COSE_Y] instanceof ByteBuffer ? $enc[self::$_COSE_Y]->getBinaryString() : null;
379
        unset ($enc);
380
 
381
        // Validation
382
        if ($credPKey->kty !== self::$_EC2_TYPE) {
383
            throw new WebAuthnException('public key not in EC2 format', WebAuthnException::INVALID_PUBLIC_KEY);
384
        }
385
 
386
        if ($credPKey->alg !== self::$_EC2_ES256) {
387
            throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
388
        }
389
 
390
        if ($credPKey->crv !== self::$_EC2_P256) {
391
            throw new WebAuthnException('curve not P-256', WebAuthnException::INVALID_PUBLIC_KEY);
392
        }
393
 
394
        if (\strlen($credPKey->x) !== 32) {
395
            throw new WebAuthnException('Invalid X-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
396
        }
397
 
398
        if (\strlen($credPKey->y) !== 32) {
399
            throw new WebAuthnException('Invalid Y-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
400
        }
401
    }
402
 
403
    /**
404
     * extract RS256 informations from COSE
405
     * @param \stdClass $credPKey
406
     * @param \stdClass $enc
407
     * @throws WebAuthnException
408
     */
409
    private function _readCredentialPublicKeyRS256(&$credPKey, $enc) {
410
        $credPKey->n = $enc[self::$_COSE_N] instanceof ByteBuffer ? $enc[self::$_COSE_N]->getBinaryString() : null;
411
        $credPKey->e = $enc[self::$_COSE_E] instanceof ByteBuffer ? $enc[self::$_COSE_E]->getBinaryString() : null;
412
        unset ($enc);
413
 
414
        // Validation
415
        if ($credPKey->kty !== self::$_RSA_TYPE) {
416
            throw new WebAuthnException('public key not in RSA format', WebAuthnException::INVALID_PUBLIC_KEY);
417
        }
418
 
419
        if ($credPKey->alg !== self::$_RSA_RS256) {
420
            throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
421
        }
422
 
423
        if (\strlen($credPKey->n) !== 256) {
424
            throw new WebAuthnException('Invalid RSA modulus', WebAuthnException::INVALID_PUBLIC_KEY);
425
        }
426
 
427
        if (\strlen($credPKey->e) !== 3) {
428
            throw new WebAuthnException('Invalid RSA public exponent', WebAuthnException::INVALID_PUBLIC_KEY);
429
        }
430
 
431
    }
432
 
433
    /**
434
     * reads cbor encoded extension data.
435
     * @param string $binary
436
     * @return array
437
     * @throws WebAuthnException
438
     */
439
    private function _readExtensionData($binary) {
440
        $ext = CborDecoder::decode($binary);
441
        if (!\is_array($ext)) {
442
            throw new WebAuthnException('invalid extension data', WebAuthnException::INVALID_DATA);
443
        }
444
 
445
        return $ext;
446
    }
447
 
448
 
449
    // ---------------
450
    // DER functions
451
    // ---------------
452
 
453
    private function _der_length($len) {
454
        if ($len < 128) {
455
            return \chr($len);
456
        }
457
        $lenBytes = '';
458
        while ($len > 0) {
459
            $lenBytes = \chr($len % 256) . $lenBytes;
460
            $len = \intdiv($len, 256);
461
        }
462
        return \chr(0x80 | \strlen($lenBytes)) . $lenBytes;
463
    }
464
 
465
    private function _der_sequence($contents) {
466
        return "\x30" . $this->_der_length(\strlen($contents)) . $contents;
467
    }
468
 
469
    private function _der_oid($encoded) {
470
        return "\x06" . $this->_der_length(\strlen($encoded)) . $encoded;
471
    }
472
 
473
    private function _der_bitString($bytes) {
474
        return "\x03" . $this->_der_length(\strlen($bytes) + 1) . "\x00" . $bytes;
475
    }
476
 
477
    private function _der_nullValue() {
478
        return "\x05\x00";
479
    }
480
 
481
    private function _der_unsignedInteger($bytes) {
482
        $len = \strlen($bytes);
483
 
484
        // Remove leading zero bytes
485
        for ($i = 0; $i < ($len - 1); $i++) {
486
            if (\ord($bytes[$i]) !== 0) {
487
                break;
488
            }
489
        }
490
        if ($i !== 0) {
491
            $bytes = \substr($bytes, $i);
492
        }
493
 
494
        // If most significant bit is set, prefix with another zero to prevent it being seen as negative number
495
        if ((\ord($bytes[0]) & 0x80) !== 0) {
496
            $bytes = "\x00" . $bytes;
497
        }
498
 
499
        return "\x02" . $this->_der_length(\strlen($bytes)) . $bytes;
500
    }
501
}