WebAuthn registration completed

This commit is contained in:
Pinga 2023-11-22 17:22:52 +02:00
parent 3684970ff9
commit 810d0cc7d1
6 changed files with 166 additions and 80 deletions

View file

@ -5,7 +5,6 @@ namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Container\ContainerInterface;
use lbuchs\WebAuthn\WebAuthn;
class ProfileController extends Controller
{
@ -14,11 +13,25 @@ class ProfileController extends Controller
public function __construct() {
$rpName = 'Namingo';
$rpId = envi('APP_DOMAIN');
$formats = [
'android-key',
'android-safetynet',
'apple',
'fido-u2f',
'none',
'packed',
'tpm'
];
$this->webAuthn = new Webauthn($rpName, $rpId);
// Additional configuration for Webauthn can go here
// Example: setting the public key credential parameters, user verification level, etc.
$this->webAuthn = new \lbuchs\WebAuthn\WebAuthn($rpName, $rpId, $formats);
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/solo.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/apple.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/yubico.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/hypersecu.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/globalSign.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/googleHardware.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/microsoftTpmCollection.pem');
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/mds');
}
public function profile(Request $request, Response $response)
@ -56,8 +69,14 @@ class ProfileController extends Controller
'SELECT tfa_enabled FROM users WHERE id = ? LIMIT 1',
[$userId]
);
$is_weba_activated = $db->select(
'SELECT * FROM users_webauthn WHERE user_id = ?',
[$userId]
);
if ($is_2fa_activated) {
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue]);
} else if ($is_weba_activated) {
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue, 'weba' => $is_weba_activated]);
} else {
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role, 'qrcodeDataUri' => $qrcodeDataUri, 'secret' => $secret, 'csrf_name' => $csrfName, 'csrf_value' => $csrfValue]);
}
@ -117,71 +136,76 @@ class ProfileController extends Controller
public function getRegistrationChallenge(Request $request, Response $response)
{
global $container;
$userName = $_SESSION['auth_username'];
$userEmail = $_SESSION['auth_email'];
$userId = $_SESSION['auth_user_id'];
// Convert the user ID to a hexadecimal string
$userIdHex = dechex($userId);
// Pad with a leading zero if the length is odd
if (strlen($userIdHex) % 2 !== 0) {
$userIdHex = '0' . $userIdHex;
$hexUserId = dechex($userId);
// Ensure even length for the hexadecimal string
if(strlen($hexUserId) % 2 != 0){
$hexUserId = '0' . $hexUserId;
}
$createArgs = $this->webAuthn->getCreateArgs(\hex2bin($hexUserId), $userName, $userName, 60*4, true, 'required', null);
// Convert the padded hexadecimal string to binary, then encode in Base64
$userIdBin = hex2bin($userIdHex);
$userIdBase64 = base64_encode($userIdBin);
// Generate the create arguments using the WebAuthn library
$createArgs = $this->webAuthn->getCreateArgs($userIdBase64, $userName, $userEmail, 60 * 4, 0, 'required', null);
// Encode the challenge in Base64
$base64Challenge = base64_encode($this->webAuthn->getChallenge());
// Set the challenge and user ID in the createArgs object
$createArgs->publicKey->challenge = $base64Challenge;
$createArgs->publicKey->user->id = $userIdBase64;
// Store the challenge in the session
$_SESSION['webauthn_challenge'] = $base64Challenge;
// Send the modified $createArgs to the client
$response->getBody()->write(json_encode($createArgs));
$challenge = $this->webAuthn->getChallenge();
$_SESSION['challenge_data'] = $challenge->getBinaryString();
return $response->withHeader('Content-Type', 'application/json');
}
public function verifyRegistration(Request $request, Response $response)
{
$challengeData = $_SESSION['challenge_data'];
$challenge = new \lbuchs\WebAuthn\Binary\ByteBuffer($challengeData);
global $container;
$data = json_decode($request->getBody()->getContents());
$data = json_decode($request->getBody()->getContents(), null, 512, JSON_THROW_ON_ERROR);
$userName = $_SESSION['auth_username'];
$userEmail = $_SESSION['auth_email'];
$userId = $_SESSION['auth_user_id'];
try {
// Decode the incoming data
$clientDataJSON = base64_decode($data->response->clientDataJSON);
$attestationObject = base64_decode($data->response->attestationObject);
$clientDataJSON = base64_decode($data->clientDataJSON);
$attestationObject = base64_decode($data->attestationObject);
// Retrieve the challenge from the session
$challenge = $_SESSION['webauthn_challenge'];
//$challenge = $_SESSION['challenge'];
// Process the WebAuthn response
$credential = $this->webAuthn->processCreate($clientDataJSON, $attestationObject, $challenge, true, true, false);
$credential = $this->webAuthn->processCreate($clientDataJSON, $attestationObject, $challenge, 'required', true, false);
// add user infos
$credential->userId = $userId;
$credential->userName = $userName;
$credential->userDisplayName = $userName;
// Store the credential data in the database
$db = $container->get('db');
$counter = is_null($credential->signatureCounter) ? 0 : $credential->signatureCounter;
$db->insert(
'users_webauthn',
[
'user_id' => $_SESSION['auth_user_id'],
'credential_id' => base64_encode($credential->credentialId), // Binary data encoded in Base64
'public_key' => $credential->publicKey, // Text data
'attestation_object' => base64_encode($credential->attestationObject), // Binary data encoded in Base64
'sign_count' => $credential->signCount // Integer
'credential_id' => base64_encode($credential->credentialId),
'public_key' => $credential->credentialPublicKey,
'attestation_object' => base64_encode($attestationObject),
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'sign_count' => $counter
]
);
$msg = 'registration success.';
if ($credential->rootValid === false) {
$msg = 'registration ok, but certificate does not match any of the selected root ca.';
}
$return = new \stdClass();
$return->success = true;
$return->msg = $msg;
// Send success response
$response->getBody()->write(json_encode(['success' => true]));
$response->getBody()->write(json_encode($return));
return $response->withHeader('Content-Type', 'application/json');
} catch (\Exception $e) {
// Handle error, return an appropriate response

View file

@ -13,6 +13,7 @@ return [
'name' => $_ENV['APP_NAME'] ?? 'CP',
'url' => $_ENV['APP_URL'] ?? 'http://localhost',
'domain' => $_ENV['APP_DOMAIN'] ?? 'example.com',
'root' => $_ENV['APP_ROOT'] ?? '/var/www/cp',
'timezone' => $_ENV['TIME_ZONE'] ?? 'UTC',
'default' => $_ENV['DB_DRIVER'] ?? 'mysql',
'connections' => [

View file

@ -2,6 +2,7 @@ APP_NAME='CP'
APP_ENV=public
APP_URL=https://cp.example.com
APP_DOMAIN=example.com
APP_ROOT=/var/www/cp
DB_DRIVER=mysql
DB_HOST=localhost

View file

@ -151,13 +151,25 @@
<table class="table table-striped">
<thead>
<tr>
<th>Device Name</th>
<th>Device/Browser Info</th>
<th>Registration Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- Dynamically populated rows go here -->
{% for device in weba %}
<tr>
<td>{{ device.user_agent }}</td>
<td>{{ device.created_at }}</td>
<td>
<a href="/path/to/action?deviceId={{ device.id }}">Edit</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="3">No devices found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
@ -188,56 +200,102 @@ document.addEventListener('DOMContentLoaded', function() {
connectButton.addEventListener('click', async function() {
try {
// Step 1: Get the registration challenge from the server
const response = await fetch('/webauthn/register/challenge');
const data = await response.json();
// Decode the challenge and user ID from Base64 to Uint8Array
const challenge = Uint8Array.from(atob(data.publicKey.challenge), c => c.charCodeAt(0));
const userId = Uint8Array.from(atob(data.publicKey.user.id), c => c.charCodeAt(0));
// check browser support
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
throw new Error('Browser not supported.');
}
// Modify the data object to use the decoded challenge and user ID
data.publicKey.challenge = challenge;
data.publicKey.user.id = userId;
// get create args
let rep = await window.fetch('/webauthn/register/challenge', {method:'GET', cache:'no-cache'});
const createArgs = await rep.json();
// Step 2: Call WebAuthn API to create credentials
const credentials = await navigator.credentials.create(data);
// error handling
if (createArgs.success === false) {
throw new Error(createArgs.msg || 'unknown error occured');
}
// Prepare credentials response
const publicKeyCredential = {
id: credentials.id,
rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))),
type: credentials.type,
response: {
attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))),
clientDataJSON: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.clientDataJSON)))
},
// Include CSRF tokens in the payload
csrf_name: '{{ csrf_name }}',
csrf_value: '{{ csrf_value }}'
// replace binary base64 data with ArrayBuffer. a other way to do this
// is the reviver function of JSON.parse()
recursiveBase64StrToArrayBuffer(createArgs);
// create credentials
const cred = await navigator.credentials.create(createArgs);
// create object
const authenticatorAttestationResponse = {
transports: cred.response.getTransports ? cred.response.getTransports() : null,
clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
attestationObject: cred.response.attestationObject ? arrayBufferToBase64(cred.response.attestationObject) : null
};
// Step 3: Send the credentials back to the server for verification
const verificationResponse = await fetch('/webauthn/register/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(publicKeyCredential)
// check auth on server side
rep = await window.fetch('/webauthn/register/verify', {
method : 'POST',
body : JSON.stringify(authenticatorAttestationResponse),
cache : 'no-cache'
});
const authenticatorAttestationServerResponse = await rep.json();
// prompt server response
if (authenticatorAttestationServerResponse.success) {
//location.reload();
window.alert(authenticatorAttestationServerResponse.msg || 'registration success');
} else {
throw new Error(authenticatorAttestationServerResponse.msg);
}
} catch (err) {
//location.reload();
window.alert(err.message || 'unknown error occured');
}
});
if(verificationResponse.ok) {
alert('Registration successful!');
window.location.reload();
/**
* convert RFC 1342-like base64 strings to array buffer
* @param {mixed} obj
* @returns {undefined}
*/
function recursiveBase64StrToArrayBuffer(obj) {
let prefix = '=?BINARY?B?';
let suffix = '?=';
if (typeof obj === 'object') {
for (let key in obj) {
if (typeof obj[key] === 'string') {
let str = obj[key];
if (str.substring(0, prefix.length) === prefix && str.substring(str.length - suffix.length) === suffix) {
str = str.substring(prefix.length, str.length - suffix.length);
let binary_string = window.atob(str);
let len = binary_string.length;
let bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
obj[key] = bytes.buffer;
}
} else {
const errorData = await verificationResponse.json();
alert('Registration failed: ' + (errorData.error || 'Unknown error'));
recursiveBase64StrToArrayBuffer(obj[key]);
}
} catch (error) {
console.error('Error during WebAuthn registration:', error);
alert('Error during registration: ' + error.message);
}
});
}
}
/**
* Convert a ArrayBuffer to Base64
* @param {ArrayBuffer} buffer
* @returns {String}
*/
function arrayBufferToBase64(buffer) {
let binary = '';
let bytes = new Uint8Array(buffer);
let len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa(binary);
}
});
</script>
{% endblock %}

View file

@ -539,6 +539,7 @@ CREATE TABLE IF NOT EXISTS `registry`.`users_webauthn` (
`public_key` TEXT NOT NULL,
`attestation_object` BLOB,
`sign_count` BIGINT NOT NULL,
`user_agent` VARCHAR(512),
`created_at` DATETIME(3) DEFAULT CURRENT_TIMESTAMP,
`last_used_at` DATETIME(3) DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)

View file

@ -509,6 +509,7 @@ CREATE TABLE IF NOT EXISTS registry.users_webauthn (
"public_key" TEXT NOT NULL,
"attestation_object" BYTEA,
"sign_count" BIGINT NOT NULL,
"user_agent" TEXT,
"created_at" TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
"last_used_at" TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)