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;
4
use lbuchs\WebAuthn\Binary\ByteBuffer;
5
require_once 'WebAuthnException.php';
6
require_once 'Binary/ByteBuffer.php';
7
require_once 'Attestation/AttestationObject.php';
8
require_once 'Attestation/AuthenticatorData.php';
9
require_once 'Attestation/Format/FormatBase.php';
10
require_once 'Attestation/Format/None.php';
11
require_once 'Attestation/Format/AndroidKey.php';
12
require_once 'Attestation/Format/AndroidSafetyNet.php';
13
require_once 'Attestation/Format/Apple.php';
14
require_once 'Attestation/Format/Packed.php';
15
require_once 'Attestation/Format/Tpm.php';
16
require_once 'Attestation/Format/U2f.php';
17
require_once 'CBOR/CborDecoder.php';
18
 
19
/**
20
 * WebAuthn
21
 * @author Lukas Buchs
22
 * @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
23
 */
24
class WebAuthn {
25
    // relying party
26
    private $_rpName;
27
    private $_rpId;
28
    private $_rpIdHash;
29
    private $_challenge;
30
    private $_signatureCounter;
31
    private $_caFiles;
32
    private $_formats;
1441 ariadna 33
    private $_androidKeyHashes;
1 efrain 34
 
35
    /**
36
     * Initialize a new WebAuthn server
37
     * @param string $rpName the relying party name
38
     * @param string $rpId the relying party ID = the domain name
39
     * @param bool $useBase64UrlEncoding true to use base64 url encoding for binary data in json objects. Default is a RFC 1342-Like serialized string.
40
     * @throws WebAuthnException
41
     */
42
    public function __construct($rpName, $rpId, $allowedFormats=null, $useBase64UrlEncoding=false) {
43
        $this->_rpName = $rpName;
44
        $this->_rpId = $rpId;
45
        $this->_rpIdHash = \hash('sha256', $rpId, true);
46
        ByteBuffer::$useBase64UrlEncoding = !!$useBase64UrlEncoding;
47
        $supportedFormats = array('android-key', 'android-safetynet', 'apple', 'fido-u2f', 'none', 'packed', 'tpm');
48
 
49
        if (!\function_exists('\openssl_open')) {
50
            throw new WebAuthnException('OpenSSL-Module not installed');
51
        }
52
 
53
        if (!\in_array('SHA256', \array_map('\strtoupper', \openssl_get_md_methods()))) {
54
            throw new WebAuthnException('SHA256 not supported by this openssl installation.');
55
        }
56
 
57
        // default: all format
58
        if (!is_array($allowedFormats)) {
59
            $allowedFormats = $supportedFormats;
60
        }
61
        $this->_formats = $allowedFormats;
62
 
63
        // validate formats
64
        $invalidFormats = \array_diff($this->_formats, $supportedFormats);
65
        if (!$this->_formats || $invalidFormats) {
66
            throw new WebAuthnException('invalid formats on construct: ' . implode(', ', $invalidFormats));
67
        }
68
    }
69
 
70
    /**
71
     * add a root certificate to verify new registrations
72
     * @param string $path file path of / directory with root certificates
73
     * @param array|null $certFileExtensions if adding a direction, all files with provided extension are added. default: pem, crt, cer, der
74
     */
75
    public function addRootCertificates($path, $certFileExtensions=null) {
76
        if (!\is_array($this->_caFiles)) {
77
            $this->_caFiles = [];
78
        }
79
        if ($certFileExtensions === null) {
80
            $certFileExtensions = array('pem', 'crt', 'cer', 'der');
81
        }
82
        $path = \rtrim(\trim($path), '\\/');
83
        if (\is_dir($path)) {
84
            foreach (\scandir($path) as $ca) {
85
                if (\is_file($path . DIRECTORY_SEPARATOR . $ca) && \in_array(\strtolower(\pathinfo($ca, PATHINFO_EXTENSION)), $certFileExtensions)) {
86
                    $this->addRootCertificates($path . DIRECTORY_SEPARATOR . $ca);
87
                }
88
            }
89
        } else if (\is_file($path) && !\in_array(\realpath($path), $this->_caFiles)) {
90
            $this->_caFiles[] = \realpath($path);
91
        }
92
    }
93
 
94
    /**
1441 ariadna 95
     * add key hashes for android verification
96
     * @param array<string> $hashes
97
     * @return void
98
     */
99
    public function addAndroidKeyHashes($hashes) {
100
        if (!\is_array($this->_androidKeyHashes)) {
101
            $this->_androidKeyHashes = [];
102
        }
103
 
104
        foreach ($hashes as $hash) {
105
            if (is_string($hash)) {
106
                $this->_androidKeyHashes[] = $hash;
107
            }
108
        }
109
    }
110
 
111
    /**
1 efrain 112
     * Returns the generated challenge to save for later validation
113
     * @return ByteBuffer
114
     */
115
    public function getChallenge() {
116
        return $this->_challenge;
117
    }
118
 
119
    /**
120
     * generates the object for a key registration
121
     * provide this data to navigator.credentials.create
122
     * @param string $userId
123
     * @param string $userName
124
     * @param string $userDisplayName
125
     * @param int $timeout timeout in seconds
126
     * @param bool|string $requireResidentKey      'required', if the key should be stored by the authentication device
127
     *                                             Valid values:
128
     *                                             true = required
129
     *                                             false = preferred
130
     *                                             string 'required' 'preferred' 'discouraged'
131
     * @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
132
     *                                             if the response does not have the UV flag set.
133
     *                                             Valid values:
134
     *                                             true = required
135
     *                                             false = preferred
136
     *                                             string 'required' 'preferred' 'discouraged'
137
     * @param bool|null $crossPlatformAttachment   true for cross-platform devices (eg. fido usb),
138
     *                                             false for platform devices (eg. windows hello, android safetynet),
139
     *                                             null for both
140
     * @param array $excludeCredentialIds a array of ids, which are already registered, to prevent re-registration
141
     * @return \stdClass
142
     */
143
    public function getCreateArgs($userId, $userName, $userDisplayName, $timeout=20, $requireResidentKey=false, $requireUserVerification=false, $crossPlatformAttachment=null, $excludeCredentialIds=[]) {
144
 
145
        $args = new \stdClass();
146
        $args->publicKey = new \stdClass();
147
 
148
        // relying party
149
        $args->publicKey->rp = new \stdClass();
150
        $args->publicKey->rp->name = $this->_rpName;
151
        $args->publicKey->rp->id = $this->_rpId;
152
 
153
        $args->publicKey->authenticatorSelection = new \stdClass();
154
        $args->publicKey->authenticatorSelection->userVerification = 'preferred';
155
 
156
        // validate User Verification Requirement
157
        if (\is_bool($requireUserVerification)) {
158
            $args->publicKey->authenticatorSelection->userVerification = $requireUserVerification ? 'required' : 'preferred';
159
 
160
        } else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
161
            $args->publicKey->authenticatorSelection->userVerification = \strtolower($requireUserVerification);
162
        }
163
 
164
        // validate Resident Key Requirement
165
        if (\is_bool($requireResidentKey) && $requireResidentKey) {
166
            $args->publicKey->authenticatorSelection->requireResidentKey = true;
167
            $args->publicKey->authenticatorSelection->residentKey = 'required';
168
 
169
        } else if (\is_string($requireResidentKey) && \in_array(\strtolower($requireResidentKey), ['required', 'preferred', 'discouraged'])) {
170
            $requireResidentKey = \strtolower($requireResidentKey);
171
            $args->publicKey->authenticatorSelection->residentKey = $requireResidentKey;
172
            $args->publicKey->authenticatorSelection->requireResidentKey = $requireResidentKey === 'required';
173
        }
174
 
175
        // filte authenticators attached with the specified authenticator attachment modality
176
        if (\is_bool($crossPlatformAttachment)) {
177
            $args->publicKey->authenticatorSelection->authenticatorAttachment = $crossPlatformAttachment ? 'cross-platform' : 'platform';
178
        }
179
 
180
        // user
181
        $args->publicKey->user = new \stdClass();
182
        $args->publicKey->user->id = new ByteBuffer($userId); // binary
183
        $args->publicKey->user->name = $userName;
184
        $args->publicKey->user->displayName = $userDisplayName;
185
 
186
        // supported algorithms
187
        $args->publicKey->pubKeyCredParams = [];
188
 
189
        if (function_exists('sodium_crypto_sign_verify_detached') || \in_array('ed25519', \openssl_get_curve_names(), true)) {
190
            $tmp = new \stdClass();
191
            $tmp->type = 'public-key';
192
            $tmp->alg = -8; // EdDSA
193
            $args->publicKey->pubKeyCredParams[] = $tmp;
194
            unset ($tmp);
195
        }
196
 
197
        if (\in_array('prime256v1', \openssl_get_curve_names(), true)) {
198
            $tmp = new \stdClass();
199
            $tmp->type = 'public-key';
200
            $tmp->alg = -7; // ES256
201
            $args->publicKey->pubKeyCredParams[] = $tmp;
202
            unset ($tmp);
203
        }
204
 
205
        $tmp = new \stdClass();
206
        $tmp->type = 'public-key';
207
        $tmp->alg = -257; // RS256
208
        $args->publicKey->pubKeyCredParams[] = $tmp;
209
        unset ($tmp);
210
 
211
        // if there are root certificates added, we need direct attestation to validate
212
        // against the root certificate. If there are no root-certificates added,
213
        // anonymization ca are also accepted, because we can't validate the root anyway.
214
        $attestation = 'indirect';
215
        if (\is_array($this->_caFiles)) {
216
            $attestation = 'direct';
217
        }
218
 
219
        $args->publicKey->attestation = \count($this->_formats) === 1 && \in_array('none', $this->_formats) ? 'none' : $attestation;
220
        $args->publicKey->extensions = new \stdClass();
221
        $args->publicKey->extensions->exts = true;
222
        $args->publicKey->timeout = $timeout * 1000; // microseconds
223
        $args->publicKey->challenge = $this->_createChallenge(); // binary
224
 
225
        //prevent re-registration by specifying existing credentials
226
        $args->publicKey->excludeCredentials = [];
227
 
228
        if (is_array($excludeCredentialIds)) {
229
            foreach ($excludeCredentialIds as $id) {
230
                $tmp = new \stdClass();
231
                $tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id);  // binary
232
                $tmp->type = 'public-key';
233
                $tmp->transports = array('usb', 'nfc', 'ble', 'hybrid', 'internal');
234
                $args->publicKey->excludeCredentials[] = $tmp;
235
                unset ($tmp);
236
            }
237
        }
