modify filemode for linux

This commit is contained in:
2026-02-14 20:08:34 +01:00
parent 0e78302640
commit ae455dba20
393 changed files with 114401 additions and 114401 deletions
@@ -1,179 +1,179 @@
<?php
namespace lbuchs\WebAuthn\Attestation;
use lbuchs\WebAuthn\WebAuthnException;
use lbuchs\WebAuthn\CBOR\CborDecoder;
use lbuchs\WebAuthn\Binary\ByteBuffer;
/**
* @author Lukas Buchs
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
*/
class AttestationObject {
private $_authenticatorData;
private $_attestationFormat;
private $_attestationFormatName;
public function __construct($binary , $allowedFormats) {
$enc = CborDecoder::decode($binary);
// validation
if (!\is_array($enc) || !\array_key_exists('fmt', $enc) || !is_string($enc['fmt'])) {
throw new WebAuthnException('invalid attestation format', WebAuthnException::INVALID_DATA);
}
if (!\array_key_exists('attStmt', $enc) || !\is_array($enc['attStmt'])) {
throw new WebAuthnException('invalid attestation format (attStmt not available)', WebAuthnException::INVALID_DATA);
}
if (!\array_key_exists('authData', $enc) || !\is_object($enc['authData']) || !($enc['authData'] instanceof ByteBuffer)) {
throw new WebAuthnException('invalid attestation format (authData not available)', 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
* @return bool
*/
public function validateRpIdHash($rpIdHash) {
return $rpIdHash === $this->_authenticatorData->getRpIdHash();
}
}
<?php
namespace lbuchs\WebAuthn\Attestation;
use lbuchs\WebAuthn\WebAuthnException;
use lbuchs\WebAuthn\CBOR\CborDecoder;
use lbuchs\WebAuthn\Binary\ByteBuffer;
/**
* @author Lukas Buchs
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
*/
class AttestationObject {
private $_authenticatorData;
private $_attestationFormat;
private $_attestationFormatName;
public function __construct($binary , $allowedFormats) {
$enc = CborDecoder::decode($binary);
// validation
if (!\is_array($enc) || !\array_key_exists('fmt', $enc) || !is_string($enc['fmt'])) {
throw new WebAuthnException('invalid attestation format', WebAuthnException::INVALID_DATA);
}
if (!\array_key_exists('attStmt', $enc) || !\is_array($enc['attStmt'])) {
throw new WebAuthnException('invalid attestation format (attStmt not available)', WebAuthnException::INVALID_DATA);
}
if (!\array_key_exists('authData', $enc) || !\is_object($enc['authData']) || !($enc['authData'] instanceof ByteBuffer)) {
throw new WebAuthnException('invalid attestation format (authData not available)', 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
* @return bool
*/
public function validateRpIdHash($rpIdHash) {
return $rpIdHash === $this->_authenticatorData->getRpIdHash();
}
}
File diff suppressed because it is too large Load Diff
@@ -1,96 +1,96 @@
<?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;
}
}
<?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 +1,152 @@
<?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));
}
}
<?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 +1,139 @@
<?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;
}
}
<?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 +1,193 @@
<?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;
}
}
<?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 +1,41 @@
<?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;
}
}
<?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 +1,139 @@
<?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;
}
}
<?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;
}
}
+180 -180
View File
@@ -1,180 +1,180 @@
<?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);
}
}
<?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 +1,93 @@
<?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;
}
}
<?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;
}
}
+300 -300
View File
@@ -1,300 +1,300 @@
<?php
namespace lbuchs\WebAuthn\Binary;
use lbuchs\WebAuthn\WebAuthnException;
/**
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/ByteBuffer.php
* Copyright © 2018 Thomas Bleeker - MIT licensed
* Modified by Lukas Buchs
* Thanks Thomas for your work!
*/
class ByteBuffer implements \JsonSerializable, \Serializable {
/**
* @var bool
*/
public static $useBase64UrlEncoding = false;
/**
* @var string
*/
private $_data;
/**
* @var int
*/
private $_length;
public function __construct($binaryData) {
$this->_data = (string)$binaryData;
$this->_length = \strlen($binaryData);
}
// -----------------------
// PUBLIC STATIC
// -----------------------
/**
* create a ByteBuffer from a base64 url encoded string
* @param string $base64url
* @return ByteBuffer
*/
public static function fromBase64Url($base64url): ByteBuffer {
$bin = self::_base64url_decode($base64url);
if ($bin === false) {
throw new WebAuthnException('ByteBuffer: Invalid base64 url string', WebAuthnException::BYTEBUFFER);
}
return new ByteBuffer($bin);
}
/**
* create a ByteBuffer from a base64 url encoded string
* @param string $hex
* @return ByteBuffer
*/
public static function fromHex($hex): ByteBuffer {
$bin = \hex2bin($hex);
if ($bin === false) {
throw new WebAuthnException('ByteBuffer: Invalid hex string', WebAuthnException::BYTEBUFFER);
}
return new ByteBuffer($bin);
}
/**
* create a random ByteBuffer
* @param string $length
* @return ByteBuffer
*/
public static function randomBuffer($length): ByteBuffer {
if (\function_exists('random_bytes')) { // >PHP 7.0
return new ByteBuffer(\random_bytes($length));
} else if (\function_exists('openssl_random_pseudo_bytes')) {
return new ByteBuffer(\openssl_random_pseudo_bytes($length));
} else {
throw new WebAuthnException('ByteBuffer: cannot generate random bytes', WebAuthnException::BYTEBUFFER);
}
}
// -----------------------
// PUBLIC
// -----------------------
public function getBytes($offset, $length): string {
if ($offset < 0 || $length < 0 || ($offset + $length > $this->_length)) {
throw new WebAuthnException('ByteBuffer: Invalid offset or length', WebAuthnException::BYTEBUFFER);
}
return \substr($this->_data, $offset, $length);
}
public function getByteVal($offset): int {
if ($offset < 0 || $offset >= $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return \ord(\substr($this->_data, $offset, 1));
}
public function getJson($jsonFlags=0) {
$data = \json_decode($this->getBinaryString(), null, 512, $jsonFlags);
if (\json_last_error() !== JSON_ERROR_NONE) {
throw new WebAuthnException(\json_last_error_msg(), WebAuthnException::BYTEBUFFER);
}
return $data;
}
public function getLength(): int {
return $this->_length;
}
public function getUint16Val($offset) {
if ($offset < 0 || ($offset + 2) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return unpack('n', $this->_data, $offset)[1];
}
public function getUint32Val($offset) {
if ($offset < 0 || ($offset + 4) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
$val = unpack('N', $this->_data, $offset)[1];
// Signed integer overflow causes signed negative numbers
if ($val < 0) {
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
}
return $val;
}
public function getUint64Val($offset) {
if (PHP_INT_SIZE < 8) {
throw new WebAuthnException('ByteBuffer: 64-bit values not supported by this system', WebAuthnException::BYTEBUFFER);
}
if ($offset < 0 || ($offset + 8) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
$val = unpack('J', $this->_data, $offset)[1];
// Signed integer overflow causes signed negative numbers
if ($val < 0) {
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
}
return $val;
}
public function getHalfFloatVal($offset) {
//FROM spec pseudo decode_half(unsigned char *halfp)
$half = $this->getUint16Val($offset);
$exp = ($half >> 10) & 0x1f;
$mant = $half & 0x3ff;
if ($exp === 0) {
$val = $mant * (2 ** -24);
} elseif ($exp !== 31) {
$val = ($mant + 1024) * (2 ** ($exp - 25));
} else {
$val = ($mant === 0) ? INF : NAN;
}
return ($half & 0x8000) ? -$val : $val;
}
public function getFloatVal($offset) {
if ($offset < 0 || ($offset + 4) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return unpack('G', $this->_data, $offset)[1];
}
public function getDoubleVal($offset) {
if ($offset < 0 || ($offset + 8) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return unpack('E', $this->_data, $offset)[1];
}
/**
* @return string
*/
public function getBinaryString(): string {
return $this->_data;
}
/**
* @param string|ByteBuffer $buffer
* @return bool
*/
public function equals($buffer): bool {
if (is_object($buffer) && $buffer instanceof ByteBuffer) {
return $buffer->getBinaryString() === $this->getBinaryString();
} else if (is_string($buffer)) {
return $buffer === $this->getBinaryString();
}
return false;
}
/**
* @return string
*/
public function getHex(): string {
return \bin2hex($this->_data);
}
/**
* @return bool
*/
public function isEmpty(): bool {
return $this->_length === 0;
}
/**
* jsonSerialize interface
* return binary data in RFC 1342-Like serialized string
* @return string
*/
public function jsonSerialize(): string {
if (ByteBuffer::$useBase64UrlEncoding) {
return self::_base64url_encode($this->_data);
} else {
return '=?BINARY?B?' . \base64_encode($this->_data) . '?=';
}
}
/**
* Serializable-Interface
* @return string
*/
public function serialize(): string {
return \serialize($this->_data);
}
/**
* Serializable-Interface
* @param string $serialized
*/
public function unserialize($serialized) {
$this->_data = \unserialize($serialized);
$this->_length = \strlen($this->_data);
}
/**
* (PHP 8 deprecates Serializable-Interface)
* @return array
*/
public function __serialize(): array {
return [
'data' => \serialize($this->_data)
];
}
/**
* object to string
* @return string
*/
public function __toString(): string {
return $this->getHex();
}
/**
* (PHP 8 deprecates Serializable-Interface)
* @param array $data
* @return void
*/
public function __unserialize($data) {
if ($data && isset($data['data'])) {
$this->_data = \unserialize($data['data']);
$this->_length = \strlen($this->_data);
}
}
// -----------------------
// PROTECTED STATIC
// -----------------------
/**
* base64 url decoding
* @param string $data
* @return string
*/
protected static function _base64url_decode($data): string {
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
}
/**
* base64 url encoding
* @param string $data
* @return string
*/
protected static function _base64url_encode($data): string {
return \rtrim(\strtr(\base64_encode($data), '+/', '-_'), '=');
}
}
<?php
namespace lbuchs\WebAuthn\Binary;
use lbuchs\WebAuthn\WebAuthnException;
/**
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/ByteBuffer.php
* Copyright © 2018 Thomas Bleeker - MIT licensed
* Modified by Lukas Buchs
* Thanks Thomas for your work!
*/
class ByteBuffer implements \JsonSerializable, \Serializable {
/**
* @var bool
*/
public static $useBase64UrlEncoding = false;
/**
* @var string
*/
private $_data;
/**
* @var int
*/
private $_length;
public function __construct($binaryData) {
$this->_data = (string)$binaryData;
$this->_length = \strlen($binaryData);
}
// -----------------------
// PUBLIC STATIC
// -----------------------
/**
* create a ByteBuffer from a base64 url encoded string
* @param string $base64url
* @return ByteBuffer
*/
public static function fromBase64Url($base64url): ByteBuffer {
$bin = self::_base64url_decode($base64url);
if ($bin === false) {
throw new WebAuthnException('ByteBuffer: Invalid base64 url string', WebAuthnException::BYTEBUFFER);
}
return new ByteBuffer($bin);
}
/**
* create a ByteBuffer from a base64 url encoded string
* @param string $hex
* @return ByteBuffer
*/
public static function fromHex($hex): ByteBuffer {
$bin = \hex2bin($hex);
if ($bin === false) {
throw new WebAuthnException('ByteBuffer: Invalid hex string', WebAuthnException::BYTEBUFFER);
}
return new ByteBuffer($bin);
}
/**
* create a random ByteBuffer
* @param string $length
* @return ByteBuffer
*/
public static function randomBuffer($length): ByteBuffer {
if (\function_exists('random_bytes')) { // >PHP 7.0
return new ByteBuffer(\random_bytes($length));
} else if (\function_exists('openssl_random_pseudo_bytes')) {
return new ByteBuffer(\openssl_random_pseudo_bytes($length));
} else {
throw new WebAuthnException('ByteBuffer: cannot generate random bytes', WebAuthnException::BYTEBUFFER);
}
}
// -----------------------
// PUBLIC
// -----------------------
public function getBytes($offset, $length): string {
if ($offset < 0 || $length < 0 || ($offset + $length > $this->_length)) {
throw new WebAuthnException('ByteBuffer: Invalid offset or length', WebAuthnException::BYTEBUFFER);
}
return \substr($this->_data, $offset, $length);
}
public function getByteVal($offset): int {
if ($offset < 0 || $offset >= $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return \ord(\substr($this->_data, $offset, 1));
}
public function getJson($jsonFlags=0) {
$data = \json_decode($this->getBinaryString(), null, 512, $jsonFlags);
if (\json_last_error() !== JSON_ERROR_NONE) {
throw new WebAuthnException(\json_last_error_msg(), WebAuthnException::BYTEBUFFER);
}
return $data;
}
public function getLength(): int {
return $this->_length;
}
public function getUint16Val($offset) {
if ($offset < 0 || ($offset + 2) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return unpack('n', $this->_data, $offset)[1];
}
public function getUint32Val($offset) {
if ($offset < 0 || ($offset + 4) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
$val = unpack('N', $this->_data, $offset)[1];
// Signed integer overflow causes signed negative numbers
if ($val < 0) {
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
}
return $val;
}
public function getUint64Val($offset) {
if (PHP_INT_SIZE < 8) {
throw new WebAuthnException('ByteBuffer: 64-bit values not supported by this system', WebAuthnException::BYTEBUFFER);
}
if ($offset < 0 || ($offset + 8) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
$val = unpack('J', $this->_data, $offset)[1];
// Signed integer overflow causes signed negative numbers
if ($val < 0) {
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
}
return $val;
}
public function getHalfFloatVal($offset) {
//FROM spec pseudo decode_half(unsigned char *halfp)
$half = $this->getUint16Val($offset);
$exp = ($half >> 10) & 0x1f;
$mant = $half & 0x3ff;
if ($exp === 0) {
$val = $mant * (2 ** -24);
} elseif ($exp !== 31) {
$val = ($mant + 1024) * (2 ** ($exp - 25));
} else {
$val = ($mant === 0) ? INF : NAN;
}
return ($half & 0x8000) ? -$val : $val;
}
public function getFloatVal($offset) {
if ($offset < 0 || ($offset + 4) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return unpack('G', $this->_data, $offset)[1];
}
public function getDoubleVal($offset) {
if ($offset < 0 || ($offset + 8) > $this->_length) {
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
}
return unpack('E', $this->_data, $offset)[1];
}
/**
* @return string
*/
public function getBinaryString(): string {
return $this->_data;
}
/**
* @param string|ByteBuffer $buffer
* @return bool
*/
public function equals($buffer): bool {
if (is_object($buffer) && $buffer instanceof ByteBuffer) {
return $buffer->getBinaryString() === $this->getBinaryString();
} else if (is_string($buffer)) {
return $buffer === $this->getBinaryString();
}
return false;
}
/**
* @return string
*/
public function getHex(): string {
return \bin2hex($this->_data);
}
/**
* @return bool
*/
public function isEmpty(): bool {
return $this->_length === 0;
}
/**
* jsonSerialize interface
* return binary data in RFC 1342-Like serialized string
* @return string
*/
public function jsonSerialize(): string {
if (ByteBuffer::$useBase64UrlEncoding) {
return self::_base64url_encode($this->_data);
} else {
return '=?BINARY?B?' . \base64_encode($this->_data) . '?=';
}
}
/**
* Serializable-Interface
* @return string
*/
public function serialize(): string {
return \serialize($this->_data);
}
/**
* Serializable-Interface
* @param string $serialized
*/
public function unserialize($serialized) {
$this->_data = \unserialize($serialized);
$this->_length = \strlen($this->_data);
}
/**
* (PHP 8 deprecates Serializable-Interface)
* @return array
*/
public function __serialize(): array {
return [
'data' => \serialize($this->_data)
];
}
/**
* object to string
* @return string
*/
public function __toString(): string {
return $this->getHex();
}
/**
* (PHP 8 deprecates Serializable-Interface)
* @param array $data
* @return void
*/
public function __unserialize($data) {
if ($data && isset($data['data'])) {
$this->_data = \unserialize($data['data']);
$this->_length = \strlen($this->_data);
}
}
// -----------------------
// PROTECTED STATIC
// -----------------------
/**
* base64 url decoding
* @param string $data
* @return string
*/
protected static function _base64url_decode($data): string {
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
}
/**
* base64 url encoding
* @param string $data
* @return string
*/
protected static function _base64url_encode($data): string {
return \rtrim(\strtr(\base64_encode($data), '+/', '-_'), '=');
}
}
+220 -220
View File
@@ -1,220 +1,220 @@
<?php
namespace lbuchs\WebAuthn\CBOR;
use lbuchs\WebAuthn\WebAuthnException;
use lbuchs\WebAuthn\Binary\ByteBuffer;
/**
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/CborDecoder.php
* Copyright © 2018 Thomas Bleeker - MIT licensed
* Modified by Lukas Buchs
* Thanks Thomas for your work!
*/
class CborDecoder {
const CBOR_MAJOR_UNSIGNED_INT = 0;
const CBOR_MAJOR_TEXT_STRING = 3;
const CBOR_MAJOR_FLOAT_SIMPLE = 7;
const CBOR_MAJOR_NEGATIVE_INT = 1;
const CBOR_MAJOR_ARRAY = 4;
const CBOR_MAJOR_TAG = 6;
const CBOR_MAJOR_MAP = 5;
const CBOR_MAJOR_BYTE_STRING = 2;
/**
* @param ByteBuffer|string $bufOrBin
* @return mixed
* @throws WebAuthnException
*/
public static function decode($bufOrBin) {
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
$offset = 0;
$result = self::_parseItem($buf, $offset);
if ($offset !== $buf->getLength()) {
throw new WebAuthnException('Unused bytes after data item.', WebAuthnException::CBOR);
}
return $result;
}
/**
* @param ByteBuffer|string $bufOrBin
* @param int $startOffset
* @param int|null $endOffset
* @return mixed
*/
public static function decodeInPlace($bufOrBin, $startOffset, &$endOffset = null) {
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
$offset = $startOffset;
$data = self::_parseItem($buf, $offset);
$endOffset = $offset;
return $data;
}
// ---------------------
// protected
// ---------------------
/**
* @param ByteBuffer $buf
* @param int $offset
* @return mixed
*/
protected static function _parseItem(ByteBuffer $buf, &$offset) {
$first = $buf->getByteVal($offset++);
$type = $first >> 5;
$val = $first & 0b11111;
if ($type === self::CBOR_MAJOR_FLOAT_SIMPLE) {
return self::_parseFloatSimple($val, $buf, $offset);
}
$val = self::_parseExtraLength($val, $buf, $offset);
return self::_parseItemData($type, $val, $buf, $offset);
}
protected static function _parseFloatSimple($val, ByteBuffer $buf, &$offset) {
switch ($val) {
case 24:
$val = $buf->getByteVal($offset);
$offset++;
return self::_parseSimple($val);
case 25:
$floatValue = $buf->getHalfFloatVal($offset);
$offset += 2;
return $floatValue;
case 26:
$floatValue = $buf->getFloatVal($offset);
$offset += 4;
return $floatValue;
case 27:
$floatValue = $buf->getDoubleVal($offset);
$offset += 8;
return $floatValue;
case 28:
case 29:
case 30:
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
case 31:
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
}
return self::_parseSimple($val);
}
/**
* @param int $val
* @return mixed
* @throws WebAuthnException
*/
protected static function _parseSimple($val) {
if ($val === 20) {
return false;
}
if ($val === 21) {
return true;
}
if ($val === 22) {
return null;
}
throw new WebAuthnException(sprintf('Unsupported simple value %d.', $val), WebAuthnException::CBOR);
}
protected static function _parseExtraLength($val, ByteBuffer $buf, &$offset) {
switch ($val) {
case 24:
$val = $buf->getByteVal($offset);
$offset++;
break;
case 25:
$val = $buf->getUint16Val($offset);
$offset += 2;
break;
case 26:
$val = $buf->getUint32Val($offset);
$offset += 4;
break;
case 27:
$val = $buf->getUint64Val($offset);
$offset += 8;
break;
case 28:
case 29:
case 30:
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
case 31:
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
}
return $val;
}
protected static function _parseItemData($type, $val, ByteBuffer $buf, &$offset) {
switch ($type) {
case self::CBOR_MAJOR_UNSIGNED_INT: // uint
return $val;
case self::CBOR_MAJOR_NEGATIVE_INT:
return -1 - $val;
case self::CBOR_MAJOR_BYTE_STRING:
$data = $buf->getBytes($offset, $val);
$offset += $val;
return new ByteBuffer($data); // bytes
case self::CBOR_MAJOR_TEXT_STRING:
$data = $buf->getBytes($offset, $val);
$offset += $val;
return $data; // UTF-8
case self::CBOR_MAJOR_ARRAY:
return self::_parseArray($buf, $offset, $val);
case self::CBOR_MAJOR_MAP:
return self::_parseMap($buf, $offset, $val);
case self::CBOR_MAJOR_TAG:
return self::_parseItem($buf, $offset); // 1 embedded data item
}
// This should never be reached
throw new WebAuthnException(sprintf('Unknown major type %d.', $type), WebAuthnException::CBOR);
}
protected static function _parseMap(ByteBuffer $buf, &$offset, $count) {
$map = array();
for ($i = 0; $i < $count; $i++) {
$mapKey = self::_parseItem($buf, $offset);
$mapVal = self::_parseItem($buf, $offset);
if (!\is_int($mapKey) && !\is_string($mapKey)) {
throw new WebAuthnException('Can only use strings or integers as map keys', WebAuthnException::CBOR);
}
$map[$mapKey] = $mapVal; // todo dup
}
return $map;
}
protected static function _parseArray(ByteBuffer $buf, &$offset, $count) {
$arr = array();
for ($i = 0; $i < $count; $i++) {
$arr[] = self::_parseItem($buf, $offset);
}
return $arr;
}
}
<?php
namespace lbuchs\WebAuthn\CBOR;
use lbuchs\WebAuthn\WebAuthnException;
use lbuchs\WebAuthn\Binary\ByteBuffer;
/**
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/CborDecoder.php
* Copyright © 2018 Thomas Bleeker - MIT licensed
* Modified by Lukas Buchs
* Thanks Thomas for your work!
*/
class CborDecoder {
const CBOR_MAJOR_UNSIGNED_INT = 0;
const CBOR_MAJOR_TEXT_STRING = 3;
const CBOR_MAJOR_FLOAT_SIMPLE = 7;
const CBOR_MAJOR_NEGATIVE_INT = 1;
const CBOR_MAJOR_ARRAY = 4;
const CBOR_MAJOR_TAG = 6;
const CBOR_MAJOR_MAP = 5;
const CBOR_MAJOR_BYTE_STRING = 2;
/**
* @param ByteBuffer|string $bufOrBin
* @return mixed
* @throws WebAuthnException
*/
public static function decode($bufOrBin) {
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
$offset = 0;
$result = self::_parseItem($buf, $offset);
if ($offset !== $buf->getLength()) {
throw new WebAuthnException('Unused bytes after data item.', WebAuthnException::CBOR);
}
return $result;
}
/**
* @param ByteBuffer|string $bufOrBin
* @param int $startOffset
* @param int|null $endOffset
* @return mixed
*/
public static function decodeInPlace($bufOrBin, $startOffset, &$endOffset = null) {
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
$offset = $startOffset;
$data = self::_parseItem($buf, $offset);
$endOffset = $offset;
return $data;
}
// ---------------------
// protected
// ---------------------
/**
* @param ByteBuffer $buf
* @param int $offset
* @return mixed
*/
protected static function _parseItem(ByteBuffer $buf, &$offset) {
$first = $buf->getByteVal($offset++);
$type = $first >> 5;
$val = $first & 0b11111;
if ($type === self::CBOR_MAJOR_FLOAT_SIMPLE) {
return self::_parseFloatSimple($val, $buf, $offset);
}
$val = self::_parseExtraLength($val, $buf, $offset);
return self::_parseItemData($type, $val, $buf, $offset);
}
protected static function _parseFloatSimple($val, ByteBuffer $buf, &$offset) {
switch ($val) {
case 24:
$val = $buf->getByteVal($offset);
$offset++;
return self::_parseSimple($val);
case 25:
$floatValue = $buf->getHalfFloatVal($offset);
$offset += 2;
return $floatValue;
case 26:
$floatValue = $buf->getFloatVal($offset);
$offset += 4;
return $floatValue;
case 27:
$floatValue = $buf->getDoubleVal($offset);
$offset += 8;
return $floatValue;
case 28:
case 29:
case 30:
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
case 31:
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
}
return self::_parseSimple($val);
}
/**
* @param int $val
* @return mixed
* @throws WebAuthnException
*/
protected static function _parseSimple($val) {
if ($val === 20) {
return false;
}
if ($val === 21) {
return true;
}
if ($val === 22) {
return null;
}
throw new WebAuthnException(sprintf('Unsupported simple value %d.', $val), WebAuthnException::CBOR);
}
protected static function _parseExtraLength($val, ByteBuffer $buf, &$offset) {
switch ($val) {
case 24:
$val = $buf->getByteVal($offset);
$offset++;
break;
case 25:
$val = $buf->getUint16Val($offset);
$offset += 2;
break;
case 26:
$val = $buf->getUint32Val($offset);
$offset += 4;
break;
case 27:
$val = $buf->getUint64Val($offset);
$offset += 8;
break;
case 28:
case 29:
case 30:
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
case 31:
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
}
return $val;
}
protected static function _parseItemData($type, $val, ByteBuffer $buf, &$offset) {
switch ($type) {
case self::CBOR_MAJOR_UNSIGNED_INT: // uint
return $val;
case self::CBOR_MAJOR_NEGATIVE_INT:
return -1 - $val;
case self::CBOR_MAJOR_BYTE_STRING:
$data = $buf->getBytes($offset, $val);
$offset += $val;
return new ByteBuffer($data); // bytes
case self::CBOR_MAJOR_TEXT_STRING:
$data = $buf->getBytes($offset, $val);
$offset += $val;
return $data; // UTF-8
case self::CBOR_MAJOR_ARRAY:
return self::_parseArray($buf, $offset, $val);
case self::CBOR_MAJOR_MAP:
return self::_parseMap($buf, $offset, $val);
case self::CBOR_MAJOR_TAG:
return self::_parseItem($buf, $offset); // 1 embedded data item
}
// This should never be reached
throw new WebAuthnException(sprintf('Unknown major type %d.', $type), WebAuthnException::CBOR);
}
protected static function _parseMap(ByteBuffer $buf, &$offset, $count) {
$map = array();
for ($i = 0; $i < $count; $i++) {
$mapKey = self::_parseItem($buf, $offset);
$mapVal = self::_parseItem($buf, $offset);
if (!\is_int($mapKey) && !\is_string($mapKey)) {
throw new WebAuthnException('Can only use strings or integers as map keys', WebAuthnException::CBOR);
}
$map[$mapKey] = $mapVal; // todo dup
}
return $map;
}
protected static function _parseArray(ByteBuffer $buf, &$offset, $count) {
$arr = array();
for ($i = 0; $i < $count; $i++) {
$arr[] = self::_parseItem($buf, $offset);
}
return $arr;
}
}
File diff suppressed because it is too large Load Diff
+28 -28
View File
@@ -1,28 +1,28 @@
<?php
namespace lbuchs\WebAuthn;
/**
* @author Lukas Buchs
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
*/
class WebAuthnException extends \Exception {
const INVALID_DATA = 1;
const INVALID_TYPE = 2;
const INVALID_CHALLENGE = 3;
const INVALID_ORIGIN = 4;
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;
public function __construct($message = "", $code = 0, $previous = null) {
parent::__construct($message, $code, $previous);
}
}
<?php
namespace lbuchs\WebAuthn;
/**
* @author Lukas Buchs
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
*/
class WebAuthnException extends \Exception {
const INVALID_DATA = 1;
const INVALID_TYPE = 2;
const INVALID_CHALLENGE = 3;
const INVALID_ORIGIN = 4;
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;
public function __construct($message = "", $code = 0, $previous = null) {
parent::__construct($message, $code, $previous);
}
}