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