238
 
239
        return $args;
240
    }
241
 
242
    /**
243
     * generates the object for key validation
244
     * Provide this data to navigator.credentials.get
245
     * @param array $credentialIds binary
246
     * @param int $timeout timeout in seconds
247
     * @param bool $allowUsb allow removable USB
248
     * @param bool $allowNfc allow Near Field Communication (NFC)
249
     * @param bool $allowBle allow Bluetooth
250
     * @param bool $allowHybrid allow a combination of (often separate) data-transport and proximity mechanisms.
251
     * @param bool $allowInternal allow client device-specific transport. These authenticators are not removable from the client device.
252
     * @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
253
     *                                             if the response does not have the UV flag set.
254
     *                                             Valid values:
255
     *                                             true = required
256
     *                                             false = preferred
257
     *                                             string 'required' 'preferred' 'discouraged'
258
     * @return \stdClass
259
     */
260
    public function getGetArgs($credentialIds=[], $timeout=20, $allowUsb=true, $allowNfc=true, $allowBle=true, $allowHybrid=true, $allowInternal=true, $requireUserVerification=false) {
261
 
262
        // validate User Verification Requirement
263
        if (\is_bool($requireUserVerification)) {
264
            $requireUserVerification = $requireUserVerification ? 'required' : 'preferred';
265
        } else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
266
            $requireUserVerification = \strtolower($requireUserVerification);
267
        } else {
268
            $requireUserVerification = 'preferred';
269
        }
