mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 00:59:03 +00:00
Passkeys: bundle report-uri/passkeys-php 2.0.1 in libs/webauthn in place of lbuchs/WebAuthn 2.2.0, Report URI's maintained fork with the fixes from their penetration test - only attestation none is accepted, cross-origin requests and Token Binding are refused, the backup flags and credential id length are checked and the RP ID is matched on a dot boundary; functions/passkey.php uses the new namespace, constructor and processCreate arguments, and the 26.12.3 changelog names the library
This commit is contained in:
@@ -19,7 +19,7 @@ Update from Maintenance > Update as usual - this release has one database change
|
||||
### Developer Updates
|
||||
|
||||
- Database 4.2.2: user_passkeys (each passkey's credential id and the SHA-256 of it to find it by, its public key, signature count, AAGUID, transports, whether it is synced, and for an agent a copy of the vault key sealed by the passkey's PRF output - AES-256-GCM under HKDF-SHA256, bound to the credential), users.user_passkey_handle (the random WebAuthn user handle) and settings.config_login_passkeys.
|
||||
- WebAuthn is checked by lbuchs/WebAuthn 2.2.0 (MIT) in libs/webauthn, with user verification required and attestation none; the origin is also matched exactly against config_base_url, as the library only checks the end of the host name. functions/passkey.php holds the challenges (session, five minutes, single use), registration, the sign-in check and the vault copy.
|
||||
- WebAuthn is checked by report-uri/passkeys-php 2.0.1 (MIT) in libs/webauthn - Report URI's maintained fork of lbuchs/WebAuthn 2.2.0, whose upstream is dormant, with the fixes from their penetration test: only attestation none (the other attestation formats' code is gone), cross-origin requests and Token Binding refused, the backup flags and the credential id's length checked, and the RP ID matched on a dot boundary. User verification is required, and the origin is still matched exactly against config_base_url, scheme and port included. functions/passkey.php holds the challenges (session, five minutes, single use), registration, the sign-in check and the vault copy.
|
||||
- Signing in: login_passkey.php answers the options and checks the browser's answer (JSON), then login.php's passkey_login step signs them in through its usual success path - the same as after a two-step code, session regeneration and new-device email included. js/passkey.js draws the button, offers passkeys in the email box (conditional mediation, never retried in a loop) and runs the add forms.
|
||||
- A locked vault: vaultLocked() and vaultUnlock(), with get_credential_via_id and get_totp_token_via_id in agent/ajax.php answering {locked}, and js/credentials.js opening the Unlock window (includes/footer.php). New calls: passkey_create_options and vault_unlock in agent/ajax.php; add_your_passkey and delete_your_passkey for agents; passkey_create_options, portal_passkey_add and portal_passkey_remove in client/post.php. The password checks for adding a passkey and unlocking are limited to five wrong ones in ten minutes per account (Password Failed).
|
||||
- $_SESSION['signed_in_with'] ('passkey' or 'password') lets includes/load_user_session.php and client/includes/check_login.php leave MFA enforcement out for a passkey sign-in.
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* face (user verification is required, every time).
|
||||
*
|
||||
* The sign-in itself (login_passkey.php): the browser signs a challenge kept in the session, the
|
||||
* signature is checked against the passkey's public key here (lbuchs/WebAuthn, libs/webauthn),
|
||||
* signature is checked against the passkey's public key here (report-uri/passkeys-php, libs/webauthn),
|
||||
* and login.php then signs them in through its usual path, as it does after a two-step code.
|
||||
*
|
||||
* The vault: an agent's copy of the vault key is sealed by their password, which a passkey sign-in
|
||||
@@ -87,7 +87,7 @@ function passkeyRp() {
|
||||
|
||||
function passkeyWebAuthn() {
|
||||
$rp = passkeyRp();
|
||||
return new \lbuchs\WebAuthn\WebAuthn($rp['name'], $rp['id'], null, true);
|
||||
return new \ReportUri\Passkeys\WebAuthn($rp['name'], $rp['id'], true);
|
||||
}
|
||||
|
||||
/** The salt the PRF extension is asked to sign - the same for every passkey here; the secret it gives is each passkey's own. */
|
||||
@@ -270,7 +270,7 @@ function passkeyRegister($user_id, $name, array $post, $master = null) {
|
||||
return [false, 'Passkeys are added at ' . passkeyRp()['address'] . ' - open ITFlow there and add it again.'];
|
||||
}
|
||||
try {
|
||||
$made = passkeyWebAuthn()->processCreate($client_data, $attestation, $challenge, true, true, false, false);
|
||||
$made = passkeyWebAuthn()->processCreate($client_data, $attestation, $challenge, true, true);
|
||||
} catch (\Throwable $e) {
|
||||
return [false, 'That passkey could not be checked (' . $e->getMessage() . ') - add it again.'];
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ MIT License
|
||||
|
||||
Copyright © 2022 Lukas Buchs
|
||||
Copyright © 2018 Thomas Bleeker (CBOR & ByteBuffer part)
|
||||
Copyright © 2026 Report-URI Ltd. (fork modifications)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
22
libs/webauthn/NOTICE.md
Normal file
22
libs/webauthn/NOTICE.md
Normal file
@@ -0,0 +1,22 @@
|
||||
# NOTICE
|
||||
|
||||
This project (`report-uri/passkeys-php`) is a fork of [lbuchs/WebAuthn](https://github.com/lbuchs/WebAuthn) by [Lukas Buchs](https://github.com/lbuchs), branched at upstream tag `v2.2.0`.
|
||||
|
||||
The original library is © Lukas Buchs, licensed under the [MIT License](LICENSE). All of the original source code remains under that license; the additions and modifications in this fork are also released under the MIT License.
|
||||
|
||||
## Changes vs upstream v2.2.0
|
||||
|
||||
- Package renamed: `lbuchs/webauthn` → `report-uri/passkeys-php`
|
||||
- Namespace renamed: `lbuchs\WebAuthn` → `ReportUri\Passkeys`
|
||||
- Five security fixes applied — see [README.md](README.md#security-improvements-vs-lbuchswebauthn-v220) and the commit history on `main`.
|
||||
|
||||
The upstream class names (`WebAuthn`, `WebAuthnException`) are preserved.
|
||||
|
||||
## Upstream
|
||||
|
||||
* Source: https://github.com/lbuchs/WebAuthn
|
||||
* Demo: https://webauthn.lubu.ch
|
||||
|
||||
Bug reports and feature requests for this fork should be filed at:
|
||||
|
||||
* https://github.com/report-uri/passkeys-php/issues
|
||||
@@ -1,23 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\CBOR\CborDecoder;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
namespace ReportUri\Passkeys\Attestation;
|
||||
use ReportUri\Passkeys\WebAuthnException;
|
||||
use ReportUri\Passkeys\CBOR\CborDecoder;
|
||||
use ReportUri\Passkeys\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
* @license https://github.com/report-uri/passkeys-php/blob/master/LICENSE MIT
|
||||
*/
|
||||
class AttestationObject {
|
||||
private $_authenticatorData;
|
||||
private $_attestationFormat;
|
||||
private $_attestationFormatName;
|
||||
|
||||
public function __construct($binary , $allowedFormats) {
|
||||
public function __construct($binary) {
|
||||
$enc = CborDecoder::decode($binary);
|
||||
// validation
|
||||
if (!\is_array($enc) || !\array_key_exists('fmt', $enc) || !is_string($enc['fmt'])) {
|
||||
|
||||
if (!\is_array($enc) || !\array_key_exists('fmt', $enc) || !\is_string($enc['fmt'])) {
|
||||
throw new WebAuthnException('invalid attestation format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
@@ -29,148 +27,31 @@ class AttestationObject {
|
||||
throw new WebAuthnException('invalid attestation format (authData not available)', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Only the "none" attestation format is supported. The RP always
|
||||
// requests attestation: 'none' in getCreateArgs(), and a spec-compliant
|
||||
// client must deliver fmt: 'none' with an empty attStmt regardless of
|
||||
// which authenticator the user holds (WebAuthn §5.4.7, §8.7).
|
||||
if ($enc['fmt'] !== 'none') {
|
||||
throw new WebAuthnException('invalid attestation format: ' . $enc['fmt'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (\count($enc['attStmt']) !== 0) {
|
||||
throw new WebAuthnException('invalid none attestation: attStmt must be empty', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_authenticatorData = new AuthenticatorData($enc['authData']->getBinaryString());
|
||||
$this->_attestationFormatName = $enc['fmt'];
|
||||
|
||||
// Format ok?
|
||||
if (!in_array($this->_attestationFormatName, $allowedFormats)) {
|
||||
throw new WebAuthnException('invalid atttestation format: ' . $this->_attestationFormatName, WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
|
||||
switch ($this->_attestationFormatName) {
|
||||
case 'android-key': $this->_attestationFormat = new Format\AndroidKey($enc, $this->_authenticatorData); break;
|
||||
case 'android-safetynet': $this->_attestationFormat = new Format\AndroidSafetyNet($enc, $this->_authenticatorData); break;
|
||||
case 'apple': $this->_attestationFormat = new Format\Apple($enc, $this->_authenticatorData); break;
|
||||
case 'fido-u2f': $this->_attestationFormat = new Format\U2f($enc, $this->_authenticatorData); break;
|
||||
case 'none': $this->_attestationFormat = new Format\None($enc, $this->_authenticatorData); break;
|
||||
case 'packed': $this->_attestationFormat = new Format\Packed($enc, $this->_authenticatorData); break;
|
||||
case 'tpm': $this->_attestationFormat = new Format\Tpm($enc, $this->_authenticatorData); break;
|
||||
default: throw new WebAuthnException('invalid attestation format: ' . $enc['fmt'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation format name
|
||||
* @return string
|
||||
*/
|
||||
public function getAttestationFormatName() {
|
||||
return $this->_attestationFormatName;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation format class
|
||||
* @return Format\FormatBase
|
||||
*/
|
||||
public function getAttestationFormat() {
|
||||
return $this->_attestationFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation public key in PEM format
|
||||
* @return AuthenticatorData
|
||||
*/
|
||||
public function getAuthenticatorData() {
|
||||
return $this->_authenticatorData;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the certificate chain as PEM
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificateChain() {
|
||||
return $this->_attestationFormat->getCertificateChain();
|
||||
}
|
||||
|
||||
/**
|
||||
* return the certificate issuer as string
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificateIssuer() {
|
||||
$pem = $this->getCertificatePem();
|
||||
$issuer = '';
|
||||
if ($pem) {
|
||||
$certInfo = \openssl_x509_parse($pem);
|
||||
if (\is_array($certInfo) && \array_key_exists('issuer', $certInfo) && \is_array($certInfo['issuer'])) {
|
||||
|
||||
$cn = $certInfo['issuer']['CN'] ?? '';
|
||||
$o = $certInfo['issuer']['O'] ?? '';
|
||||
$ou = $certInfo['issuer']['OU'] ?? '';
|
||||
|
||||
if ($cn) {
|
||||
$issuer .= $cn;
|
||||
}
|
||||
if ($issuer && ($o || $ou)) {
|
||||
$issuer .= ' (' . trim($o . ' ' . $ou) . ')';
|
||||
} else {
|
||||
$issuer .= trim($o . ' ' . $ou);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* return the certificate subject as string
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificateSubject() {
|
||||
$pem = $this->getCertificatePem();
|
||||
$subject = '';
|
||||
if ($pem) {
|
||||
$certInfo = \openssl_x509_parse($pem);
|
||||
if (\is_array($certInfo) && \array_key_exists('subject', $certInfo) && \is_array($certInfo['subject'])) {
|
||||
|
||||
$cn = $certInfo['subject']['CN'] ?? '';
|
||||
$o = $certInfo['subject']['O'] ?? '';
|
||||
$ou = $certInfo['subject']['OU'] ?? '';
|
||||
|
||||
if ($cn) {
|
||||
$subject .= $cn;
|
||||
}
|
||||
if ($subject && ($o || $ou)) {
|
||||
$subject .= ' (' . trim($o . ' ' . $ou) . ')';
|
||||
} else {
|
||||
$subject .= trim($o . ' ' . $ou);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_attestationFormat->getCertificatePem();
|
||||
}
|
||||
|
||||
/**
|
||||
* checks validity of the signature
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_attestationFormat->validateAttestation($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
return $this->_attestationFormat->validateRootCertificate($rootCas);
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if the RpId-Hash is valid
|
||||
* @param string$rpIdHash
|
||||
* @param string $rpIdHash
|
||||
* @return bool
|
||||
*/
|
||||
public function validateRpIdHash($rpIdHash) {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\CBOR\CborDecoder;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
namespace ReportUri\Passkeys\Attestation;
|
||||
use ReportUri\Passkeys\WebAuthnException;
|
||||
use ReportUri\Passkeys\CBOR\CborDecoder;
|
||||
use ReportUri\Passkeys\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
* @license https://github.com/report-uri/passkeys-php/blob/master/LICENSE MIT
|
||||
*/
|
||||
class AuthenticatorData {
|
||||
protected $_binary;
|
||||
@@ -125,7 +125,7 @@ class AuthenticatorData {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
|
||||
$der = null;
|
||||
switch ($this->_attestedCredentialData->credentialPublicKey->kty ?? null) {
|
||||
case self::$_EC2_TYPE: $der = $this->_getEc2Der(); break;
|
||||
@@ -281,6 +281,12 @@ class AuthenticatorData {
|
||||
$flags->isBackup = $flags->bit_4;
|
||||
$flags->attestedDataIncluded = $flags->bit_6;
|
||||
$flags->extensionDataIncluded = $flags->bit_7;
|
||||
|
||||
// Backup State (BS) requires Backup Eligible (BE) per spec.
|
||||
if ($flags->isBackup && !$flags->isBackupEligible) {
|
||||
throw new WebAuthnException('invalid backup flags: BS without BE', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
return $flags;
|
||||
}
|
||||
|
||||
@@ -302,6 +308,17 @@ class AuthenticatorData {
|
||||
|
||||
//Byte length L of Credential ID, 16-bit unsigned big-endian integer.
|
||||
$length = \unpack('nlength', \substr($binary, 53, 2))['length'];
|
||||
|
||||
// W3C WebAuthn Level 3 §5.8.3: credential ID length MUST be in [16, 1023]
|
||||
if ($length < 16 || $length > 1023) {
|
||||
throw new WebAuthnException('Invalid credential ID length', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Guard against declared length exceeding the available binary
|
||||
if (55 + $length > \strlen($binary)) {
|
||||
throw new WebAuthnException('Credential ID length exceeds attested data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$attestedCData->credentialId = \substr($binary, 55, $length);
|
||||
|
||||
// set end offset
|
||||
@@ -345,6 +362,10 @@ class AuthenticatorData {
|
||||
*/
|
||||
private function _readCredentialPublicKeyEDDSA(&$credPKey, $enc) {
|
||||
$credPKey->crv = $enc[self::$_COSE_CRV];
|
||||
|
||||
if (!isset($enc[self::$_COSE_X])) {
|
||||
throw new WebAuthnException('public key missing', WebAuthnException::MISSING_PUBLIC_KEY);
|
||||
}
|
||||
$credPKey->x = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class AndroidKey extends FormatBase {
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check u2f data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('x5c', $attStmt) || !\is_array($attStmt['x5c']) || \count($attStmt['x5c']) < 1) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\is_object($attStmt['x5c'][0]) || !($attStmt['x5c'][0] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_x5c = $attStmt['x5c'][0]->getBinaryString();
|
||||
|
||||
if (count($attStmt['x5c']) > 1) {
|
||||
for ($i=1; $i<count($attStmt['x5c']); $i++) {
|
||||
$this->_x5c_chain[] = $attStmt['x5c'][$i]->getBinaryString();
|
||||
}
|
||||
unset ($i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the attestation public key in attestnCert with the algorithm specified in alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class AndroidSafetyNet extends FormatBase {
|
||||
private $_signature;
|
||||
private $_signedValue;
|
||||
private $_x5c;
|
||||
private $_payload;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('ver', $attStmt) || !$attStmt['ver']) {
|
||||
throw new WebAuthnException('invalid Android Safety Net Format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('response', $attStmt) || !($attStmt['response'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid Android Safety Net Format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$response = $attStmt['response']->getBinaryString();
|
||||
|
||||
// Response is a JWS [RFC7515] object in Compact Serialization.
|
||||
// JWSs have three segments separated by two period ('.') characters
|
||||
$parts = \explode('.', $response);
|
||||
unset ($response);
|
||||
if (\count($parts) !== 3) {
|
||||
throw new WebAuthnException('invalid JWS data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$header = $this->_base64url_decode($parts[0]);
|
||||
$payload = $this->_base64url_decode($parts[1]);
|
||||
$this->_signature = $this->_base64url_decode($parts[2]);
|
||||
$this->_signedValue = $parts[0] . '.' . $parts[1];
|
||||
unset ($parts);
|
||||
|
||||
$header = \json_decode($header);
|
||||
$payload = \json_decode($payload);
|
||||
|
||||
if (!($header instanceof \stdClass)) {
|
||||
throw new WebAuthnException('invalid JWS header', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
if (!($payload instanceof \stdClass)) {
|
||||
throw new WebAuthnException('invalid JWS payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!isset($header->x5c) || !is_array($header->x5c) || count($header->x5c) === 0) {
|
||||
throw new WebAuthnException('No X.509 signature in JWS Header', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// algorithm
|
||||
if (!\in_array($header->alg, array('RS256', 'ES256'))) {
|
||||
throw new WebAuthnException('invalid JWS algorithm ' . $header->alg, WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = \base64_decode($header->x5c[0]);
|
||||
$this->_payload = $payload;
|
||||
|
||||
if (count($header->x5c) > 1) {
|
||||
for ($i=1; $i<count($header->x5c); $i++) {
|
||||
$this->_x5c_chain[] = \base64_decode($header->x5c[$i]);
|
||||
}
|
||||
unset ($i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ctsProfileMatch: A stricter verdict of device integrity.
|
||||
* If the value of ctsProfileMatch is true, then the profile of the device running your app matches
|
||||
* the profile of a device that has passed Android compatibility testing and
|
||||
* has been approved as a Google-certified Android device.
|
||||
* @return bool
|
||||
*/
|
||||
public function ctsProfileMatch() {
|
||||
return isset($this->_payload->ctsProfileMatch) ? !!$this->_payload->ctsProfileMatch : false;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
// Verify that the nonce in the response is identical to the Base64 encoding
|
||||
// of the SHA-256 hash of the concatenation of authenticatorData and clientDataHash.
|
||||
if (empty($this->_payload->nonce) || $this->_payload->nonce !== \base64_encode(\hash('SHA256', $this->_authenticatorData->getBinary() . $clientDataHash, true))) {
|
||||
throw new WebAuthnException('invalid nonce in JWS payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that attestationCert is issued to the hostname "attest.android.com"
|
||||
$certInfo = \openssl_x509_parse($this->getCertificatePem());
|
||||
if (!\is_array($certInfo) || ($certInfo['subject']['CN'] ?? '') !== 'attest.android.com') {
|
||||
throw new WebAuthnException('invalid certificate CN in JWS (' . ($certInfo['subject']['CN'] ?? '-'). ')', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that the basicIntegrity attribute in the payload of response is true.
|
||||
if (empty($this->_payload->basicIntegrity)) {
|
||||
throw new WebAuthnException('invalid basicIntegrity in payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($this->_signedValue, $this->_signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* decode base64 url
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
private function _base64url_decode($data) {
|
||||
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Apple extends FormatBase {
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new WebAuthnException('invalid Apple attestation statement: missing x5c', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Concatenate authenticatorData and clientDataHash to form nonceToHash.
|
||||
$nonceToHash = $this->_authenticatorData->getBinary();
|
||||
$nonceToHash .= $clientDataHash;
|
||||
|
||||
// Perform SHA-256 hash of nonceToHash to produce nonce
|
||||
$nonce = hash('SHA256', $nonceToHash, true);
|
||||
|
||||
$credCert = openssl_x509_read($this->getCertificatePem());
|
||||
if ($credCert === false) {
|
||||
throw new WebAuthnException('invalid x5c certificate: ' . \openssl_error_string(), WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$keyData = openssl_pkey_get_details(openssl_pkey_get_public($credCert));
|
||||
$key = is_array($keyData) && array_key_exists('key', $keyData) ? $keyData['key'] : null;
|
||||
|
||||
|
||||
// Verify that nonce equals the value of the extension with OID ( 1.2.840.113635.100.8.2 ) in credCert.
|
||||
$parsedCredCert = openssl_x509_parse($credCert);
|
||||
$nonceExtension = $parsedCredCert['extensions']['1.2.840.113635.100.8.2'] ?? '';
|
||||
|
||||
// nonce padded by ASN.1 string: 30 24 A1 22 04 20
|
||||
// 30 — type tag indicating sequence
|
||||
// 24 — 36 byte following
|
||||
// A1 — Enumerated [1]
|
||||
// 22 — 34 byte following
|
||||
// 04 — type tag indicating octet string
|
||||
// 20 — 32 byte following
|
||||
|
||||
$asn1Padding = "\x30\x24\xA1\x22\x04\x20";
|
||||
if (substr($nonceExtension, 0, strlen($asn1Padding)) === $asn1Padding) {
|
||||
$nonceExtension = substr($nonceExtension, strlen($asn1Padding));
|
||||
}
|
||||
|
||||
if ($nonceExtension !== $nonce) {
|
||||
throw new WebAuthnException('nonce doesn\'t equal the value of the extension with OID 1.2.840.113635.100.8.2', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that the credential public key equals the Subject Public Key of credCert.
|
||||
$authKeyData = openssl_pkey_get_details(openssl_pkey_get_public($this->_authenticatorData->getPublicKeyPem()));
|
||||
$authKey = is_array($authKeyData) && array_key_exists('key', $authKeyData) ? $authKeyData['key'] : null;
|
||||
|
||||
if ($key === null || $key !== $authKey) {
|
||||
throw new WebAuthnException('credential public key doesn\'t equal the Subject Public Key of credCert', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
|
||||
|
||||
abstract class FormatBase {
|
||||
protected $_attestationObject = null;
|
||||
protected $_authenticatorData = null;
|
||||
protected $_x5c_chain = array();
|
||||
protected $_x5c_tempFile = null;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Array $AttestionObject
|
||||
* @param AuthenticatorData $authenticatorData
|
||||
*/
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
$this->_attestationObject = $AttestionObject;
|
||||
$this->_authenticatorData = $authenticatorData;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __destruct() {
|
||||
// delete X.509 chain certificate file after use
|
||||
if ($this->_x5c_tempFile && \is_file($this->_x5c_tempFile)) {
|
||||
\unlink($this->_x5c_tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the certificate chain in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificateChain() {
|
||||
if ($this->_x5c_tempFile && \is_file($this->_x5c_tempFile)) {
|
||||
return \file_get_contents($this->_x5c_tempFile);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the key X.509 certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
// need to be overwritten
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* checks validity of the signature
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
// need to be overwritten
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
// need to be overwritten
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* create a PEM encoded certificate with X.509 binary data
|
||||
* @param string $x5c
|
||||
* @return string
|
||||
*/
|
||||
protected function _createCertificatePem($x5c) {
|
||||
$pem = '-----BEGIN CERTIFICATE-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($x5c), 64, "\n");
|
||||
$pem .= '-----END CERTIFICATE-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* creates a PEM encoded chain file
|
||||
* @return string|null
|
||||
*/
|
||||
protected function _createX5cChainFile() {
|
||||
$content = '';
|
||||
if (\is_array($this->_x5c_chain) && \count($this->_x5c_chain) > 0) {
|
||||
foreach ($this->_x5c_chain as $x5c) {
|
||||
$certInfo = \openssl_x509_parse($this->_createCertificatePem($x5c));
|
||||
|
||||
// check if certificate is self signed
|
||||
if (\is_array($certInfo) && \is_array($certInfo['issuer']) && \is_array($certInfo['subject'])) {
|
||||
$selfSigned = false;
|
||||
|
||||
$subjectKeyIdentifier = $certInfo['extensions']['subjectKeyIdentifier'] ?? null;
|
||||
$authorityKeyIdentifier = $certInfo['extensions']['authorityKeyIdentifier'] ?? null;
|
||||
|
||||
if ($authorityKeyIdentifier && substr($authorityKeyIdentifier, 0, 6) === 'keyid:') {
|
||||
$authorityKeyIdentifier = substr($authorityKeyIdentifier, 6);
|
||||
}
|
||||
if ($subjectKeyIdentifier && substr($subjectKeyIdentifier, 0, 6) === 'keyid:') {
|
||||
$subjectKeyIdentifier = substr($subjectKeyIdentifier, 6);
|
||||
}
|
||||
|
||||
if (($subjectKeyIdentifier && !$authorityKeyIdentifier) || ($authorityKeyIdentifier && $authorityKeyIdentifier === $subjectKeyIdentifier)) {
|
||||
$selfSigned = true;
|
||||
}
|
||||
|
||||
if (!$selfSigned) {
|
||||
$content .= "\n" . $this->_createCertificatePem($x5c) . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($content) {
|
||||
$this->_x5c_tempFile = \tempnam(\sys_get_temp_dir(), 'x5c_');
|
||||
if (\file_put_contents($this->_x5c_tempFile, $content) !== false) {
|
||||
return $this->_x5c_tempFile;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns the name and openssl key for provided cose number.
|
||||
* @param int $coseNumber
|
||||
* @return \stdClass|null
|
||||
*/
|
||||
protected function _getCoseAlgorithm($coseNumber) {
|
||||
// https://www.iana.org/assignments/cose/cose.xhtml#algorithms
|
||||
$coseAlgorithms = array(
|
||||
array(
|
||||
'hash' => 'SHA1',
|
||||
'openssl' => OPENSSL_ALGO_SHA1,
|
||||
'cose' => array(
|
||||
-65535 // RS1
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA256',
|
||||
'openssl' => OPENSSL_ALGO_SHA256,
|
||||
'cose' => array(
|
||||
-257, // RS256
|
||||
-37, // PS256
|
||||
-7, // ES256
|
||||
5 // HMAC256
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA384',
|
||||
'openssl' => OPENSSL_ALGO_SHA384,
|
||||
'cose' => array(
|
||||
-258, // RS384
|
||||
-38, // PS384
|
||||
-35, // ES384
|
||||
6 // HMAC384
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA512',
|
||||
'openssl' => OPENSSL_ALGO_SHA512,
|
||||
'cose' => array(
|
||||
-259, // RS512
|
||||
-39, // PS512
|
||||
-36, // ES512
|
||||
7 // HMAC512
|
||||
))
|
||||
);
|
||||
|
||||
foreach ($coseAlgorithms as $coseAlgorithm) {
|
||||
if (\in_array($coseNumber, $coseAlgorithm['cose'], true)) {
|
||||
$return = new \stdClass();
|
||||
$return->hash = $coseAlgorithm['hash'];
|
||||
$return->openssl = $coseAlgorithm['openssl'];
|
||||
return $return;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
|
||||
class None extends FormatBase {
|
||||
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates.
|
||||
* Format 'none' does not contain any ca, so always false.
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Packed extends FormatBase {
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
if (!$this->_x5c) {
|
||||
return null;
|
||||
}
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
if ($this->_x5c) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
} else {
|
||||
return $this->_validateSelfAttestation($clientDataHash);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
if (!$this->_x5c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the attestation public key in attestnCert with the algorithm specified in alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if self attestation is in use
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
*/
|
||||
protected function _validateSelfAttestation($clientDataHash) {
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the credential public key with alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$publicKey = $this->_authenticatorData->getPublicKeyPem();
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Tpm extends FormatBase {
|
||||
private $_TPM_GENERATED_VALUE = "\xFF\x54\x43\x47";
|
||||
private $_TPM_ST_ATTEST_CERTIFY = "\x80\x17";
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_pubArea;
|
||||
private $_x5c;
|
||||
|
||||
/**
|
||||
* @var ByteBuffer
|
||||
*/
|
||||
private $_certInfo;
|
||||
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('ver', $attStmt) || $attStmt['ver'] !== '2.0') {
|
||||
throw new WebAuthnException('invalid tpm version: ' . $attStmt['ver'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('signature not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('certInfo', $attStmt) || !\is_object($attStmt['certInfo']) || !($attStmt['certInfo'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('certInfo not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('pubArea', $attStmt) || !\is_object($attStmt['pubArea']) || !($attStmt['pubArea'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('pubArea not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_certInfo = $attStmt['certInfo'];
|
||||
$this->_pubArea = $attStmt['pubArea'];
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new WebAuthnException('no x5c certificate found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
if (!$this->_x5c) {
|
||||
return null;
|
||||
}
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
if (!$this->_x5c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Concatenate authenticatorData and clientDataHash to form attToBeSigned.
|
||||
$attToBeSigned = $this->_authenticatorData->getBinary();
|
||||
$attToBeSigned .= $clientDataHash;
|
||||
|
||||
// Validate that certInfo is valid:
|
||||
|
||||
// Verify that magic is set to TPM_GENERATED_VALUE.
|
||||
if ($this->_certInfo->getBytes(0, 4) !== $this->_TPM_GENERATED_VALUE) {
|
||||
throw new WebAuthnException('tpm magic not TPM_GENERATED_VALUE', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that type is set to TPM_ST_ATTEST_CERTIFY.
|
||||
if ($this->_certInfo->getBytes(4, 2) !== $this->_TPM_ST_ATTEST_CERTIFY) {
|
||||
throw new WebAuthnException('tpm type not TPM_ST_ATTEST_CERTIFY', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$offset = 6;
|
||||
$qualifiedSigner = $this->_tpmReadLengthPrefixed($this->_certInfo, $offset);
|
||||
$extraData = $this->_tpmReadLengthPrefixed($this->_certInfo, $offset);
|
||||
$coseAlg = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// Verify that extraData is set to the hash of attToBeSigned using the hash algorithm employed in "alg".
|
||||
if ($extraData->getBinaryString() !== \hash($coseAlg->hash, $attToBeSigned, true)) {
|
||||
throw new WebAuthnException('certInfo:extraData not hash of attToBeSigned', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify the sig is a valid signature over certInfo using the attestation
|
||||
// public key in aikCert with the algorithm specified in alg.
|
||||
return \openssl_verify($this->_certInfo->getBinaryString(), $this->_signature, $publicKey, $coseAlg->openssl) === 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns next part of ByteBuffer
|
||||
* @param ByteBuffer $buffer
|
||||
* @param int $offset
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
protected function _tpmReadLengthPrefixed(ByteBuffer $buffer, &$offset) {
|
||||
$len = $buffer->getUint16Val($offset);
|
||||
$data = $buffer->getBytes($offset + 2, $len);
|
||||
$offset += (2 + $len);
|
||||
|
||||
return new ByteBuffer($data);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class U2f extends FormatBase {
|
||||
private $_alg = -7;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check u2f data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (\array_key_exists('alg', $attStmt) && $attStmt['alg'] !== $this->_alg) {
|
||||
throw new WebAuthnException('u2f only accepts algorithm -7 ("ES256"), but got ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('x5c', $attStmt) || !\is_array($attStmt['x5c']) || \count($attStmt['x5c']) !== 1) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\is_object($attStmt['x5c'][0]) || !($attStmt['x5c'][0] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_x5c = $attStmt['x5c'][0]->getBinaryString();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
$pem = '-----BEGIN CERTIFICATE-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($this->_x5c), 64, "\n");
|
||||
$pem .= '-----END CERTIFICATE-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Let verificationData be the concatenation of (0x00 || rpIdHash || clientDataHash || credentialId || publicKeyU2F)
|
||||
$dataToVerify = "\x00";
|
||||
$dataToVerify .= $this->_authenticatorData->getRpIdHash();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
$dataToVerify .= $this->_authenticatorData->getCredentialId();
|
||||
$dataToVerify .= $this->_authenticatorData->getPublicKeyU2F();
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Binary;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
namespace ReportUri\Passkeys\Binary;
|
||||
use ReportUri\Passkeys\WebAuthnException;
|
||||
|
||||
/**
|
||||
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/ByteBuffer.php
|
||||
@@ -196,7 +196,7 @@ class ByteBuffer implements \JsonSerializable, \Serializable {
|
||||
} else if (is_string($buffer)) {
|
||||
return $buffer === $this->getBinaryString();
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\CBOR;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
namespace ReportUri\Passkeys\CBOR;
|
||||
use ReportUri\Passkeys\WebAuthnException;
|
||||
use ReportUri\Passkeys\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/CborDecoder.php
|
||||
|
||||
@@ -1,25 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
namespace ReportUri\Passkeys;
|
||||
use ReportUri\Passkeys\Binary\ByteBuffer;
|
||||
require_once 'WebAuthnException.php';
|
||||
require_once 'Binary/ByteBuffer.php';
|
||||
require_once 'Attestation/AttestationObject.php';
|
||||
require_once 'Attestation/AuthenticatorData.php';
|
||||
require_once 'Attestation/Format/FormatBase.php';
|
||||
require_once 'Attestation/Format/None.php';
|
||||
require_once 'Attestation/Format/AndroidKey.php';
|
||||
require_once 'Attestation/Format/AndroidSafetyNet.php';
|
||||
require_once 'Attestation/Format/Apple.php';
|
||||
require_once 'Attestation/Format/Packed.php';
|
||||
require_once 'Attestation/Format/Tpm.php';
|
||||
require_once 'Attestation/Format/U2f.php';
|
||||
require_once 'CBOR/CborDecoder.php';
|
||||
|
||||
/**
|
||||
* WebAuthn
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
* @license https://github.com/report-uri/passkeys-php/blob/master/LICENSE MIT
|
||||
*/
|
||||
class WebAuthn {
|
||||
// relying party
|
||||
@@ -28,9 +20,6 @@ class WebAuthn {
|
||||
private $_rpIdHash;
|
||||
private $_challenge;
|
||||
private $_signatureCounter;
|
||||
private $_caFiles;
|
||||
private $_formats;
|
||||
private $_androidKeyHashes;
|
||||
|
||||
/**
|
||||
* Initialize a new WebAuthn server
|
||||
@@ -39,12 +28,11 @@ class WebAuthn {
|
||||
* @param bool $useBase64UrlEncoding true to use base64 url encoding for binary data in json objects. Default is a RFC 1342-Like serialized string.
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function __construct($rpName, $rpId, $allowedFormats=null, $useBase64UrlEncoding=false) {
|
||||
public function __construct($rpName, $rpId, $useBase64UrlEncoding=false) {
|
||||
$this->_rpName = $rpName;
|
||||
$this->_rpId = $rpId;
|
||||
$this->_rpIdHash = \hash('sha256', $rpId, true);
|
||||
ByteBuffer::$useBase64UrlEncoding = !!$useBase64UrlEncoding;
|
||||
$supportedFormats = array('android-key', 'android-safetynet', 'apple', 'fido-u2f', 'none', 'packed', 'tpm');
|
||||
|
||||
if (!\function_exists('\openssl_open')) {
|
||||
throw new WebAuthnException('OpenSSL-Module not installed');
|
||||
@@ -53,59 +41,6 @@ class WebAuthn {
|
||||
if (!\in_array('SHA256', \array_map('\strtoupper', \openssl_get_md_methods()))) {
|
||||
throw new WebAuthnException('SHA256 not supported by this openssl installation.');
|
||||
}
|
||||
|
||||
// default: all format
|
||||
if (!is_array($allowedFormats)) {
|
||||
$allowedFormats = $supportedFormats;
|
||||
}
|
||||
$this->_formats = $allowedFormats;
|
||||
|
||||
// validate formats
|
||||
$invalidFormats = \array_diff($this->_formats, $supportedFormats);
|
||||
if (!$this->_formats || $invalidFormats) {
|
||||
throw new WebAuthnException('invalid formats on construct: ' . implode(', ', $invalidFormats));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* add a root certificate to verify new registrations
|
||||
* @param string $path file path of / directory with root certificates
|
||||
* @param array|null $certFileExtensions if adding a direction, all files with provided extension are added. default: pem, crt, cer, der
|
||||
*/
|
||||
public function addRootCertificates($path, $certFileExtensions=null) {
|
||||
if (!\is_array($this->_caFiles)) {
|
||||
$this->_caFiles = [];
|
||||
}
|
||||
if ($certFileExtensions === null) {
|
||||
$certFileExtensions = array('pem', 'crt', 'cer', 'der');
|
||||
}
|
||||
$path = \rtrim(\trim($path), '\\/');
|
||||
if (\is_dir($path)) {
|
||||
foreach (\scandir($path) as $ca) {
|
||||
if (\is_file($path . DIRECTORY_SEPARATOR . $ca) && \in_array(\strtolower(\pathinfo($ca, PATHINFO_EXTENSION)), $certFileExtensions)) {
|
||||
$this->addRootCertificates($path . DIRECTORY_SEPARATOR . $ca);
|
||||
}
|
||||
}
|
||||
} else if (\is_file($path) && !\in_array(\realpath($path), $this->_caFiles)) {
|
||||
$this->_caFiles[] = \realpath($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* add key hashes for android verification
|
||||
* @param array<string> $hashes
|
||||
* @return void
|
||||
*/
|
||||
public function addAndroidKeyHashes($hashes) {
|
||||
if (!\is_array($this->_androidKeyHashes)) {
|
||||
$this->_androidKeyHashes = [];
|
||||
}
|
||||
|
||||
foreach ($hashes as $hash) {
|
||||
if (is_string($hash)) {
|
||||
$this->_androidKeyHashes[] = $hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -186,7 +121,7 @@ class WebAuthn {
|
||||
// supported algorithms
|
||||
$args->publicKey->pubKeyCredParams = [];
|
||||
|
||||
if (function_exists('sodium_crypto_sign_verify_detached') || \in_array('ed25519', \openssl_get_curve_names(), true)) {
|
||||
if (function_exists('sodium_crypto_sign_verify_detached') || defined('OPENSSL_KEYTYPE_ED25519')) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -8; // EdDSA
|
||||
@@ -208,15 +143,7 @@ class WebAuthn {
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
|
||||
// if there are root certificates added, we need direct attestation to validate
|
||||
// against the root certificate. If there are no root-certificates added,
|
||||
// anonymization ca are also accepted, because we can't validate the root anyway.
|
||||
$attestation = 'indirect';
|
||||
if (\is_array($this->_caFiles)) {
|
||||
$attestation = 'direct';
|
||||
}
|
||||
|
||||
$args->publicKey->attestation = \count($this->_formats) === 1 && \in_array('none', $this->_formats) ? 'none' : $attestation;
|
||||
$args->publicKey->attestation = 'none';
|
||||
$args->publicKey->extensions = new \stdClass();
|
||||
$args->publicKey->extensions->exts = true;
|
||||
$args->publicKey->timeout = $timeout * 1000; // microseconds
|
||||
@@ -324,12 +251,10 @@ class WebAuthn {
|
||||
* @param string|ByteBuffer $challenge binary used challange
|
||||
* @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
|
||||
* @param bool $requireUserPresent false, if the device must NOT check user presence (e.g. by pressing a button)
|
||||
* @param bool $failIfRootMismatch false, if there should be no error thrown if root certificate doesn't match
|
||||
* @param bool $requireCtsProfileMatch false, if you don't want to check if the device is approved as a Google-certified Android device.
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function processCreate($clientDataJSON, $attestationObject, $challenge, $requireUserVerification=false, $requireUserPresent=true, $failIfRootMismatch=true, $requireCtsProfileMatch=true) {
|
||||
public function processCreate($clientDataJSON, $attestationObject, $challenge, $requireUserVerification=false, $requireUserPresent=true) {
|
||||
$clientDataHash = \hash('sha256', $clientDataJSON, true);
|
||||
$clientData = \json_decode($clientDataJSON);
|
||||
$challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
|
||||
@@ -357,32 +282,27 @@ class WebAuthn {
|
||||
throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// Attestation
|
||||
$attestationObject = new Attestation\AttestationObject($attestationObject, $this->_formats);
|
||||
// Reject cross-origin requests (proposed Level 3 spec §7.1 Step 10).
|
||||
if (\property_exists($clientData, 'crossOrigin') && $clientData->crossOrigin === true) {
|
||||
throw new WebAuthnException('cross-origin request not allowed', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// 6. Verify tokenBinding status matches the TLS connection. We do not
|
||||
// support Token Binding, so reject status "present" (Level 2 §7.1 Step 6).
|
||||
if (\property_exists($clientData, 'tokenBinding') && \is_object($clientData->tokenBinding) && \property_exists($clientData->tokenBinding, 'status') && $clientData->tokenBinding->status === 'present') {
|
||||
throw new WebAuthnException('token binding not supported', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Attestation. The RP requested attestation: 'none', so a compliant
|
||||
// client must deliver fmt: 'none' with an empty attStmt — both
|
||||
// invariants are enforced by AttestationObject's constructor.
|
||||
$attestationObject = new Attestation\AttestationObject($attestationObject);
|
||||
|
||||
// 9. Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
|
||||
if (!$attestationObject->validateRpIdHash($this->_rpIdHash)) {
|
||||
throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
|
||||
}
|
||||
|
||||
// 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature
|
||||
if (!$attestationObject->validateAttestation($clientDataHash)) {
|
||||
throw new WebAuthnException('invalid certificate signature', WebAuthnException::INVALID_SIGNATURE);
|
||||
}
|
||||
|
||||
// Android-SafetyNet: if required, check for Compatibility Testing Suite (CTS).
|
||||
if ($requireCtsProfileMatch && $attestationObject->getAttestationFormat() instanceof Attestation\Format\AndroidSafetyNet) {
|
||||
if (!$attestationObject->getAttestationFormat()->ctsProfileMatch()) {
|
||||
throw new WebAuthnException('invalid ctsProfileMatch: device is not approved as a Google-certified Android device.', WebAuthnException::ANDROID_NOT_TRUSTED);
|
||||
}
|
||||
}
|
||||
|
||||
// 15. If validation is successful, obtain a list of acceptable trust anchors
|
||||
$rootValid = is_array($this->_caFiles) ? $attestationObject->validateRootCertificate($this->_caFiles) : null;
|
||||
if ($failIfRootMismatch && is_array($this->_caFiles) && !$rootValid) {
|
||||
throw new WebAuthnException('invalid root certificate', WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
|
||||
// 10. Verify that the User Present bit of the flags in authData is set.
|
||||
$userPresent = $attestationObject->getAuthenticatorData()->getUserPresent();
|
||||
if ($requireUserPresent && !$userPresent) {
|
||||
@@ -403,19 +323,13 @@ class WebAuthn {
|
||||
// prepare data to store for future logins
|
||||
$data = new \stdClass();
|
||||
$data->rpId = $this->_rpId;
|
||||
$data->attestationFormat = $attestationObject->getAttestationFormatName();
|
||||
$data->credentialId = $attestationObject->getAuthenticatorData()->getCredentialId();
|
||||
$data->credentialPublicKey = $attestationObject->getAuthenticatorData()->getPublicKeyPem();
|
||||
$data->certificateChain = $attestationObject->getCertificateChain();
|
||||
$data->certificate = $attestationObject->getCertificatePem();
|
||||
$data->certificateIssuer = $attestationObject->getCertificateIssuer();
|
||||
$data->certificateSubject = $attestationObject->getCertificateSubject();
|
||||
$data->signatureCounter = $this->_signatureCounter;
|
||||
$data->AAGUID = $attestationObject->getAuthenticatorData()->getAAGUID();
|
||||
$data->rootValid = $rootValid;
|
||||
$data->userPresent = $userPresent;
|
||||
$data->userVerified = $userVerified;
|
||||
$data->isBackupEligible = $attestationObject->getAuthenticatorData()->getIsBackupEligible();
|
||||
$data->isBackupEligible = $attestationObject->getAuthenticatorData()->getIsBackupEligible();
|
||||
$data->isBackedUp = $attestationObject->getAuthenticatorData()->getIsBackup();
|
||||
return $data;
|
||||
}
|
||||
@@ -475,6 +389,17 @@ class WebAuthn {
|
||||
throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// Reject cross-origin requests (proposed Level 3 spec §7.2 Step 13).
|
||||
if (\property_exists($clientData, 'crossOrigin') && $clientData->crossOrigin === true) {
|
||||
throw new WebAuthnException('cross-origin request not allowed', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// 10. Verify tokenBinding status matches the TLS connection. We do not
|
||||
// support Token Binding, so reject status "present" (Level 2 §7.2 Step 10).
|
||||
if (\property_exists($clientData, 'tokenBinding') && \is_object($clientData->tokenBinding) && \property_exists($clientData->tokenBinding, 'status') && $clientData->tokenBinding->status === 'present') {
|
||||
throw new WebAuthnException('token binding not supported', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// 11. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party.
|
||||
if ($authenticatorObj->getRpIdHash() !== $this->_rpIdHash) {
|
||||
throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
|
||||
@@ -523,93 +448,6 @@ class WebAuthn {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads root certificates from FIDO Alliance Metadata Service (MDS) to a specific folder
|
||||
* https://fidoalliance.org/metadata/
|
||||
* @param string $certFolder Folder path to save the certificates in PEM format.
|
||||
* @param bool $deleteCerts delete certificates in the target folder before adding the new ones.
|
||||
* @return int number of cetificates
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function queryFidoMetaDataService($certFolder, $deleteCerts=true) {
|
||||
$url = 'https://mds.fidoalliance.org/';
|
||||
$raw = null;
|
||||
if (\function_exists('curl_init')) {
|
||||
$ch = \curl_init($url);
|
||||
\curl_setopt($ch, CURLOPT_HEADER, false);
|
||||
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
\curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
||||
\curl_setopt($ch, CURLOPT_USERAGENT, 'github.com/lbuchs/WebAuthn - A simple PHP WebAuthn server library');
|
||||
$raw = \curl_exec($ch);
|
||||
\curl_close($ch);
|
||||
} else {
|
||||
$raw = \file_get_contents($url);
|
||||
}
|
||||
|
||||
$certFolder = \rtrim(\realpath($certFolder), '\\/');
|
||||
if (!is_dir($certFolder)) {
|
||||
throw new WebAuthnException('Invalid folder path for query FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
if (!\is_string($raw)) {
|
||||
throw new WebAuthnException('Unable to query FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
$jwt = \explode('.', $raw);
|
||||
if (\count($jwt) !== 3) {
|
||||
throw new WebAuthnException('Invalid JWT from FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
if ($deleteCerts) {
|
||||
foreach (\scandir($certFolder) as $ca) {
|
||||
if (\substr($ca, -4) === '.pem') {
|
||||
if (\unlink($certFolder . DIRECTORY_SEPARATOR . $ca) === false) {
|
||||
throw new WebAuthnException('Cannot delete certs in folder for FIDO Alliance Metadata Service');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list($header, $payload, $hash) = $jwt;
|
||||
$payload = Binary\ByteBuffer::fromBase64Url($payload)->getJson();
|
||||
|
||||
$count = 0;
|
||||
if (\is_object($payload) && \property_exists($payload, 'entries') && \is_array($payload->entries)) {
|
||||
foreach ($payload->entries as $entry) {
|
||||
if (\is_object($entry) && \property_exists($entry, 'metadataStatement') && \is_object($entry->metadataStatement)) {
|
||||
$description = $entry->metadataStatement->description ?? null;
|
||||
$attestationRootCertificates = $entry->metadataStatement->attestationRootCertificates ?? null;
|
||||
|
||||
if ($description && $attestationRootCertificates) {
|
||||
|
||||
// create filename
|
||||
$certFilename = \preg_replace('/[^a-z0-9]/i', '_', $description);
|
||||
$certFilename = \trim(\preg_replace('/\_{2,}/i', '_', $certFilename),'_') . '.pem';
|
||||
$certFilename = \strtolower($certFilename);
|
||||
|
||||
// add certificate
|
||||
$certContent = $description . "\n";
|
||||
$certContent .= \str_repeat('-', \mb_strlen($description)) . "\n";
|
||||
|
||||
foreach ($attestationRootCertificates as $attestationRootCertificate) {
|
||||
$attestationRootCertificate = \str_replace(["\n", "\r", ' '], '', \trim($attestationRootCertificate));
|
||||
$count++;
|
||||
$certContent .= "\n-----BEGIN CERTIFICATE-----\n";
|
||||
$certContent .= \chunk_split($attestationRootCertificate, 64, "\n");
|
||||
$certContent .= "-----END CERTIFICATE-----\n";
|
||||
}
|
||||
|
||||
if (\file_put_contents($certFolder . DIRECTORY_SEPARATOR . $certFilename, $certContent) === false) {
|
||||
throw new WebAuthnException('unable to save certificate from FIDO Alliance Metadata Service');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
// -----------------------------------------------
|
||||
// PRIVATE
|
||||
// -----------------------------------------------
|
||||
@@ -621,10 +459,6 @@ class WebAuthn {
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _checkOrigin($origin) {
|
||||
if (str_starts_with($origin, 'android:apk-key-hash:')) {
|
||||
return $this->_checkAndroidKeyHashes($origin);
|
||||
}
|
||||
|
||||
// https://www.w3.org/TR/webauthn/#rp-id
|
||||
|
||||
// The origin's scheme must be https
|
||||
@@ -636,22 +470,12 @@ class WebAuthn {
|
||||
$host = \parse_url($origin, PHP_URL_HOST);
|
||||
$host = \trim($host, '.');
|
||||
|
||||
// The RP ID must be equal to the origin's effective domain, or a registrable
|
||||
// domain suffix of the origin's effective domain.
|
||||
return \preg_match('/' . \preg_quote($this->_rpId) . '$/i', $host) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if the origin value contains a known android key hash
|
||||
* @param string $origin
|
||||
* @return boolean
|
||||
*/
|
||||
private function _checkAndroidKeyHashes($origin) {
|
||||
$parts = explode('android:apk-key-hash:', $origin);
|
||||
if (count($parts) !== 2) {
|
||||
return false;
|
||||
// The RP ID must be equal to the origin's effective domain, or the
|
||||
// origin's host must be a subdomain of the RP ID (i.e. preceded by a dot).
|
||||
if (\strcasecmp($host, $this->_rpId) === 0) {
|
||||
return true;
|
||||
}
|
||||
return in_array($parts[1], $this->_androidKeyHashes, true);
|
||||
return \str_ends_with(\strtolower($host), '.' . \strtolower($this->_rpId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -676,8 +500,8 @@ class WebAuthn {
|
||||
*/
|
||||
private function _verifySignature($dataToVerify, $signature, $credentialPublicKey) {
|
||||
|
||||
// Use Sodium to verify EdDSA 25519 as its not yet supported by openssl
|
||||
if (\function_exists('sodium_crypto_sign_verify_detached') && !\in_array('ed25519', \openssl_get_curve_names(), true)) {
|
||||
// Use Sodium to verify EdDSA 25519 if it's not supported by openssl
|
||||
if (\function_exists('sodium_crypto_sign_verify_detached') && !defined('OPENSSL_KEYTYPE_ED25519')) {
|
||||
$pkParts = [];
|
||||
if (\preg_match('/BEGIN PUBLIC KEY\-+(?:\s|\n|\r)+([^\-]+)(?:\s|\n|\r)*\-+END PUBLIC KEY/i', $credentialPublicKey, $pkParts)) {
|
||||
$rawPk = \base64_decode($pkParts[1]);
|
||||
@@ -685,7 +509,7 @@ class WebAuthn {
|
||||
// 30 = der sequence
|
||||
// 2a = length 42 byte
|
||||
// 30 = der sequence
|
||||
// 05 = lenght 5 byte
|
||||
// 05 = length 5 byte
|
||||
// 06 = der OID
|
||||
// 03 = OID length 3 byte
|
||||
// 2b 65 70 = OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
|
||||
@@ -709,6 +533,17 @@ class WebAuthn {
|
||||
throw new WebAuthnException('public key invalid', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
return \openssl_verify($dataToVerify, $signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
$algo = OPENSSL_ALGO_SHA256;
|
||||
|
||||
if (defined('OPENSSL_KEYTYPE_ED25519')) {
|
||||
$publicKeyDetails = \openssl_pkey_get_details($publicKey);
|
||||
|
||||
if ($publicKeyDetails && $publicKeyDetails['type'] === OPENSSL_KEYTYPE_ED25519) {
|
||||
// algorithm 0 is used because EdDSA has a built-in hash
|
||||
$algo = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return \openssl_verify($dataToVerify, $signature, $publicKey, $algo) === 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
namespace lbuchs\WebAuthn;
|
||||
namespace ReportUri\Passkeys;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
* @license https://github.com/report-uri/passkeys-php/blob/master/LICENSE MIT
|
||||
*/
|
||||
class WebAuthnException extends \Exception {
|
||||
const INVALID_DATA = 1;
|
||||
@@ -13,14 +13,13 @@ class WebAuthnException extends \Exception {
|
||||
const INVALID_RELYING_PARTY = 5;
|
||||
const INVALID_SIGNATURE = 6;
|
||||
const INVALID_PUBLIC_KEY = 7;
|
||||
const CERTIFICATE_NOT_TRUSTED = 8;
|
||||
const USER_PRESENT = 9;
|
||||
const USER_VERIFICATED = 10;
|
||||
const SIGNATURE_COUNTER = 11;
|
||||
const CRYPTO_STRONG = 13;
|
||||
const BYTEBUFFER = 14;
|
||||
const CBOR = 15;
|
||||
const ANDROID_NOT_TRUSTED = 16;
|
||||
const MISSING_PUBLIC_KEY = 17;
|
||||
|
||||
public function __construct($message = "", $code = 0, $previous = null) {
|
||||
parent::__construct($message, $code, $previous);
|
||||
|
||||
Reference in New Issue
Block a user