pax_global_header 0000666 0000000 0000000 00000000064 14342705561 0014521 g ustar 00root root 0000000 0000000 52 comment=6931a00f5feb0d923ea28d3e4816272536f45077
U2F-php-server-1.2.1/ 0000775 0000000 0000000 00000000000 14342705561 0014207 5 ustar 00root root 0000000 0000000 U2F-php-server-1.2.1/CHANGELOG.md 0000664 0000000 0000000 00000002556 14342705561 0016030 0 ustar 00root root 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased] - yyyy-mm-dd
## [1.2.1] - 2022-12-03
- Don't replace `samyoul/u2f-php-server` anymore in `composer.json`
- Exclude tests and phpunit config from vendor archives
- Apply `wdes/coding-standard` and make constants officially public
## [1.2.0] - 2021-12-12
- Added `ReturnTypeWillChange` for PHP 8.1 on SignRequest and RegistrationRequest
- Wrote tests for most of the code of this library
- Run tests on GitHub actions
- Changed the namespace from `Samyoul` to `CodeLts`
- Cleaned up the code
- Added a `.gitattributes` file
- Improved phpdoc blocks
- Wrote betters comments
- Added a CHANGELOG file
- Improved the README file
## [1.1.4] - 2018-10-26
- Fix issue when there is more than one U2F key registered
## [1.1.3] - 2016-12-14
- Fix public property access bug in `U2FServer` class
- Made `SignRequest` class json `JsonSerializable`
## [1.1.2] - 2016-12-13
- Replaced `toString()` with `jsonSerialize()` on `RegistrationRequest` class
## [1.1.1] - 2016-12-13
- Added `toString()` on `RegistrationRequest` class
## [1.1.0] - 2016-12-13
- Re-Namespaced the classes
## [1.0.0] - 2016-12-12
- First version
U2F-php-server-1.2.1/LICENCE 0000664 0000000 0000000 00000002513 14342705561 0015175 0 ustar 00root root 0000000 0000000 BSD 2-Clause License
Copyright (c) 2016-2018, Samyoul
Copyright (c) 2020, William Desportes
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
U2F-php-server-1.2.1/README.md 0000664 0000000 0000000 00000041200 14342705561 0015463 0 ustar 00root root 0000000 0000000 # U2F-php-server
[](https://packagist.org/packages/code-lts/u2f-php-server)
[](LICENCE)
[](https://codecov.io/gh/code-lts/U2F-php-server)
Server-side handling of FIDO U2F registration and authentication for PHP.
Securing your online accounts and doing your bit to protect your data is extremely important and increasingly more so as hackers get more sophisticated.
FIDO's U2F enables you to add a simple unobtrusive method of 2nd factor authentication, allowing users of your service and/or application to link a hardware key to their account.
## Story about this library fork
All started in this [issue](https://github.com/Samyoul/U2F-php-server/issues/8) in October 2020.
I quickly worked hard on building tests and opening a [pull-request](https://github.com/Samyoul/U2F-php-server/pull/9).
But nothing got merged because the library author vanished.
### What does change in this fork ?
For the first released version: nothing changed, only tests where written. And PHP 8.1 support was done.
Future versions may change things.
## The Family of U2F php Libraries
**Base Library**
https://github.com/code-lts/U2F-php-server
## Contents
1. [Installation](#installation)
2. [Requirements](#requirements)
1. [OpenSSL](#openssl)
1. [Clientside Magic](#client-side-the-magic-javascript-bit-of-talking-with-a-usb-device)
1. [HTTPS and SSL](#https-and-ssl)
3. [Terminology](#terminology)
4. [Recommended Datastore Structure](#recommended-datastore-structure)
5. [Process Workflow](#process-workflow)
1. [Registration Process Flow](#registration-process-flow)
1. [Authentication Process Flow](#authentication-process-flow)
6. [Example Code](#example-code)
1. [Compatibility Check](#compatibility-code)
1. [Registration Code](#registration-code)
1. [Authentication Code](#authentication-code)
7. [Frameworks](#frameworks)
1. [Laravel](#laravel-framework)
1. [Yii](#yii-framework)
1. [CodeIgniter](#codeigniter-framework)
8. [Licence](#licence)
9. [Credits](#credits)
## Installation
`composer require code-lts/u2f-php-server`
## Requirements
A few **things you need** to know before working with this:
1. [**_OpenSSL_**](#openssl) You need at least OpenSSL 1.0.0 or higher.
2. [**_Client-side Handling_**](#client-side) You need to be able to communicate with a some kind of device.
3. [**_A HTTPS URL_**](#https-and-ssl) This is very important, without HTTPS U2F simply will not work.
4. [**_A Datastore_**](#recommended-datastore-structure) You need some kind of datastore for all your U2F registered users (although if you have a system with user authentication I'm presuming you've got this one sorted).
### OpenSSL
This repository requires OpenSSL 1.0.0 or higher. For further details on installing OpenSSL please refer to the [php manual](https://www.php.net/manual/en/openssl.installation.php).
Also see [Compatibility Code](#compatibility-code), to check if you have the correct version of OpenSSL installed, and are unsure how else to check.
### Client-side (The magic JavaScript Bit of talking with a USB device)
My presumption is that if you are looking to add U2F authentication to a php system, then you'll probably are also looking for some client-side handling. You've got a U2F enabled USB device and you want to get the USB device speaking with the browser and then with your server running php.
1. Google already have this bit sorted : [u2f-api.js](https://github.com/google/u2f-ref-code/blob/master/u2f-gae-demo/war/js/u2f-api.js)
2. [Mastahyeti](https://github.com/mastahyeti) has created a repo dedicated to Google's JavaScript Client-side API : https://github.com/mastahyeti/u2f-api
### HTTPS and SSL
For U2F to work your website/service must use a HTTPS URL. Without a HTTPS URL your code won't work, so get one for your localhost, get one for your production. https://letsencrypt.org/
Basically encrypt everything.
## Terminology
**_HID_** : _Human Interface Device_, like A USB Device [like these things](https://www.google.co.uk/search?q=fido+usb+key&safe=off&tbm=isch)
## Recommended Datastore Structure
You don't need to follow this structure exactly, but you will need to associate your Registration data with a user. You'll also need to store the key handle, public key and the certificate, counter isn't 100% essential but it makes your application more secure.
|Name|Type|Description|
|---|---|---|
|id|integer primary key||
|user_id|integer||
|key_handle|varchar(255)||
|public_key|varchar(255)||
|certificate|text||
|counter|integer||
TODO the descriptions
## Process Workflow
### Registration Process Flow
1. User navigates to a 2nd factor authentication page in your application.
... TODO add the rest of the registration process flow ...
### Authentication Process Flow
1. User navigates to their login page as they usually would, submits username and password.
1. Server received POST request authentication data, normal username + password validation occurs
1. On successful authentication, the application checks 2nd factor authentication is required. We're going to presume it is, otherwise the user would just be logged in at this stage.
1. Application gets the user's registered signatures from the application datastore: `$registrations`.
1. Application gets its ID, usually the domain the application is accessible from: `$appId`
1. Application makes a `U2F::makeAuthentication($registrations, $appId)` call, the method returns an array of `SignRequest` objects: `$authenticationRequest`.
1. Application JSON encodes the array and passes the data to the view
1. When the browser loads the page the JavaScript fires the `u2f.sign(authenticationRequest, function(data){ // Callback logic })` function
1. The view will use JavaScript / Browser to poll the host machine's ports for a FIDO U2F device
1. Once the HID has been found the JavaScript / Browser will send the sign request with data.
1. The HID will prompt the user to authorize the sign request
1. On success the HID returns authentication data
1. The JavaScript receives the HID's returned data and passes it to the server
1. The application takes the returned data passes it to the `U2F::authenticate($authenticationRequest, $registrations, $authenticationResponse)` method
1. If the method returns a registration and doesn't throw an Exception, authentication is complete.
1. Set the user's session, inform the user of the success, and redirect them.
## Example Code
For a full working code example for this repository please see [the dedicated example repository](https://github.com/code-lts/U2F-php-server-examples)
You can also install it with the following:
```sh
$ git clone https://github.com/code-lts/U2F-php-server-examples.git
$ cd u2f-php-server-examples
$ composer install
```
1. [Compatibility Code](#compatibility-code)
2. [Registration Code](#registration-code)
1. [Step 1: Starting](#registration-step-1)
1. [Step 2: Talking to the HID](#registration-step-2)
1. [Step 3: Validation & Storage](#registration-step-3)
3. [Authentication Code](#authentication-code)
1. [Step 1: Starting](#authentication-step-1)
1. [Step 2: Talking to the HID](#authentication-step-2)
1. [Step 3: Validation](#authentication-step-3)
---
### Compatibility Code
You'll only ever need to use this method call once per installation and only in the context of debugging if the class is giving you unexpected errors. This method call will check your OpenSSL version and ensure it is at least 1.0.0 .
```php
$jsRequest,
'jsSignatures' => $jsSignatures,
]);
```
#### Registration Step 2:
**Client-side, Talking To The USB**
Non-AJAX client-side registration of U2F key token. AJAX can of course be used in your application, but it is easier to demonstrate a linear process without AJAX and callbacks.
```html
U2F Key Registration
U2F Registration
Please enter your FIDO U2F device into your computer's USB port. Then confirm registration on the device.
```
#### Registration Step 3:
**Validation and Key Storage**
This is the last stage of registration. Validate the registration response data against the original request data.
```php
storeRegistration($validatedRegistration);
// Then let your user know what happened
$userMessage = 'Success';
} catch( Exception $e ) {
$userMessage = 'We had an error: '. $e->getMessage();
}
//Fictitious view.
echo View::make('template/location/u2f-registration-result.html', [
'userMessage' => $userMessage,
]);
```
---
### Authentication Code
#### Authentication Step 1:
**Starting the authentication process:**
We assume that user has successfully authenticated and has previously registered to use FIDO U2F.
```php
U2FRegistrations();
// This can be anything, but usually easier if you choose your applications domain and top level domain.
$appId = 'yourdomain.tld';
// Call the U2F makeAuthentication method, passing in the user's registration(s) and the app ID
$authenticationRequest = U2F::makeAuthentication($registrations, $appId);
// Store the request for later
$_SESSION['authenticationRequest'] = $authenticationRequest;
// now pass the data to a fictitious view.
echo View::make('template/location/u2f-authentication.html', [
'authenticationRequest' => $authenticationRequest,
]);
```
#### Authentication Step 2:
**Client-side, Talking To The USB**
Non-AJAX client-side authentication of U2F key token. AJAX can of course be used in your application, but it is easier to demonstrate a linear process without AJAX and callbacks.
```html
U2F Key Authentication
U2F Authentication
Please enter your FIDO U2F device into your computer's USB port. Then confirm authentication on the device.
```
#### Authentication Step 3:
**Validation**
This is the last stage of authentication. Validate the authentication response data against the original request data.
```php
U2FRegistrations();
try {
// Validate the authentication response against the registration request.
// The output are the credentials you need to store for U2F authentication.
$validatedAuthentication = U2F::authenticate(
$_SESSION['authenticationRequest'],
$registrations,
json_decode($_POST['u2f_authentication_response'])
);
// Fictitious function representing the updating of the U2F token count integer.
$user->updateU2FRegistrationCount($validatedAuthentication);
// Then let your user know what happened
$userMessage = 'Success';
} catch( Exception $e ) {
$userMessage = 'We had an error: '. $e->getMessage();
}
//Fictitious view.
echo View::make('template/location/u2f-authentication-result.html', [
'userMessage' => $userMessage,
]);
```
---
Again, if you want to just download some example code to play with just install the full working code examples written for this repository please see [the dedicated example repository](https://github.com/code-lts/U2F-php-server-examples)
You can also install it with the following:
```sh
$ git clone https://github.com/code-lts/U2F-php-server-examples.git
$ cd u2f-php-server-examples
$ composer install
```
## Licence
The repository is licensed under a BSD license. [Read details here](https://github.com/code-lts/U2F-php-server/blob/master/LICENCE)
## Credits
This repo was originally based on the [Yubico php-u2flib-server](https://github.com/Yubico/php-u2flib-server)
U2F-php-server-1.2.1/composer.json 0000664 0000000 0000000 00000002510 14342705561 0016727 0 ustar 00root root 0000000 0000000 {
"name": "code-lts/u2f-php-server",
"description": "Server side handling class for FIDO U2F registration and authentication",
"license":"BSD-2-Clause",
"homepage": "https://github.com/code-lts/U2F-php-server#readme",
"authors": [
{
"name": "Samuel Hawksby-Robinson",
"email": "samuel@samyoul.com"
},
{
"name": "William Desportes",
"email": "williamdes@wdes.fr"
}
],
"support": {
"issues": "https://github.com/code-lts/U2F-php-server/issues",
"source": "https://github.com/code-lts/U2F-php-server"
},
"scripts": {
"test": "@php phpunit",
"phpcs": "@php phpcs",
"phpcbf": "@php phpcbf"
},
"require": {
"php": "^7.1 || ^8.0",
"ext-openssl":"*"
},
"require-dev": {
"phpunit/phpunit": "^7 || ^8 || ^9",
"wdes/coding-standard": "^3.3"
},
"autoload": {
"psr-4": { "CodeLts\\U2F\\U2FServer\\": ["src/"] }
},
"autoload-dev": {
"psr-4": { "CodeLts\\U2F\\U2FServer\\Tests\\": ["test/"] }
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
},
"archive": {
"exclude": [
"/test",
"/phpunit.xml"
]
}
}
U2F-php-server-1.2.1/phpunit.xml 0000664 0000000 0000000 00000001525 14342705561 0016423 0 ustar 00root root 0000000 0000000
src
test/
U2F-php-server-1.2.1/src/ 0000775 0000000 0000000 00000000000 14342705561 0014776 5 ustar 00root root 0000000 0000000 U2F-php-server-1.2.1/src/Registration.php 0000664 0000000 0000000 00000002453 14342705561 0020165 0 ustar 00root root 0000000 0000000 keyHandle = $keyHandle;
}
/**
* @param string $publicKey
*/
public function setPublicKey($publicKey)
{
$this->publicKey = $publicKey;
}
/**
* @param string $certificate
*/
public function setCertificate($certificate)
{
$this->certificate = $certificate;
}
/**
* @return string
*/
public function getKeyHandle()
{
return $this->keyHandle;
}
/**
* @return string
*/
public function getPublicKey()
{
return $this->publicKey;
}
/**
* @return string
*/
public function getCertificate()
{
return $this->certificate;
}
/**
* @return string
*/
public function getCounter()
{
return $this->counter;
}
}
U2F-php-server-1.2.1/src/RegistrationRequest.php 0000664 0000000 0000000 00000002106 14342705561 0021531 0 ustar 00root root 0000000 0000000 challenge = $challenge;
$this->appId = $appId;
}
/**
* @return string
*/
public function version()
{
return $this->version;
}
/**
* @return string
*/
public function challenge()
{
return $this->challenge;
}
/**
* @return string
*/
public function appId()
{
return $this->appId;
}
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return [
'version' => $this->version,
'challenge' => $this->challenge,
'appId' => $this->appId,
];
}
}
U2F-php-server-1.2.1/src/SignRequest.php 0000664 0000000 0000000 00000002477 14342705561 0017772 0 ustar 00root root 0000000 0000000 challenge = $parameters['challenge'];
$this->keyHandle = $parameters['keyHandle'];
$this->appId = $parameters['appId'];
}
/**
* @return string
*/
public function version()
{
return $this->version;
}
/**
* @return string
*/
public function challenge()
{
return $this->challenge;
}
/**
* @return string
*/
public function keyHandle()
{
return $this->keyHandle;
}
/**
* @return string
*/
public function appId()
{
return $this->appId;
}
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return [
'version' => $this->version,
'challenge' => $this->challenge,
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
];
}
}
U2F-php-server-1.2.1/src/U2FException.php 0000664 0000000 0000000 00000003231 14342705561 0017761 0 ustar 00root root 0000000 0000000 An array of two elements, the first containing a
* RegisterRequest the second being an array of SignRequest
* @throws U2FException
*/
public static function makeRegistration($appId, array $registrations = [])
{
$request = new RegistrationRequest(static::createChallenge(), $appId);
$signatures = static::makeAuthentication($registrations, $appId);
return [
'request' => $request,
'signatures' => $signatures,
];
}
/**
* Called to verify and unpack a registration message.
*
* @param RegistrationRequest $request this is a reply to
* @param object $response response from a user
* @param string|null $attestDir The folder to use where trusted CA files are stored (optional)
* @param bool $includeCert set to true if the attestation certificate should be
* included in the returned Registration object (optional)
* @return Registration
* @throws U2FException
*/
public static function register(RegistrationRequest $request, $response, $attestDir = null, $includeCert = true)
{
// Parameter Checks
// $request is safe because of the php typehint
if (!is_object($response)) {
throw new \InvalidArgumentException('$response of register() method only accepts object.');
}
if (property_exists($response, 'errorCode') && $response->errorCode !== 0) {
throw new U2FException(
'User-agent returned error. Error code: ' . $response->errorCode,
U2FException::BAD_UA_RETURNING
);
}
if (!is_bool($includeCert)) {
throw new \InvalidArgumentException('$include_cert of register() method only accepts boolean.');
}
// Unpack the registration data coming from the client-side token
$rawRegistration = static::base64uDecode($response->registrationData);
$registrationData = array_values(unpack('C*', $rawRegistration));
$clientData = static::base64uDecode($response->clientData);
$clientToken = json_decode($clientData);
// Check Client's challenge matches the original request's challenge
if ($clientToken->challenge !== $request->challenge()) {
throw new U2FException(
'Registration challenge does not match',
U2FException::UNMATCHED_CHALLENGE
);
}
// Begin validating and building the registration
$registration = new Registration();
$offset = 1;
$pubKey = substr($rawRegistration, $offset, static::PUBKEY_LEN);
$offset += static::PUBKEY_LEN;
// Validate and set the public key
if (static::publicKeyToPem($pubKey) === null) {
throw new U2FException(
'Decoding of public key failed',
U2FException::PUBKEY_DECODE
);
}
$registration->setPublicKey(base64_encode($pubKey));
// Build and set the key handle.
$keyHandleLength = $registrationData[$offset++];
$keyHandle = substr($rawRegistration, $offset, $keyHandleLength);
$offset += $keyHandleLength;
$registration->setKeyHandle(static::base64uEncode($keyHandle));
// Build certificate
// Set certificate length
// Note: length of certificate is stored in byte 3 and 4 (excluding the first 4 bytes)
$certLength = 4;
$certLength += ($registrationData[$offset + 2] << 8);
$certLength += $registrationData[$offset + 3];
// Write the certificate from the returning registration data
$rawCert = static::fixSignatureUnusedBits(substr($rawRegistration, $offset, $certLength));
$offset += $certLength;
$pemCert = "-----BEGIN CERTIFICATE-----\r\n";
$pemCert .= chunk_split(base64_encode($rawCert), 64);
$pemCert .= '-----END CERTIFICATE-----';
if ($includeCert) {
$registration->setCertificate(base64_encode($rawCert));
}
// If we've set the attestDir, check the given certificate can be used.
if ($attestDir) {
if (openssl_x509_checkpurpose($pemCert, -1, static::getCerts($attestDir)) !== true) {
throw new U2FException(
'Attestation certificate can not be validated',
U2FException::ATTESTATION_VERIFICATION
);
}
}
// Attempt to extract public key from the certificate, if we can't something went wrong in making it.
if (!openssl_pkey_get_public($pemCert)) {
throw new U2FException(
'Decoding of public key failed',
U2FException::PUBKEY_DECODE
);
}
// Generate signature from the remaining part of the raw registration data
$signature = substr($rawRegistration, $offset);
// Build a verification string from the components we've made in this function
$dataToVerify = chr(0);
$dataToVerify .= hash('sha256', $request->appId(), true);
$dataToVerify .= hash('sha256', $clientData, true);
$dataToVerify .= $keyHandle;
$dataToVerify .= $pubKey;
// Verify our data against the signature and the certificate, on success return the registration object
if (openssl_verify($dataToVerify, $signature, $pemCert, 'sha256') === 1) {
return $registration;
} else {
throw new U2FException(
'Attestation signature does not match',
U2FException::ATTESTATION_SIGNATURE
);
}
}
/**
* Called to get an authentication request.
*
* @param stdClass[] $registrations An array of the registrations to create authentication requests for.
* @param string $appId Application id for the running application, Basically the app's URL
* @return SignRequest[] An array of SignRequest
* @throws \InvalidArgumentException
*/
public static function makeAuthentication(array $registrations, $appId)
{
$signatures = [];
$challenge = static::createChallenge();
foreach ($registrations as $reg) {
if (!is_object($reg)) {
throw new \InvalidArgumentException('$registrations of makeAuthentication() method only accepts array of object.');
}
$signatures[] = new SignRequest(
[
'appId' => $appId,
'keyHandle' => $reg->keyHandle,
'challenge' => $challenge,
]
);
}
return $signatures;
}
/**
* Called to verify an authentication response
*
* @param SignRequest[] $requests An array of outstanding authentication requests
* @param stdClass[] $registrations An array of current registrations
* @param object $response A response from the authenticator
* @return \stdClass
* @throws U2FException
*
* The Registration object returned on success contains an updated counter
* that should be saved for future authentications.
* If the Error returned is ERR_COUNTER_TOO_LOW this is an indication of
* token cloning or similar and appropriate action should be taken.
*/
public static function authenticate(array $requests, array $registrations, $response)
{
// Parameter checks
if (!is_object($response)) {
throw new \InvalidArgumentException('$response of authenticate() method only accepts object.');
}
if (property_exists($response, 'errorCode') && $response->errorCode !== 0) {
throw new U2FException(
'User-agent returned error. Error code: ' . $response->errorCode,
U2FException::BAD_UA_RETURNING
);
}
// Set default values to null, so we get fails by default
/** @var object|null $req */
$req = null;
/** @var object|null $reg */
$reg = null;
// Extract client response data
$clientData = static::base64uDecode($response->clientData);
$decodedClient = json_decode($clientData);
// Check we have a match among the requests and the response
foreach ($requests as $req) {
if (!is_object($req)) {
throw new \InvalidArgumentException('$requests of authenticate() method only accepts an array of objects.');
}
if ($req->keyHandle() === $response->keyHandle && $req->challenge() === $decodedClient->challenge) {
break;
}
$req = null;
}
if ($req === null) {
throw new U2FException(
'No matching request found',
U2FException::NO_MATCHING_REQUEST
);
}
// Check for a match for the response among a list of registrations
foreach ($registrations as $reg) {
if (!is_object($reg)) {
throw new \InvalidArgumentException('$registrations of authenticate() method only accepts an array of objects.');
}
if ($reg->keyHandle === $response->keyHandle) {
break;
}
$reg = null;
}
if ($reg === null) {
throw new U2FException(
'No matching registration found',
U2FException::NO_MATCHING_REGISTRATION
);
}
// On Success, check we have a valid public key
$pemKey = static::publicKeyToPem(static::base64uDecode($reg->publicKey));
if ($pemKey === null) {
throw new U2FException(
'Decoding of public key failed',
U2FException::PUBKEY_DECODE
);
}
// Build signature and data from response
$signData = static::base64uDecode($response->signatureData);
$dataToVerify = hash('sha256', $req->appId(), true);
$dataToVerify .= substr($signData, 0, 5);
$dataToVerify .= hash('sha256', $clientData, true);
$signature = substr($signData, 5);
// Verify the response data against the public key
if (openssl_verify($dataToVerify, $signature, $pemKey, 'sha256') === 1) {
$ctr = unpack('Nctr', substr($signData, 1, 4));
$counter = $ctr['ctr'];
/* TODO: wrap-around should be handled somehow.. */
if ($counter > $reg->counter) {
$reg->counter = $counter;
return $reg;
} else {
throw new U2FException(
'Counter too low.',
U2FException::COUNTER_TOO_LOW
);
}
} else {
throw new U2FException(
'Authentication failed',
U2FException::AUTHENTICATION_FAILURE
);
}
}
/**
* Get all files from a directory
*
* @param string $attestDir The folder to find files into
* @return string[]
*/
private static function getCerts($attestDir)
{
$files = [];
$dir = $attestDir;
if ($dir && $handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (is_file($dir . DIRECTORY_SEPARATOR . $entry)) {
$files[] = $dir . DIRECTORY_SEPARATOR . $entry;
}
}
closedir($handle);
}
return $files;
}
/**
* @param string $data
* @return string
*/
private static function base64uEncode($data)
{
return trim(strtr(base64_encode($data), '+/', '-_'), '=');
}
/**
* @param string $data
* @return string
*/
private static function base64uDecode($data)
{
return base64_decode(strtr($data, '-_', '+/'));
}
/**
* @param string $key
* @return null|string
*/
private static function publicKeyToPem($key)
{
if (strlen($key) !== static::PUBKEY_LEN || $key[0] !== "\x04") {
return null;
}
/*
* Convert the public key to binary DER format first
* Using the ECC SubjectPublicKeyInfo OIDs from RFC 5480
*
* SEQUENCE(2 elem) 30 59
* SEQUENCE(2 elem) 30 13
* OID1.2.840.10045.2.1 (id-ecPublicKey) 06 07 2a 86 48 ce 3d 02 01
* OID1.2.840.10045.3.1.7 (secp256r1) 06 08 2a 86 48 ce 3d 03 01 07
* BIT STRING(520 bit) 03 42 ..key..
*/
$der = "\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01";
$der .= "\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42";
$der .= "\0" . $key;
$pem = "-----BEGIN PUBLIC KEY-----\r\n";
$pem .= chunk_split(base64_encode($der), 64);
$pem .= '-----END PUBLIC KEY-----';
return $pem;
}
/**
* @return string
* @throws U2FException
*/
private static function createChallenge()
{
$challenge = openssl_random_pseudo_bytes(32, $crypto_strong);
if ($crypto_strong !== true) {
throw new U2FException(
'Unable to obtain a good source of randomness',
U2FException::BAD_RANDOM
);
}
$challenge = static::base64uEncode($challenge);
return $challenge;
}
/**
* Fixes a certificate where the signature contains unused bits.
*
* @param string $cert
* @return string
*/
private static function fixSignatureUnusedBits($cert)
{
if (in_array(hash('sha256', $cert), static::$FIXCERTS)) {
$cert[strlen($cert) - 257] = "\0"; // Fix the "unused bits" field (should always be 0).
}
return $cert;
}
}
U2F-php-server-1.2.1/test/ 0000775 0000000 0000000 00000000000 14342705561 0015166 5 ustar 00root root 0000000 0000000 U2F-php-server-1.2.1/test/RegistrationRequestTest.php 0000664 0000000 0000000 00000001664 14342705561 0022571 0 ustar 00root root 0000000 0000000 assertSame('http://demo.example.com', $rr->appId());
$this->assertSame('yKA0x075tjJ-GE7fKTfnzTOSaNUOWQxRd9TWz5aFOg8', $rr->challenge());
$this->assertSame('U2F_V2', $rr->version());
}
public function testToJson(): void
{
$rr = new RegistrationRequest('yKA0x075tjJ-GE7fKTfnzTOSaNUOWQxRd9TWz5aFOg8', 'http://demo.example.com');
$this->assertSame(
'{"version":"U2F_V2","challenge":"yKA0x075tjJ-GE7fKTfnzTOSaNUOWQxRd9TWz5aFOg8","appId":"http:\/\/demo.example.com"}',
json_encode($rr)
);
}
}
U2F-php-server-1.2.1/test/SignRequestTest.php 0000664 0000000 0000000 00000003250 14342705561 0021010 0 ustar 00root root 0000000 0000000 'fEnc9oV79EaBgK5BoNERU5gPKM2XGYWrz4fUjgc0000',
'keyHandle' => $this->keyHandle,
'appId' => 'http://demo.example.com',
]
);
$this->assertSame('http://demo.example.com', $sr->appId());
$this->assertSame('fEnc9oV79EaBgK5BoNERU5gPKM2XGYWrz4fUjgc0000', $sr->challenge());
$this->assertSame('U2F_V2', $sr->version());
}
public function testToJson(): void
{
$sr = new SignRequest(
[
'challenge' => 'fEnc9oV79EaBgK5BoNERU5gPKM2XGYWrz4fUjgc0000',
'keyHandle' => $this->keyHandle,
'appId' => 'http://demo.example.com',
]
);
$this->assertSame(
'{"version":"U2F_V2","challenge":"fEnc9oV79EaBgK5BoNERU5gPKM2XGYWrz4fUjgc0000",'
. '"keyHandle":"CTUayZo8hCBeC-sGQJChC0wW-bBg99bmOlGCgw8XGq4dLsxO3yWh9mRYArZxocP5hBB1pEGB3bbJYiM-5acc5w",'
. '"appId":"http:\/\/demo.example.com"}',
json_encode($sr)
);
}
}
U2F-php-server-1.2.1/test/U2FServerTest.php 0000664 0000000 0000000 00000065537 14342705561 0020342 0 ustar 00root root 0000000 0000000 getMethod($methodName);
$method->setAccessible(true);
return $method;
}
public function testCreateChallenge(): void
{
$u2f = self::getClassMethod(U2FServer::class, 'createChallenge');
$challengeResult = $u2f->invokeArgs(new U2FServer(), []);
$this->assertNotEmpty($challengeResult);
$this->assertGreaterThan(20, strlen($challengeResult));
}
public function dataProviderForFixSignatureUnusedBits(): array
{
return [
[
// This is an example certificate in hex format
// @see https://fidoalliance.org/specs/u2f-specs-1.0-bt-nfc-id-amendment/fido-u2f-raw-message-formats.html
'3082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e7562627920'
. '50696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f7447'
. '6e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d03010703'
. '4200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf020'
. '3b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb8'
. '36bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df',
'99ab7a0d6a31feb411158184b5acadb8325a2c7e82a55cd709de7771ef6cd3b5',
'3082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e75626279205'
. '0696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e'
. '756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200'
. '048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b'
. '8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bc'
. 'd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df',
],
[
// This is the "CN=Yubico U2F EE Serial 13831167861" certificate as hex
// @see https://github.com/privacyidea/privacyidea/blob/v3.4.1/tests/test_lib_tokens_u2f.py#L22
// After 70d01010b038201010 the 0 is a 2 after transformation
'3082021c30820106a00302010202043866df75300b06092a864886f70d01010b302e312c302a0603550403132359756269636f205532462'
. '0526f6f742043412053657269616c203435373230303633313020170d3134303830313030303030305a180f32303530303930343030303030'
. '305a302b3129302706035504030c2059756269636f205532462045452053657269616c2031333833313136373836313059301306072a8648ce'
. '3d020106082a8648ce3d03010703420004378dfc740c739b94724ed3d523b9b876810656c13de86fafaecf38d90f55e2c80a1bfe0b30dc53b35'
. 'de7d045b96dcb8f2bf94fa8e0b903163c7f6edc2e487b71a3123010300e060a2b0601040182c40a01010400300b06092a864886f70d01010b0'
. '3820101021a4764ca0089cf92adb87fa848538e72cc3efdbb34792943047b8216a939baf4c113562a345b61475979697947bce671aa6a7c06'
. '796ed4ebb1b8fd602719b71deb3cf642e98db1d9666ff01e6db74f45af7967c046d6e6ff4b4e09a3141834b69af16465ccdecf3a0a809c0aa'
. '49a7b1943f5bd4e3dae3bdccfde6a713a49269eacfb3f9cede0ba79c6bbfba75e6118e20f0f957ea61eed52688226cab42df791037e97eda5e'
. '2df6029d2bb7fc327e745e7f9f5862bed29b068cb972a36c86522deb2c7196533335ddfaeb8b6fa0db5026aca845419061aa4d17c070e98fa2'
. 'fd671d4acd0c290e474a1b4783ec246e0f89a9887c0a4d7a85c662919ba24ea7b9c',
'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f',
'3082021c30820106a00302010202043866df75300b06092a864886f70d01010b302e312c302a0603550403132359756269636f2055324620526'
. 'f6f742043412053657269616c203435373230303633313020170d3134303830313030303030305a180f32303530303930343030303030305a30'
. '2b3129302706035504030c2059756269636f205532462045452053657269616c2031333833313136373836313059301306072a8648ce3d02010'
. '6082a8648ce3d03010703420004378dfc740c739b94724ed3d523b9b876810656c13de86fafaecf38d90f55e2c80a1bfe0b30dc53b35de7d045'
. 'b96dcb8f2bf94fa8e0b903163c7f6edc2e487b71a3123010300e060a2b0601040182c40a01010400300b06092a864886f70d01010b038201010'
. '01a4764ca0089cf92adb87fa848538e72cc3efdbb34792943047b8216a939baf4c113562a345b61475979697947bce671aa6a7c06796ed4ebb1'
. 'b8fd602719b71deb3cf642e98db1d9666ff01e6db74f45af7967c046d6e6ff4b4e09a3141834b69af16465ccdecf3a0a809c0aa49a7b1943f5b'
. 'd4e3dae3bdccfde6a713a49269eacfb3f9cede0ba79c6bbfba75e6118e20f0f957ea61eed52688226cab42df791037e97eda5e2df6029d2bb7f'
. 'c327e745e7f9f5862bed29b068cb972a36c86522deb2c7196533335ddfaeb8b6fa0db5026aca845419061aa4d17c070e98fa2fd671d4acd0c29'
. '0e474a1b4783ec246e0f89a9887c0a4d7a85c662919ba24ea7b9c',
],
];
}
/**
* @dataProvider dataProviderForFixSignatureUnusedBits
*/
public function testFixSignatureUnusedBits(
string $inputSignatureBlock,
string $signatureHash,
string $outputSignatureBlock
): void {
$signature = hex2bin($inputSignatureBlock);
$this->assertSame($signatureHash, hash('sha256', $signature));
$u2f = self::getClassMethod(U2FServer::class, 'fixSignatureUnusedBits');
$output = bin2hex($u2f->invokeArgs(new U2FServer(), [$signature]));
$this->assertSame($output, $outputSignatureBlock);
}
public function testBase64UEncodeDecode(): void
{
$shortBlob = 'Salut';
$u2f = self::getClassMethod(U2FServer::class, 'base64uEncode');
$encoded = $u2f->invokeArgs(new U2FServer(), [$shortBlob]);
$this->assertNotEmpty($encoded);
$this->assertSame('U2FsdXQ', $encoded);
$u2f = self::getClassMethod(U2FServer::class, 'base64uDecode');
$decoded = $u2f->invokeArgs(new U2FServer(), [$encoded]);
$this->assertNotEmpty($decoded);
$this->assertSame($shortBlob, $decoded);
$longBlob = '&àçècmm!:************************************************************';
$longBlob .= '^$ùzefzef:ezf:ze;fzefilqsnéà_è(_yà"tjzifzpofkzof,zlgugealuvnskqjvneruieg';
$u2f = self::getClassMethod(U2FServer::class, 'base64uEncode');
$encoded = $u2f->invokeArgs(new U2FServer(), [$longBlob]);
$this->assertNotEmpty($encoded);
$this->assertSame(
'JsOgw6fDqGNtbSE6KioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKio'
. 'qKioqKioqKioqKioqXiTDuXplZnplZjplemY6emU7ZnplZmlscXNuw6nDoF_DqChfecOgInRqemlmen'
. 'BvZmt6b2YsemxndWdlYWx1dm5za3Fqdm5lcnVpZWc',
$encoded
);
$u2f = self::getClassMethod(U2FServer::class, 'base64uDecode');
$decoded = $u2f->invokeArgs(new U2FServer(), [$encoded]);
$this->assertNotEmpty($decoded);
$this->assertSame($longBlob, $decoded);
}
/**
* @group openssl
*/
public function testCheckOpenSSLVersion(): void
{
$u2f = self::getClassMethod(U2FServer::class, 'checkOpenSSLVersion');
$goodVersion = $u2f->invokeArgs(new U2FServer(), []);
$this->assertTrue($goodVersion);
}
/**
* @group file-system
*/
public function testGetCerts(): void
{
$tempDirName = tempnam(sys_get_temp_dir(), '_testGetCerts');
unlink($tempDirName); // This is a file for now
mkdir($tempDirName); // And now a directory
$tmpFile = tempnam($tempDirName, 'cert_');
$u2f = self::getClassMethod(U2FServer::class, 'getCerts');
$filesList = $u2f->invokeArgs(new U2FServer(), [$tempDirName]);
$this->assertSame(
[
$tmpFile,
],
$filesList
);
unlink($tmpFile);
rmdir($tempDirName);
}
public function testPublicKeyToPem(): void
{
$u2f = self::getClassMethod(U2FServer::class, 'publicKeyToPem');
$pemKey = $u2f->invokeArgs(
new U2FServer(),
[
'',
]
);
$this->assertNull($pemKey);
$pemKeyWrongStart = $u2f->invokeArgs(
new U2FServer(),
[
'd',
]
);
$this->assertNull($pemKeyWrongStart);
$pemKeyWrongLength = $u2f->invokeArgs(
new U2FServer(),
[
"\x04",
]
);
$this->assertNull($pemKeyWrongLength);
$pemKeyWrongLength = $u2f->invokeArgs(
new U2FServer(),
[
"\x04" . str_repeat('*', 63),
]
);
$this->assertNull($pemKeyWrongLength);
$pemKeyOkay = $u2f->invokeArgs(
new U2FServer(),
[
// Public key for "CN=PilotGnubby-0.4.1-47901280001155957352"
// Value shown by KSE
hex2bin(
'048D617E65C9508E64BCC5673AC82A6799DA3C1446682C258C463FFFDF58DFD2FA3E6C378B5'
. '3D795C4A4DFFB4199EDD7862F23ABAF0203B4B8911BA0569994E101'
),
]
);
$this->assertSame(
// Value shown by KSE
'-----BEGIN PUBLIC KEY-----' . "\r\n"
. 'MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEjWF+ZclQjmS8xWc6yCpnmdo8FEZo' . "\r\n"
. 'LCWMRj//31jf0vo+bDeLU9eVxKTf+0GZ7deGLyOrrwIDtLiRG6BWmZThAQ==' . "\r\n"
. '-----END PUBLIC KEY-----',
$pemKeyOkay
);
}
public function testMakeAuthentication(): void
{
$regs = [
(object) [
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 3,
],
];
$auths = U2FServer::makeAuthentication(
$regs,
$this->appId
);
$this->assertSame(
[
[
'version' => 'U2F_V2',
'challenge' => $auths[0]->challenge(),
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
],
],
json_decode(json_encode($auths), true)
);
}
public function testAuthenticate(): void
{
$regs = [
(object) [
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 3,
],
];
$reqs = [
new SignRequest(
[
'challenge' => $this->challenge,
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
]
),
];
$this->assertSame('U2F_V2', $reqs[0]->version());
$response = (object) [
'signatureData' => $this->signatureData,
'clientData' => $this->clientData,
'keyHandle' => $this->keyHandle,
'errorCode' => 0,
];
$auth = U2FServer::authenticate(
$reqs,
$regs,
$response
);
$this->assertSame(
[
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 4,
],
(array) $auth
);
$this->assertEquals(4, $auth->counter);
}
public function testMakeRegistration(): void
{
$regs = [
(object) [
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 3,
],
];
$auth = U2FServer::makeRegistration(
$this->appId,
$regs
);
$this->assertSame(
[
'request' => [
'version' => 'U2F_V2',
'challenge' => $auth['request']->challenge(),
'appId' => $this->appId,
],
'signatures' => [
(new SignRequest(
[
'challenge' => $auth['signatures'][0]->challenge(),
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
]
))->jsonSerialize(),
],
],
json_decode(json_encode($auth), true)
);
}
public function testRegister(): void
{
$response = (object) [
'registrationData' => $this->registrationData,
'clientData' => $this->clientData2,
'errorCode' => 0,
];
$registration = U2FServer::register(
new RegistrationRequest('yKA0x075tjJ-GE7fKTfnzTOSaNUOWQxRd9TWz5aFOg8', $this->appId),
$response
);
$this->assertSame($this->keyHandle, $registration->getKeyHandle());
$this->assertSame(str_replace('\/', '/', $this->publicKey), $registration->getPublicKey());
$this->assertSame(str_replace('\/', '/', $this->certificate), $registration->getCertificate());
$this->assertLessThan(0, $registration->getCounter());
}
public function testRegisterAttestationFail(): void
{
$this->expectExceptionMessage('Attestation signature does not match');
$this->expectExceptionCode(U2FException::ATTESTATION_SIGNATURE);
$this->expectException(U2FException::class);
$response = (object) [
// Alter the data
'registrationData' => str_replace('DY8XvKbPwMuBVrOSO-ayvT', 'DY8XvKbPaMuBVrOSO-ayvT', $this->registrationData),
'clientData' => $this->clientData2,
'errorCode' => 0,
];
U2FServer::register(
new RegistrationRequest('yKA0x075tjJ-GE7fKTfnzTOSaNUOWQxRd9TWz5aFOg8', $this->appId),
$response
);
}
public function testRegisterChallengeMismatch(): void
{
$this->expectExceptionMessage('Registration challenge does not match');
$this->expectExceptionCode(U2FException::UNMATCHED_CHALLENGE);
$this->expectException(U2FException::class);
$response = (object) [
'registrationData' => $this->registrationData,
'clientData' => $this->clientData2,
'errorCode' => 0,
];
$regReq = new RegistrationRequest('yKA0x088tff-GE7fKTfnzTOSaNUOWQxRd9TWz5aFOg8', $this->appId);
$this->assertSame('U2F_V2', $regReq->version());
U2FServer::register(
$regReq,
$response
);
}
public function testAuthenticateNoChallengeMatch(): void
{
$this->expectExceptionMessage('No matching request found');
$this->expectExceptionCode(U2FException::NO_MATCHING_REQUEST);
$this->expectException(U2FException::class);
$regs = [
(object) [
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 3,
],
];
$reqs = [
new SignRequest(
[
'challenge' => 'fEnc9oV79EaBgK5BoNERU5gPKM2XGYWrz4fUjgc0000',
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
]
),
];
$response = (object) [
'signatureData' => $this->signatureData,
'clientData' => $this->clientData,
'keyHandle' => $this->keyHandle,
'errorCode' => 0,
];
U2FServer::authenticate(
$reqs,
$regs,
$response
);
}
public function testAuthenticateLowCounter(): void
{
$this->expectExceptionMessage('Counter too low.');
$this->expectExceptionCode(U2FException::COUNTER_TOO_LOW);
$this->expectException(U2FException::class);
$regs = [
(object) [
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 5,
],
];
$reqs = [
new SignRequest(
[
'challenge' => $this->challenge,
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
]
),
];
$response = (object) [
'signatureData' => $this->signatureData,
'clientData' => $this->clientData,
'keyHandle' => $this->keyHandle,
'errorCode' => 0,
];
U2FServer::authenticate(
$reqs,
$regs,
$response
);
}
public function testAuthenticateFail(): void
{
$this->expectExceptionMessage('Authentication failed');
$this->expectExceptionCode(U2FException::AUTHENTICATION_FAILURE);
$this->expectException(U2FException::class);
$regs = [
(object) [
'keyHandle' => $this->keyHandle,
'publicKey' => $this->publicKey,
'certificate' => $this->certificate,
'counter' => 5,
],
];
$reqs = [
new SignRequest(
[
'challenge' => $this->challenge,
'keyHandle' => $this->keyHandle,
'appId' => $this->appId,
]
),
];
$response = (object) [
// Alter the data
'signatureData' => str_replace('SUAng==', 'SUwww==', $this->signatureData),
'clientData' => $this->clientData,
'keyHandle' => $this->keyHandle,
'errorCode' => 0,
];
U2FServer::authenticate(
$reqs,
$regs,
$response
);
}
public function testRegisterUserAgentError(): void
{
$this->expectExceptionMessage('User-agent returned error. Error code: 1');
$this->expectExceptionCode(U2FException::BAD_UA_RETURNING);
$this->expectException(U2FException::class);
$response = (object) [
'errorCode' => 1,
];
$regReq = new RegistrationRequest('ffffffffffffffffffffffffff', $this->appId);
$this->assertSame('U2F_V2', $regReq->version());
U2FServer::register(
$regReq,
$response
);
}
public function testAuthenticateNotAnObject(): void
{
$this->expectExceptionMessage('$response of authenticate() method only accepts object.');
$this->expectException(InvalidArgumentException::class);
U2FServer::authenticate(
[],
[],
[]
);
}
public function testRegisterNotAnObject(): void
{
$this->expectExceptionMessage('$response of register() method only accepts object.');
$this->expectException(InvalidArgumentException::class);
U2FServer::register(
new RegistrationRequest('ffffffffffffffffffffffffff', $this->appId),
[
'errorCode' => 0,
]
);
}
public function testRegisterNotABoolean(): void
{
$this->expectExceptionMessage('$include_cert of register() method only accepts boolean.');
$this->expectException(InvalidArgumentException::class);
U2FServer::register(
new RegistrationRequest('ffffffffffffffffffffffffff', $this->appId),
(object) [
'errorCode' => 0,
],
null,
null
);
}
public function testAuthenticateUserAgentError(): void
{
$this->expectExceptionMessage('User-agent returned error. Error code: 1');
$this->expectExceptionCode(U2FException::BAD_UA_RETURNING);
$this->expectException(U2FException::class);
U2FServer::authenticate(
[],
[],
(object) [
'errorCode' => 1,
]
);
}
public function testMakeBadAuthentication(): void
{
$this->expectExceptionMessage('$registrations of makeAuthentication() method only accepts array of object.');
$this->expectException(\Exception::class);
U2FServer::makeAuthentication(
[
[],
],
$this->appId
);
}
}