270
 
271
        $args = new \stdClass();
272
        $args->publicKey = new \stdClass();
273
        $args->publicKey->timeout = $timeout * 1000; // microseconds
274
        $args->publicKey->challenge = $this->_createChallenge();  // binary
275
        $args->publicKey->userVerification = $requireUserVerification;
276
        $args->publicKey->rpId = $this->_rpId;
277
 
278
        if (\is_array($credentialIds) && \count($credentialIds) > 0) {
279
            $args->publicKey->allowCredentials = [];
280
 
281
            foreach ($credentialIds as $id) {
282
                $tmp = new \stdClass();
283
                $tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id);  // binary
284
                $tmp->transports = [];
285
 
286
                if ($allowUsb) {
287
                    $tmp->transports[] = 'usb';
288
                }
289
                if ($allowNfc) {
290
                    $tmp->transports[] = 'nfc';
291
                }
292
                if ($allowBle) {
293
                    $tmp->transports[] = 'ble';
294
                }
295
                if ($allowHybrid) {
296
                    $tmp->transports[] = 'hybrid';
297
                }
298
                if ($allowInternal) {
299
                    $tmp->transports[] = 'internal';
300
                }
301
 
302
                $tmp->type = 'public-key';
303
                $args->publicKey->allowCredentials[] = $tmp;
304
                unset ($tmp);
305
            }
