WebAuthn.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. <?php
  2. namespace WebAuthn;
  3. use 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. */
  65. public function addRootCertificates($path) {
  66. if (!\is_array($this->_caFiles)) {
  67. $this->_caFiles = array();
  68. }
  69. $path = \rtrim(\trim($path), '\\/');
  70. if (\is_dir($path)) {
  71. foreach (\scandir($path) as $ca) {
  72. if (\is_file($path . '/' . $ca)) {
  73. $this->addRootCertificates($path . '/' . $ca);
  74. }
  75. }
  76. } else if (\is_file($path) && !\in_array(\realpath($path), $this->_caFiles)) {
  77. $this->_caFiles[] = \realpath($path);
  78. }
  79. }
  80. /**
  81. * Returns the generated challenge to save for later validation
  82. * @return ByteBuffer
  83. */
  84. public function getChallenge() {
  85. return $this->_challenge;
  86. }
  87. /**
  88. * generates the object for a key registration
  89. * provide this data to navigator.credentials.create
  90. * @param string $userId
  91. * @param string $userName
  92. * @param string $userDisplayName
  93. * @param int $timeout timeout in seconds
  94. * @param bool $requireResidentKey true, if the key should be stored by the authentication device
  95. * @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
  96. * if the response does not have the UV flag set.
  97. * Valid values:
  98. * true = required
  99. * false = preferred
  100. * string 'required' 'preferred' 'discouraged'
  101. * @param bool|null $crossPlatformAttachment true for cross-platform devices (eg. fido usb),
  102. * false for platform devices (eg. windows hello, android safetynet),
  103. * null for both
  104. * @param array $excludeCredentialIds a array of ids, which are already registered, to prevent re-registration
  105. * @return \stdClass
  106. */
  107. public function getCreateArgs($userId, $userName, $userDisplayName, $timeout=20, $requireResidentKey=false, $requireUserVerification=false, $crossPlatformAttachment=null, $excludeCredentialIds=array()) {
  108. // validate User Verification Requirement
  109. if (\is_bool($requireUserVerification)) {
  110. $requireUserVerification = $requireUserVerification ? 'required' : 'preferred';
  111. } else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
  112. $requireUserVerification = \strtolower($requireUserVerification);
  113. } else {
  114. $requireUserVerification = 'preferred';
  115. }
  116. $args = new \stdClass();
  117. $args->publicKey = new \stdClass();
  118. // relying party
  119. $args->publicKey->rp = new \stdClass();
  120. $args->publicKey->rp->name = $this->_rpName;
  121. $args->publicKey->rp->id = $this->_rpId;
  122. $args->publicKey->authenticatorSelection = new \stdClass();
  123. $args->publicKey->authenticatorSelection->userVerification = $requireUserVerification;
  124. if ($requireResidentKey) {
  125. $args->publicKey->authenticatorSelection->requireResidentKey = true;
  126. }
  127. if (is_bool($crossPlatformAttachment)) {
  128. $args->publicKey->authenticatorSelection->authenticatorAttachment = $crossPlatformAttachment ? 'cross-platform' : 'platform';
  129. }
  130. // user
  131. $args->publicKey->user = new \stdClass();
  132. $args->publicKey->user->id = new ByteBuffer($userId); // binary
  133. $args->publicKey->user->name = $userName;
  134. $args->publicKey->user->displayName = $userDisplayName;
  135. $args->publicKey->pubKeyCredParams = array();
  136. $tmp = new \stdClass();
  137. $tmp->type = 'public-key';
  138. $tmp->alg = -7; // ES256
  139. $args->publicKey->pubKeyCredParams[] = $tmp;
  140. unset ($tmp);
  141. $tmp = new \stdClass();
  142. $tmp->type = 'public-key';
  143. $tmp->alg = -257; // RS256
  144. $args->publicKey->pubKeyCredParams[] = $tmp;
  145. unset ($tmp);
  146. // if there are root certificates added, we need direct attestation to validate
  147. // against the root certificate. If there are no root-certificates added,
  148. // anonymization ca are also accepted, because we can't validate the root anyway.
  149. $attestation = 'indirect';
  150. if (\is_array($this->_caFiles)) {
  151. $attestation = 'direct';
  152. }
  153. $args->publicKey->attestation = \count($this->_formats) === 1 && \in_array('none', $this->_formats) ? 'none' : $attestation;
  154. $args->publicKey->extensions = new \stdClass();
  155. $args->publicKey->extensions->exts = true;
  156. $args->publicKey->timeout = $timeout * 1000; // microseconds
  157. $args->publicKey->challenge = $this->_createChallenge(); // binary
  158. //prevent re-registration by specifying existing credentials
  159. $args->publicKey->excludeCredentials = array();
  160. if (is_array($excludeCredentialIds)) {
  161. foreach ($excludeCredentialIds as $id) {
  162. $tmp = new \stdClass();
  163. $tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id); // binary
  164. $tmp->type = 'public-key';
  165. $tmp->transports = array('usb', 'ble', 'nfc', 'internal');
  166. $args->publicKey->excludeCredentials[] = $tmp;
  167. unset ($tmp);
  168. }
  169. }
  170. return $args;
  171. }
  172. /**
  173. * generates the object for key validation
  174. * Provide this data to navigator.credentials.get
  175. * @param array $credentialIds binary
  176. * @param int $timeout timeout in seconds
  177. * @param bool $allowUsb allow removable USB
  178. * @param bool $allowNfc allow Near Field Communication (NFC)
  179. * @param bool $allowBle allow Bluetooth
  180. * @param bool $allowInternal allow client device-specific transport. These authenticators are not removable from the client device.
  181. * @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
  182. * if the response does not have the UV flag set.
  183. * Valid values:
  184. * true = required
  185. * false = preferred
  186. * string 'required' 'preferred' 'discouraged'
  187. * @return \stdClass
  188. */
  189. public function getGetArgs($credentialIds=array(), $timeout=20, $allowUsb=true, $allowNfc=true, $allowBle=true, $allowInternal=true, $requireUserVerification=false) {
  190. // validate User Verification Requirement
  191. if (\is_bool($requireUserVerification)) {
  192. $requireUserVerification = $requireUserVerification ? 'required' : 'preferred';
  193. } else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
  194. $requireUserVerification = \strtolower($requireUserVerification);
  195. } else {
  196. $requireUserVerification = 'preferred';
  197. }
  198. $args = new \stdClass();
  199. $args->publicKey = new \stdClass();
  200. $args->publicKey->timeout = $timeout * 1000; // microseconds
  201. $args->publicKey->challenge = $this->_createChallenge(); // binary
  202. $args->publicKey->userVerification = $requireUserVerification;
  203. $args->publicKey->rpId = $this->_rpId;
  204. if (\is_array($credentialIds) && \count($credentialIds) > 0) {
  205. $args->publicKey->allowCredentials = array();
  206. foreach ($credentialIds as $id) {
  207. $tmp = new \stdClass();
  208. $tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id); // binary
  209. $tmp->transports = array();
  210. if ($allowUsb) {
  211. $tmp->transports[] = 'usb';
  212. }
  213. if ($allowNfc) {
  214. $tmp->transports[] = 'nfc';
  215. }
  216. if ($allowBle) {
  217. $tmp->transports[] = 'ble';
  218. }
  219. if ($allowInternal) {
  220. $tmp->transports[] = 'internal';
  221. }
  222. $tmp->type = 'public-key';
  223. $args->publicKey->allowCredentials[] = $tmp;
  224. unset ($tmp);
  225. }
  226. }
  227. return $args;
  228. }
  229. /**
  230. * returns the new signature counter value.
  231. * returns null if there is no counter
  232. * @return ?int
  233. */
  234. public function getSignatureCounter() {
  235. return \is_int($this->_signatureCounter) ? $this->_signatureCounter : null;
  236. }
  237. /**
  238. * process a create request and returns data to save for future logins
  239. * @param string $clientDataJSON binary from browser
  240. * @param string $attestationObject binary from browser
  241. * @param string|ByteBuffer $challenge binary used challange
  242. * @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
  243. * @param bool $requireUserPresent false, if the device must NOT check user presence (e.g. by pressing a button)
  244. * @return \stdClass
  245. * @throws WebAuthnException
  246. */
  247. public function processCreate($clientDataJSON, $attestationObject, $challenge, $requireUserVerification=false, $requireUserPresent=true) {
  248. $clientDataHash = \hash('sha256', $clientDataJSON, true);
  249. $clientData = \json_decode($clientDataJSON);
  250. $challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
  251. // security: https://www.w3.org/TR/webauthn/#registering-a-new-credential
  252. // 2. Let C, the client data claimed as collected during the credential creation,
  253. // be the result of running an implementation-specific JSON parser on JSONtext.
  254. if (!\is_object($clientData)) {
  255. throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
  256. }
  257. // 3. Verify that the value of C.type is webauthn.create.
  258. if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.create') {
  259. throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
  260. }
  261. // 4. Verify that the value of C.challenge matches the challenge that was sent to the authenticator in the create() call.
  262. if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
  263. throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
  264. }
  265. // 5. Verify that the value of C.origin matches the Relying Party's origin.
  266. if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
  267. throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
  268. }
  269. // Attestation
  270. $attestationObject = new Attestation\AttestationObject($attestationObject, $this->_formats);
  271. // 9. Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
  272. if (!$attestationObject->validateRpIdHash($this->_rpIdHash)) {
  273. throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
  274. }
  275. // 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature
  276. if (!$attestationObject->validateAttestation($clientDataHash)) {
  277. throw new WebAuthnException('invalid certificate signature', WebAuthnException::INVALID_SIGNATURE);
  278. }
  279. // 15. If validation is successful, obtain a list of acceptable trust anchors
  280. if (is_array($this->_caFiles) && !$attestationObject->validateRootCertificate($this->_caFiles)) {
  281. throw new WebAuthnException('invalid root certificate', WebAuthnException::CERTIFICATE_NOT_TRUSTED);
  282. }
  283. // 10. Verify that the User Present bit of the flags in authData is set.
  284. if ($requireUserPresent && !$attestationObject->getAuthenticatorData()->getUserPresent()) {
  285. throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
  286. }
  287. // 11. If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
  288. if ($requireUserVerification && !$attestationObject->getAuthenticatorData()->getUserVerified()) {
  289. throw new WebAuthnException('user not verificated during authentication', WebAuthnException::USER_VERIFICATED);
  290. }
  291. $signCount = $attestationObject->getAuthenticatorData()->getSignCount();
  292. if ($signCount > 0) {
  293. $this->_signatureCounter = $signCount;
  294. }
  295. // prepare data to store for future logins
  296. $data = new \stdClass();
  297. $data->rpId = $this->_rpId;
  298. $data->credentialId = $attestationObject->getAuthenticatorData()->getCredentialId();
  299. $data->credentialPublicKey = $attestationObject->getAuthenticatorData()->getPublicKeyPem();
  300. $data->certificateChain = $attestationObject->getCertificateChain();
  301. $data->certificate = $attestationObject->getCertificatePem();
  302. $data->certificateIssuer = $attestationObject->getCertificateIssuer();
  303. $data->certificateSubject = $attestationObject->getCertificateSubject();
  304. $data->signatureCounter = $this->_signatureCounter;
  305. $data->AAGUID = $attestationObject->getAuthenticatorData()->getAAGUID();
  306. return $data;
  307. }
  308. /**
  309. * process a get request
  310. * @param string $clientDataJSON binary from browser
  311. * @param string $authenticatorData binary from browser
  312. * @param string $signature binary from browser
  313. * @param string $credentialPublicKey string PEM-formated public key from used credentialId
  314. * @param string|ByteBuffer $challenge binary from used challange
  315. * @param int $prevSignatureCnt signature count value of the last login
  316. * @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
  317. * @param bool $requireUserPresent true, if the device must check user presence (e.g. by pressing a button)
  318. * @return boolean true if get is successful
  319. * @throws WebAuthnException
  320. */
  321. public function processGet($clientDataJSON, $authenticatorData, $signature, $credentialPublicKey, $challenge, $prevSignatureCnt=null, $requireUserVerification=false, $requireUserPresent=true) {
  322. $authenticatorObj = new Attestation\AuthenticatorData($authenticatorData);
  323. $clientDataHash = \hash('sha256', $clientDataJSON, true);
  324. $clientData = \json_decode($clientDataJSON);
  325. $challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
  326. // https://www.w3.org/TR/webauthn/#verifying-assertion
  327. // 1. If the allowCredentials option was given when this authentication ceremony was initiated,
  328. // verify that credential.id identifies one of the public key credentials that were listed in allowCredentials.
  329. // -> TO BE VERIFIED BY IMPLEMENTATION
  330. // 2. If credential.response.userHandle is present, verify that the user identified
  331. // by this value is the owner of the public key credential identified by credential.id.
  332. // -> TO BE VERIFIED BY IMPLEMENTATION
  333. // 3. Using credential’s id attribute (or the corresponding rawId, if base64url encoding is
  334. // inappropriate for your use case), look up the corresponding credential public key.
  335. // -> TO BE LOOKED UP BY IMPLEMENTATION
  336. // 5. Let JSONtext be the result of running UTF-8 decode on the value of cData.
  337. if (!\is_object($clientData)) {
  338. throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
  339. }
  340. // 7. Verify that the value of C.type is the string webauthn.get.
  341. if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.get') {
  342. throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
  343. }
  344. // 8. Verify that the value of C.challenge matches the challenge that was sent to the
  345. // authenticator in the PublicKeyCredentialRequestOptions passed to the get() call.
  346. if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
  347. throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
  348. }
  349. // 9. Verify that the value of C.origin matches the Relying Party's origin.
  350. if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
  351. throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
  352. }
  353. // 11. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party.
  354. if ($authenticatorObj->getRpIdHash() !== $this->_rpIdHash) {
  355. throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
  356. }
  357. // 12. Verify that the User Present bit of the flags in authData is set
  358. if ($requireUserPresent && !$authenticatorObj->getUserPresent()) {
  359. throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
  360. }
  361. // 13. If user verification is required for this assertion, verify that the User Verified bit of the flags in authData is set.
  362. if ($requireUserVerification && !$authenticatorObj->getUserVerified()) {
  363. throw new WebAuthnException('user not verificated during authentication', WebAuthnException::USER_VERIFICATED);
  364. }
  365. // 14. Verify the values of the client extension outputs
  366. // (extensions not implemented)
  367. // 16. Using the credential public key looked up in step 3, verify that sig is a valid signature
  368. // over the binary concatenation of authData and hash.
  369. $dataToVerify = '';
  370. $dataToVerify .= $authenticatorData;
  371. $dataToVerify .= $clientDataHash;
  372. $publicKey = \openssl_pkey_get_public($credentialPublicKey);
  373. if ($publicKey === false) {
  374. throw new WebAuthnException('public key invalid', WebAuthnException::INVALID_PUBLIC_KEY);
  375. }
  376. if (\openssl_verify($dataToVerify, $signature, $publicKey, OPENSSL_ALGO_SHA256) !== 1) {
  377. throw new WebAuthnException('invalid signature', WebAuthnException::INVALID_SIGNATURE);
  378. }
  379. // 17. If the signature counter value authData.signCount is nonzero,
  380. // if less than or equal to the signature counter value stored,
  381. // is a signal that the authenticator may be cloned
  382. $signatureCounter = $authenticatorObj->getSignCount();
  383. if ($signatureCounter > 0) {
  384. $this->_signatureCounter = $signatureCounter;
  385. if ($prevSignatureCnt !== null && $prevSignatureCnt >= $signatureCounter) {
  386. throw new WebAuthnException('signature counter not valid', WebAuthnException::SIGNATURE_COUNTER);
  387. }
  388. }
  389. return true;
  390. }
  391. // -----------------------------------------------
  392. // PRIVATE
  393. // -----------------------------------------------
  394. /**
  395. * checks if the origin matchs the RP ID
  396. * @param string $origin
  397. * @return boolean
  398. * @throws WebAuthnException
  399. */
  400. private function _checkOrigin($origin) {
  401. // https://www.w3.org/TR/webauthn/#rp-id
  402. // The origin's scheme must be https
  403. if ($this->_rpId !== 'localhost' && \parse_url($origin, PHP_URL_SCHEME) !== 'https') {
  404. return false;
  405. }
  406. // extract host from origin
  407. $host = \parse_url($origin, PHP_URL_HOST);
  408. $host = \trim($host, '.');
  409. // The RP ID must be equal to the origin's effective domain, or a registrable
  410. // domain suffix of the origin's effective domain.
  411. return \preg_match('/' . \preg_quote($this->_rpId) . '$/i', $host) === 1;
  412. }
  413. /**
  414. * generates a new challange
  415. * @param int $length
  416. * @return string
  417. * @throws WebAuthnException
  418. */
  419. private function _createChallenge($length = 32) {
  420. if (!$this->_challenge) {
  421. $this->_challenge = ByteBuffer::randomBuffer($length);
  422. }
  423. return $this->_challenge;
  424. }
  425. }