WebAuthn.php 28 KB

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