306
        }
307
 
308
        return $args;
309
    }
310
 
311
    /**
312
     * returns the new signature counter value.
313
     * returns null if there is no counter
314
     * @return ?int
315
     */
316
    public function getSignatureCounter() {
317
        return \is_int($this->_signatureCounter) ? $this->_signatureCounter : null;
318
    }
319
 
320
    /**
321
     * process a create request and returns data to save for future logins
322
     * @param string $clientDataJSON binary from browser
323
     * @param string $attestationObject binary from browser
324
     * @param string|ByteBuffer $challenge binary used challange
325
     * @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
326
     * @param bool $requireUserPresent false, if the device must NOT check user presence (e.g. by pressing a button)
327
     * @param bool $failIfRootMismatch false, if there should be no error thrown if root certificate doesn't match
328
     * @param bool $requireCtsProfileMatch false, if you don't want to check if the device is approved as a Google-certified Android device.
329
     * @return \stdClass
330
     * @throws WebAuthnException
331
     */
332
    public function processCreate($clientDataJSON, $attestationObject, $challenge, $requireUserVerification=false, $requireUserPresent=true, $failIfRootMismatch=true, $requireCtsProfileMatch=true) {
333
        $clientDataHash = \hash('sha256', $clientDataJSON, true);
334
        $clientData = \json_decode($clientDataJSON);
335
        $challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
336
 
337
        // security: https://www.w3.org/TR/webauthn/#registering-a-new-credential
338
 
339
        // 2. Let C, the client data claimed as collected during the credential creation,
340
        //    be the result of running an implementation-specific JSON parser on JSONtext.
341
        if (!\is_object($clientData)) {
342
            throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
343
        }
344
 
345
        // 3. Verify that the value of C.type is webauthn.create.
346
        if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.create') {
347
            throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
348
        }
349
 
350
        // 4. Verify that the value of C.challenge matches the challenge that was sent to the authenticator in the create() call.
351
        if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
352
            throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
353
        }
354
 
355
        // 5. Verify that the value of C.origin matches the Relying Party's origin.
356
        if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
357
            throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
358
        }
359
 
360
        // Attestation
361
        $attestationObject = new Attestation\AttestationObject($attestationObject, $this->_formats);
362
 
363
        // 9. Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
364
        if (!$attestationObject->validateRpIdHash($this->_rpIdHash)) {
365
            throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
366
        }
367
 
368
        // 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature
369
        if (!$attestationObject->validateAttestation($clientDataHash)) {
370
            throw new WebAuthnException('invalid certificate signature', WebAuthnException::INVALID_SIGNATURE);
371
        }
