WebAuthn.php 22 KB

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