Update website

This commit is contained in:
Guilhem Lavaux 2024-11-19 08:02:04 +01:00
parent 4413528994
commit 1d90fbf296
6865 changed files with 1091082 additions and 0 deletions

View file

@ -0,0 +1,52 @@
# 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

View file

@ -0,0 +1,26 @@
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.

View file

@ -0,0 +1,452 @@
# U2F-php-server
[![Latest Stable Version](https://img.shields.io/packagist/v/code-lts/u2f-php-server.svg?style=flat-square)](https://packagist.org/packages/code-lts/u2f-php-server)
[![GitHub license](https://img.shields.io/github/license/code-lts/U2F-php-server?style=flat-square)](LICENCE)
[![codecov](https://codecov.io/gh/code-lts/U2F-php-server/branch/main/graph/badge.svg?token=y0ssZvgEPn)](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
<?php
require __DIR__ . '/vendor/autoload.php';
use CodeLts\U2F\U2FServer\U2FServer as U2F;
var_dump(U2F::checkOpenSSLVersion());
```
---
### Registration Code
#### Registration Step 1:
**Starting the registration process:**
We assume that user has successfully authenticated and wishes to register.
```php
<?php
require __DIR__ . '/vendor/autoload.php';
use CodeLts\U2F\U2FServer\U2FServer as U2F;
session_start();
// This can be anything, but usually easier if you choose your applications domain and top level domain.
$appId = 'yourdomain.tld';
// Call the makeRegistration method, passing in the app ID
$registrationData = U2F::makeRegistration($appId);
// Store the request for later
$_SESSION['registrationRequest'] = $registrationData['request'];
// Extract the request and signatures, JSON encode them so we can give the data to our javaScript magic
$jsRequest = json_encode($registrationData['request']);
$jsSignatures = json_encode($registrationData['signatures']);
// now pass the data to a fictitious view.
echo View::make('template/location/u2f-registration.html', [
'jsRequest' => $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
<html>
<head>
<title>U2F Key Registration</title>
</head>
<body>
<h1>U2F Registration</h1>
<h2>Please enter your FIDO U2F device into your computer's USB port. Then confirm registration on the device.</h2>
<div style="display:none;">
<form id="u2f_submission" method="post" action="auth/u2f-registration/confirm">
<input id="u2f_registration_response" name="registration_response" value="" />
</form>
</div>
<script type="javascript" src="https://raw.githubusercontent.com/google/u2f-ref-code/master/u2f-gae-demo/war/js/u2f-api.js"></script>
<script>
setTimeout(function() {
// A magic JS function that talks to the USB device. This function will keep polling for the USB device until it finds one.
u2f.register([<?php echo $jsRequest ?>], <?php echo $jsSignatures ?>], function(data) {
// Handle returning error data
if(data.errorCode && errorCode != 0) {
alert('registration failed with error: ' + data.errorCode);
// Or handle the error however you'd like.
return;
}
// On success process the data from USB device to send to the server
var registration_response = JSON.stringify(data);
// Get the form items so we can send data back to the server
var form = document.getElementById('u2f_submission');
var response = document.getElementById('u2f_registration_response');
// Fill and submit form.
response.value = JSON.stringify(registration_response);
form.submit();
});
}, 1000);
</script>
</body>
</html>
```
#### 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
<?php
require('vendor/autoload.php');
use CodeLts\U2F\U2FServer\U2FServer as U2F;
session_start();
// Fictitious function representing getting the authenticated user object
$user = getAuthenticatedUser();
try {
// Validate the registration response against the registration request.
// The output are the credentials you need to store for U2F authentication.
$validatedRegistration = U2F::register(
$_SESSION['registrationRequest'],
json_decode($_POST['u2f_registration_response'])
);
// Fictitious function representing the storing of the validated U2F registration data against the authenticated user.
$user->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
<?php
require('vendor/autoload.php');
use CodeLts\U2F\U2FServer\U2FServer as U2F;
session_start();
// Fictitious function representing getting the authenticated user object
$user = getAuthenticatedUser();
// Fictitious function, get U2F registrations associated with the user
$registrations = $user->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
<html>
<head>
<title>U2F Key Authentication</title>
</head>
<body>
<h1>U2F Authentication</h1>
<h2>Please enter your FIDO U2F device into your computer's USB port. Then confirm authentication on the device.</h2>
<div style="display:none;">
<form id="u2f_submission" method="post" action="auth/u2f-authentication/confirm">
<input id="u2f_authentication_response" name="authentication_response" value="" />
</form>
</div>
<script type="javascript" src="https://raw.githubusercontent.com/google/u2f-ref-code/master/u2f-gae-demo/war/js/u2f-api.js"></script>
<script>
setTimeout(function() {
// Magic JavaScript talking to your HID
u2f.sign(<?php echo $authenticationRequest; ?>, function(data) {
// Handle returning error data
if(data.errorCode && errorCode != 0) {
alert('Authentication failed with error: ' + data.errorCode);
// Or handle the error however you'd like.
return;
}
// On success process the data from USB device to send to the server
var authentication_response = JSON.stringify(data);
// Get the form items so we can send data back to the server
var form = document.getElementById('u2f_submission');
var response = document.getElementById('u2f_authentication_response');
// Fill and submit form.
response.value = JSON.stringify(authentication_response);
form.submit();
});
}, 1000);
</script>
</body>
</html>
```
#### Authentication Step 3:
**Validation**
This is the last stage of authentication. Validate the authentication response data against the original request data.
```php
<?php
require('vendor/autoload.php');
use CodeLts\U2F\U2FServer\U2FServer as U2F;
session_start();
// Fictitious function representing getting the authenticated user object
$user = authenticatedUser();
// Fictitious function, get U2F registrations associated with the user
$registrations = $user->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)

View file

@ -0,0 +1,50 @@
{
"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"
]
}
}

View file

@ -0,0 +1,72 @@
<?php
namespace CodeLts\U2F\U2FServer;
class Registration
{
/** The key handle of the registered authenticator */
protected $keyHandle;
/** The public key of the registered authenticator */
protected $publicKey;
/** The attestation certificate of the registered authenticator */
protected $certificate;
/** The counter associated with this registration */
protected $counter = -1;
/**
* @param string $keyHandle
*/
public function setKeyHandle($keyHandle)
{
$this->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;
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace CodeLts\U2F\U2FServer;
class RegistrationRequest implements \JsonSerializable
{
/** @var string Protocol version */
protected $version = U2FServer::VERSION;
/** @var string Registration challenge */
protected $challenge;
/** @var string Application id */
protected $appId;
/**
* @param string $challenge
* @param string $appId
*/
public function __construct($challenge, $appId)
{
$this->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,
];
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace CodeLts\U2F\U2FServer;
class SignRequest implements \JsonSerializable
{
/** @var string Protocol version */
protected $version = U2FServer::VERSION;
/** @var string Authentication challenge */
protected $challenge;
/** @var string Key handle of a registered authenticator */
protected $keyHandle;
/** @var string Application id */
protected $appId;
public function __construct(array $parameters)
{
$this->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,
];
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace CodeLts\U2F\U2FServer;
class U2FException extends \Exception
{
/**
* Error for the authentication message not matching any outstanding
* authentication request
*/
public const NO_MATCHING_REQUEST = 1;
/** Error for the authentication message not matching any registration */
public const NO_MATCHING_REGISTRATION = 2;
/**
* Error for the signature on the authentication message not verifying with
* the correct key
*/
public const AUTHENTICATION_FAILURE = 3;
/** Error for the challenge in the registration message not matching the
* registration challenge */
public const UNMATCHED_CHALLENGE = 4;
/**
* Error for the attestation signature on the registration message not
* verifying
*/
public const ATTESTATION_SIGNATURE = 5;
/** Error for the attestation verification not verifying */
public const ATTESTATION_VERIFICATION = 6;
/** Error for not getting good random from the system */
public const BAD_RANDOM = 7;
/** Error when the counter is lower than expected */
public const COUNTER_TOO_LOW = 8;
/** Error decoding public key */
public const PUBKEY_DECODE = 9;
/** Error user-agent returned error */
public const BAD_UA_RETURNING = 10;
/** Error old OpenSSL version */
public const OLD_OPENSSL = 11;
/**
* Override constructor and make message and code mandatory
* @param string $message
* @param int $code
* @param \Exception|null $previous
*/
public function __construct($message, $code, ?\Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View file

@ -0,0 +1,440 @@
<?php
namespace CodeLts\U2F\U2FServer;
class U2FServer
{
/** Constant for the version of the u2f protocol */
public const VERSION = 'U2F_V2';
/** @internal */
public const PUBKEY_LEN = 65;
/*
* NOTE: If you are lucky and can match this CNs to the hashes please also add it to
* the existing test case provider
* "CN=Yubico U2F EE Serial 776137165",
* "CN=Yubico U2F EE Serial 1086591525",
* "CN=Yubico U2F EE Serial 1973679733",
* "CN=Yubico U2F EE Serial 13503277888",
* "CN=Yubico U2F EE Serial 14803321578"
*/
/**
* @internal
* @see https://books.google.fr/books?id=SF68CwAAQBAJ&lpg=PT96&ots=PCLmrWyu2F&hl=fr&pg=PT96#v=onepage&q&f=false
* @see https://github.com/Yubico/python-u2flib-server/issues/15#issue-107916981
*/
private static $FIXCERTS = [
'349bca1031f8c82c4ceca38b9cebf1a69df9fb3b94eed99eb3fb9aa3822d26e8',
'dd574527df608e47ae45fbba75a2afdd5c20fd94a02419381813cd55a2a3398f', // "CN=Yubico U2F EE Serial 13831167861"
'1d8764f0f7cd1352df6150045c8f638e517270e8b5dda1c63ade9c2280240cae',
'd0edc9a91a1677435a953390865d208c55b3183c6759c9b5a7ff494c322558eb',
'6073c436dcd064a48127ddbf6032ac1a66fd59a0c24434f070d4e564c124c897',
'ca993121846c464d666096d35f13bf44c1b05af205f9b4a1e00cf6cc10c5e511',
];
/**
* @throws U2FException If OpenSSL older than 1.0.0 is used
*/
public static function checkOpenSSLVersion()
{
if (OPENSSL_VERSION_NUMBER < 0x10000000) {
throw new U2FException(
'OpenSSL has to be at least version 1.0.0, this is ' . OPENSSL_VERSION_TEXT,
U2FException::OLD_OPENSSL
);
}
return true;
}
/**
* Called to get a registration request to send to a user.
* Returns an array of one registration request and a array of sign requests.
*
* @param string $appId Application id for the running application, Basically the app's URL
* @param stdClass[] $registrations List of current registrations for this
* user, to prevent the user from registering the same authenticator several
* times.
* @return array<string,RegistrationRequest|SignRequest[]> 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;
}
}