372
 
373
        // Android-SafetyNet: if required, check for Compatibility Testing Suite (CTS).
374
        if ($requireCtsProfileMatch && $attestationObject->getAttestationFormat() instanceof Attestation\Format\AndroidSafetyNet) {
375
            if (!$attestationObject->getAttestationFormat()->ctsProfileMatch()) {
376
                 throw new WebAuthnException('invalid ctsProfileMatch: device is not approved as a Google-certified Android device.', WebAuthnException::ANDROID_NOT_TRUSTED);
377
            }
378
        }
379
 
380
        // 15. If validation is successful, obtain a list of acceptable trust anchors
381
        $rootValid = is_array($this->_caFiles) ? $attestationObject->validateRootCertificate($this->_caFiles) : null;
382
        if ($failIfRootMismatch && is_array($this->_caFiles) && !$rootValid) {
383
            throw new WebAuthnException('invalid root certificate', WebAuthnException::CERTIFICATE_NOT_TRUSTED);
384
        }
385
 
386
        // 10. Verify that the User Present bit of the flags in authData is set.
387
        $userPresent = $attestationObject->getAuthenticatorData()->getUserPresent();
388
        if ($requireUserPresent && !$userPresent) {
389
            throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
390
        }
391
 
392
        // 11. If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
393
        $userVerified = $attestationObject->getAuthenticatorData()->getUserVerified();
394
        if ($requireUserVerification && !$userVerified) {
395
            throw new WebAuthnException('user not verified during authentication', WebAuthnException::USER_VERIFICATED);
396
        }
397
 
398
        $signCount = $attestationObject->getAuthenticatorData()->getSignCount();
399
        if ($signCount > 0) {
400
            $this->_signatureCounter = $signCount;
401
        }
402
 
403
        // prepare data to store for future logins
404
        $data = new \stdClass();
405
        $data->rpId = $this->_rpId;
406
        $data->attestationFormat = $attestationObject->getAttestationFormatName();
407
        $data->credentialId = $attestationObject->getAuthenticatorData()->getCredentialId();
408
        $data->credentialPublicKey = $attestationObject->getAuthenticatorData()->getPublicKeyPem();
409
        $data->certificateChain = $attestationObject->getCertificateChain();
410
        $data->certificate = $attestationObject->getCertificatePem();
411
        $data->certificateIssuer = $attestationObject->getCertificateIssuer();
412
        $data->certificateSubject = $attestationObject->getCertificateSubject();
413
        $data->signatureCounter = $this->_signatureCounter;
414
        $data->AAGUID = $attestationObject->getAuthenticatorData()->getAAGUID();
415
        $data->rootValid = $rootValid;
416
        $data->userPresent = $userPresent;
417
        $data->userVerified = $userVerified;
1441 ariadna 418
    	$data->isBackupEligible = $attestationObject->getAuthenticatorData()->getIsBackupEligible();
419
        $data->isBackedUp = $attestationObject->getAuthenticatorData()->getIsBackup();
1 efrain 420
        return $data;
421
    }
422
 
423
 
424
    /**
425
     * process a get request
426
     * @param string $clientDataJSON binary from browser
427
     * @param string $authenticatorData binary from browser
428
     * @param string $signature binary from browser
429
     * @param string $credentialPublicKey string PEM-formated public key from used credentialId
430
     * @param string|ByteBuffer $challenge  binary from used challange
431
     * @param int $prevSignatureCnt signature count value of the last login
432
     * @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
433
     * @param bool $requireUserPresent true, if the device must check user presence (e.g. by pressing a button)
434
     * @return boolean true if get is successful
435
     * @throws WebAuthnException
436
     */
