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.
Base Library
https://github.com/Samyoul/U2F-php-server
Fido Test Suite (UTD)
https://github.com/Samyoul/U2F-php-UTD
Frameworks
Laravel https://github.com/Samyoul/U2F-Laravel-server
Yii https://github.com/Samyoul/U2F-Yii-server
CodeIgniter https://github.com/Samyoul/U2F-CodeIgniter-server
- Installation
- Requirements
- Terminology
- Recommended Datastore Structure
- Process Workflow
- Example Code
- Frameworks
- Licence
- Credits
composer require samyoul/u2f-php-server
A few things you need to know before working with this:
- OpenSSL You need at least OpenSSL 1.0.0 or higher.
- Client-side Handling You need to be able to communicate with a some kind of device.
- A HTTPS URL This is very important, without HTTPS U2F simply will not work.
- A Datastore 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).
This repository requires OpenSSL 1.0.0 or higher. For further details on installing OpenSSL please refer to the php manual http://php.net/manual/en/openssl.installation.php .
Also see Compatibility Code, to check if you have the correct version of OpenSSL installed, and are unsure how else to check.
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.
- Google already have this bit sorted : https://github.com/google/u2f-ref-code/blob/master/u2f-gae-demo/war/js/u2f-api.js
- Mastahyeti has created a repo dedicated to Google's JavaScript Client-side API : https://github.com/mastahyeti/u2f-api
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.
HID : Human Interface Device, like A USB Device like these things
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
- User navigates to a 2nd factor authentication page in your application.
... TODO add the rest of the registration process flow ...
- User navigates to their login page as they usually would, submits username and password.
- Server received POST request authentication data, normal username + password validation occurs
- 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.
- Application gets the user's registered signatures from the application datastore:
$registrations
. - Application gets its ID, usually the domain the application is accessible from:
$appId
- Application makes a
U2F::makeAuthentication($registrations, $appId)
call, the method returns an array ofSignRequest
objects:$authenticationRequest
. - Application JSON encodes the array and passes the data to the view
- When the browser loads the page the JavaScript fires the
u2f.sign(authenticationRequest, function(data){ // Callback logic })
function - The view will use JavaScript / Browser to poll the host machine's ports for a FIDO U2F device
- Once the HID has been found the JavaScript / Browser will send the sign request with data.
- The HID will prompt the user to authorise the sign request
- On success the HID returns authentication data
- The JavaScript receives the HID's returned data and passes it to the server
- The application takes the returned data passes it to the
U2F::authenticate($authenticationRequest, $registrations, $authenticationResponse)
method - If the method returns a registration and doesn't throw an Exception, authentication is complete.
- Set the user's session, inform the user of the success, and redirect them.
For a full working code example for this repository please see the dedicated example repository
You can also install it with the following:
$ git clone https://github.com/Samyoul/U2F-php-server-examples.git
$ cd u2f-php-server-examples
$ composer install
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
require('vendor/autoload.php');
use Samyoul\U2F\U2FServer\U2FServer as U2F;
var_dump(U2F::checkOpenSSLVersion());
Starting the registration process:
We assume that user has successfully authenticated and wishes to register.
<?php
require('vendor/autoload.php');
use Samyoul\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', compact("jsRequest", "jsSignatures"));
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>
<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>
Validation and Key Storage
This is the last stage of registration. Validate the registration response data against the original request data.
<?php
require('vendor/autoload.php');
use Samyoul\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', compact('userMessage'));
Starting the authentication process:
We assume that user has successfully authenticated and has previously registered to use FIDO U2F.
<?php
require('vendor/autoload.php');
use Samyoul\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', compact("authenticationRequest"));
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>
<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>
Validation
This is the last stage of authentication. Validate the authentication response data against the original request data.
<?php
require('vendor/autoload.php');
use Samyoul\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', compact('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
You can also install it with the following:
$ git clone https://github.com/Samyoul/U2F-php-server-examples.git
$ cd u2f-php-server-examples
$ composer install
See the dedicated repository : https://github.com/Samyoul/U2F-Laravel-server
Installation:
composer require u2f-laravel-server
See the dedicated repository : https://github.com/Samyoul/U2F-Yii-server
Installation:
composer require u2f-yii-server
See the dedicated repository : https://github.com/Samyoul/U2F-CodeIgniter-server
Installation:
composer require u2f-codeigniter-server
Your favourite php framework not in this list? Get coding and submit a pull request and get your framework extension included here.
The repository is licensed under a BSD license. Read details here
This repo was originally based on the Yubico php-u2flib-server https://github.com/Yubico/php-u2flib-server