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