437
    public function processGet($clientDataJSON, $authenticatorData, $signature, $credentialPublicKey, $challenge, $prevSignatureCnt=null, $requireUserVerification=false, $requireUserPresent=true) {
438
        $authenticatorObj = new Attestation\AuthenticatorData($authenticatorData);
439
        $clientDataHash = \hash('sha256', $clientDataJSON, true);
440
        $clientData = \json_decode($clientDataJSON);
441
        $challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
442
 
443
        // https://www.w3.org/TR/webauthn/#verifying-assertion
444
 
445
        // 1. If the allowCredentials option was given when this authentication ceremony was initiated,
446
        //    verify that credential.id identifies one of the public key credentials that were listed in allowCredentials.
447
        //    -> TO BE VERIFIED BY IMPLEMENTATION
448
 
449
        // 2. If credential.response.userHandle is present, verify that the user identified
450
        //    by this value is the owner of the public key credential identified by credential.id.
451
        //    -> TO BE VERIFIED BY IMPLEMENTATION
452
 
453
        // 3. Using credential’s id attribute (or the corresponding rawId, if base64url encoding is
454
        //    inappropriate for your use case), look up the corresponding credential public key.
455
        //    -> TO BE LOOKED UP BY IMPLEMENTATION
456
 
457
        // 5. Let JSONtext be the result of running UTF-8 decode on the value of cData.
458
        if (!\is_object($clientData)) {
459
            throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
460
        }
461
 
462
        // 7. Verify that the value of C.type is the string webauthn.get.
463
        if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.get') {
464
            throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
465
        }
466
 
467
        // 8. Verify that the value of C.challenge matches the challenge that was sent to the
468
        //    authenticator in the PublicKeyCredentialRequestOptions passed to the get() call.
469
        if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
470
            throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
471
        }
472
 
473
        // 9. Verify that the value of C.origin matches the Relying Party's origin.
474
        if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
475
            throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
476
        }
477
 
478
        // 11. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party.
479
        if ($authenticatorObj->getRpIdHash() !== $this->_rpIdHash) {
480
            throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
481
        }
482
 
483
        // 12. Verify that the User Present bit of the flags in authData is set
484
        if ($requireUserPresent && !$authenticatorObj->getUserPresent()) {
485
            throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
486
        }
487
 
488
        // 13. If user verification is required for this assertion, verify that the User Verified bit of the flags in authData is set.
489
        if ($requireUserVerification && !$authenticatorObj->getUserVerified()) {
490
            throw new WebAuthnException('user not verificated during authentication', WebAuthnException::USER_VERIFICATED);
491
        }
492
 
493
        // 14. Verify the values of the client extension outputs
494
        //     (extensions not implemented)
495
 
496
        // 16. Using the credential public key looked up in step 3, verify that sig is a valid signature
497
        //     over the binary concatenation of authData and hash.
498
        $dataToVerify = '';
499
        $dataToVerify .= $authenticatorData;
500
        $dataToVerify .= $clientDataHash;
501
 
502
        if (!$this->_verifySignature($dataToVerify, $signature, $credentialPublicKey)) {
503
            throw new WebAuthnException('invalid signature', WebAuthnException::INVALID_SIGNATURE);
504
        }
505
 
506
        $signatureCounter = $authenticatorObj->getSignCount();
507
        if ($signatureCounter !== 0) {
508
            $this->_signatureCounter = $signatureCounter;
509
        }
510
 
511
        // 17. If either of the signature counter value authData.signCount or
512
        //     previous signature count is nonzero, and if authData.signCount
513
        //     less than or equal to previous signature count, it's a signal
514
        //     that the authenticator may be cloned
515
        if ($prevSignatureCnt !== null) {
516
            if ($signatureCounter !== 0 || $prevSignatureCnt !== 0) {
517
                if ($prevSignatureCnt >= $signatureCounter) {
518
                    throw new WebAuthnException('signature counter not valid', WebAuthnException::SIGNATURE_COUNTER);
519
                }
520
            }
521
        }
522
 
523
        return true;
524
    }
525
 
526
    /**
527
     * Downloads root certificates from FIDO Alliance Metadata Service (MDS) to a specific folder
528
     * https://fidoalliance.org/metadata/
529
     * @param string $certFolder Folder path to save the certificates in PEM format.
530
     * @param bool $deleteCerts delete certificates in the target folder before adding the new ones.
531
     * @return int number of cetificates
532
     * @throws WebAuthnException
533
     */
534
    public function queryFidoMetaDataService($certFolder, $deleteCerts=true) {
535
        $url = 'https://mds.fidoalliance.org/';
536
        $raw = null;
537
        if (\function_exists('curl_init')) {
538
            $ch = \curl_init($url);
539
            \curl_setopt($ch, CURLOPT_HEADER, false);
540
            \curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
541
            \curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
542
            \curl_setopt($ch, CURLOPT_USERAGENT, 'github.com/lbuchs/WebAuthn - A simple PHP WebAuthn server library');
543
            $raw = \curl_exec($ch);
544
            \curl_close($ch);
545
        } else {
546
            $raw = \file_get_contents($url);
547
        }
548
 
549
        $certFolder = \rtrim(\realpath($certFolder), '\\/');
550
        if (!is_dir($certFolder)) {
551
            throw new WebAuthnException('Invalid folder path for query FIDO Alliance Metadata Service');
552
        }
553
 
554
        if (!\is_string($raw)) {
555
            throw new WebAuthnException('Unable to query FIDO Alliance Metadata Service');
556
        }
557
 
558
        $jwt = \explode('.', $raw);
559
        if (\count($jwt) !== 3) {
560
            throw new WebAuthnException('Invalid JWT from FIDO Alliance Metadata Service');
561
        }
562
 
563
        if ($deleteCerts) {
564
            foreach (\scandir($certFolder) as $ca) {
565
                if (\substr($ca, -4) === '.pem') {
566
                    if (\unlink($certFolder . DIRECTORY_SEPARATOR . $ca) === false) {
567
                        throw new WebAuthnException('Cannot delete certs in folder for FIDO Alliance Metadata Service');
568
                    }
569
                }
570
            }
571
        }
572
 
573
        list($header, $payload, $hash) = $jwt;
574
        $payload = Binary\ByteBuffer::fromBase64Url($payload)->getJson();
575
 
576
        $count = 0;
577
        if (\is_object($payload) && \property_exists($payload, 'entries') && \is_array($payload->entries)) {
578
            foreach ($payload->entries as $entry) {
579
                if (\is_object($entry) && \property_exists($entry, 'metadataStatement') && \is_object($entry->metadataStatement)) {
580
                    $description = $entry->metadataStatement->description ?? null;
581
                    $attestationRootCertificates = $entry->metadataStatement->attestationRootCertificates ?? null;
582
 
583
                    if ($description && $attestationRootCertificates) {
584
 
585
                        // create filename
586
                        $certFilename = \preg_replace('/[^a-z0-9]/i', '_', $description);
587
                        $certFilename = \trim(\preg_replace('/\_{2,}/i', '_', $certFilename),'_') . '.pem';
588
                        $certFilename = \strtolower($certFilename);
589
 
590
                        // add certificate
591
                        $certContent = $description . "\n";
592
                        $certContent .= \str_repeat('-', \mb_strlen($description)) . "\n";
593
 
594
                        foreach ($attestationRootCertificates as $attestationRootCertificate) {
595
                            $attestationRootCertificate = \str_replace(["\n", "\r", ' '], '', \trim($attestationRootCertificate));
596
                            $count++;
597
                            $certContent .= "\n-----BEGIN CERTIFICATE-----\n";
598
                            $certContent .= \chunk_split($attestationRootCertificate, 64, "\n");
599
                            $certContent .= "-----END CERTIFICATE-----\n";
600
                        }
601
 
602
                        if (\file_put_contents($certFolder . DIRECTORY_SEPARATOR . $certFilename, $certContent) === false) {
603
                            throw new WebAuthnException('unable to save certificate from FIDO Alliance Metadata Service');
604
                        }
605
                    }
606
                }
607
            }
608
        }
609
 
610
        return $count;
611
    }
612
 
613
    // -----------------------------------------------
614
    // PRIVATE
615
    // -----------------------------------------------
616
 
617
    /**
618
     * checks if the origin matchs the RP ID
619
     * @param string $origin
620
     * @return boolean
621
     * @throws WebAuthnException
622
     */
623
    private function _checkOrigin($origin) {
1441 ariadna 624
        if (str_starts_with($origin, 'android:apk-key-hash:')) {
625
            return $this->_checkAndroidKeyHashes($origin);
626
        }
627
 
1 efrain 628
        // https://www.w3.org/TR/webauthn/#rp-id
629
 
630
        // The origin's scheme must be https
631
        if ($this->_rpId !== 'localhost' && \parse_url($origin, PHP_URL_SCHEME) !== 'https') {
632
            return false;
633
        }
634
 
635
        // extract host from origin
636
        $host = \parse_url($origin, PHP_URL_HOST);
637
        $host = \trim($host, '.');
638
 
639
        // The RP ID must be equal to the origin's effective domain, or a registrable
640
        // domain suffix of the origin's effective domain.
641
        return \preg_match('/' . \preg_quote($this->_rpId) . '$/i', $host) === 1;
642
    }
643
 
644
    /**
1441 ariadna 645
     * checks if the origin value contains a known android key hash
646
     * @param string $origin
647
     * @return boolean
648
     */
649
    private function _checkAndroidKeyHashes($origin) {
650
        $parts = explode('android:apk-key-hash:', $origin);
651
        if (count($parts) !== 2) {
652
            return false;
653
        }
654
        return in_array($parts[1], $this->_androidKeyHashes, true);
655
    }
656
 
657
    /**
1 efrain 658
     * generates a new challange
659
     * @param int $length
660
     * @return string
661
     * @throws WebAuthnException
662
     */
663
    private function _createChallenge($length = 32) {
664
        if (!$this->_challenge) {
665
            $this->_challenge = ByteBuffer::randomBuffer($length);
666
        }
667
        return $this->_challenge;
668
    }
669
 
670
    /**
671
     * check if the signature is valid.
672
     * @param string $dataToVerify
673
     * @param string $signature
674
     * @param string $credentialPublicKey PEM format
675
     * @return bool
676
     */
677
    private function _verifySignature($dataToVerify, $signature, $credentialPublicKey) {
678
 
679
        // Use Sodium to verify EdDSA 25519 as its not yet supported by openssl
680
        if (\function_exists('sodium_crypto_sign_verify_detached') && !\in_array('ed25519', \openssl_get_curve_names(), true)) {
681
            $pkParts = [];
682
            if (\preg_match('/BEGIN PUBLIC KEY\-+(?:\s|\n|\r)+([^\-]+)(?:\s|\n|\r)*\-+END PUBLIC KEY/i', $credentialPublicKey, $pkParts)) {
683
                $rawPk = \base64_decode($pkParts[1]);
684
 
685
                // 30        = der sequence
686
                // 2a        = length 42 byte
687
                // 30        = der sequence
688
                // 05        = lenght 5 byte
689
                // 06        = der OID
690
                // 03        = OID length 3 byte
691
                // 2b 65 70  = OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
692
                // 03        = der bit string
693
                // 21        = length 33 byte
694
                // 00        = null padding
695
                // [...]     = 32 byte x-curve
696
                $okpPrefix = "\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00";
697
 
698
                if ($rawPk && \strlen($rawPk) === 44 && \substr($rawPk,0, \strlen($okpPrefix)) === $okpPrefix) {
699
                    $publicKeyXCurve = \substr($rawPk, \strlen($okpPrefix));
700
 
701
                    return \sodium_crypto_sign_verify_detached($signature, $dataToVerify, $publicKeyXCurve);
702
                }
703
            }
704
        }
705
 
706
        // verify with openSSL
707
        $publicKey = \openssl_pkey_get_public($credentialPublicKey);
708
        if ($publicKey === false) {
709
            throw new WebAuthnException('public key invalid', WebAuthnException::INVALID_PUBLIC_KEY);
710
        }
711
 
712
        return \openssl_verify($dataToVerify, $signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
713
    }
714
}