mirror of
https://github.com/getnamingo/registry.git
synced 2025-05-13 16:16:59 +02:00
WebAuthn registration completed
This commit is contained in:
parent
3684970ff9
commit
810d0cc7d1
6 changed files with 166 additions and 80 deletions
|
@ -5,7 +5,6 @@ namespace App\Controllers;
|
||||||
use Psr\Http\Message\ResponseInterface as Response;
|
use Psr\Http\Message\ResponseInterface as Response;
|
||||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||||
use Psr\Container\ContainerInterface;
|
use Psr\Container\ContainerInterface;
|
||||||
use lbuchs\WebAuthn\WebAuthn;
|
|
||||||
|
|
||||||
class ProfileController extends Controller
|
class ProfileController extends Controller
|
||||||
{
|
{
|
||||||
|
@ -14,11 +13,25 @@ class ProfileController extends Controller
|
||||||
public function __construct() {
|
public function __construct() {
|
||||||
$rpName = 'Namingo';
|
$rpName = 'Namingo';
|
||||||
$rpId = envi('APP_DOMAIN');
|
$rpId = envi('APP_DOMAIN');
|
||||||
|
$formats = [
|
||||||
|
'android-key',
|
||||||
|
'android-safetynet',
|
||||||
|
'apple',
|
||||||
|
'fido-u2f',
|
||||||
|
'none',
|
||||||
|
'packed',
|
||||||
|
'tpm'
|
||||||
|
];
|
||||||
|
|
||||||
$this->webAuthn = new Webauthn($rpName, $rpId);
|
$this->webAuthn = new \lbuchs\WebAuthn\WebAuthn($rpName, $rpId, $formats);
|
||||||
|
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/solo.pem');
|
||||||
// Additional configuration for Webauthn can go here
|
$this->webAuthn->addRootCertificates(envi('APP_ROOT').'/vendor/lbuchs/webauthn/_test/rootCertificates/apple.pem');
|
||||||
// Example: setting the public key credential parameters, user verification level, etc.
|
$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)
|
public function profile(Request $request, Response $response)
|
||||||
|
@ -56,8 +69,14 @@ class ProfileController extends Controller
|
||||||
'SELECT tfa_enabled FROM users WHERE id = ? LIMIT 1',
|
'SELECT tfa_enabled FROM users WHERE id = ? LIMIT 1',
|
||||||
[$userId]
|
[$userId]
|
||||||
);
|
);
|
||||||
|
$is_weba_activated = $db->select(
|
||||||
|
'SELECT * FROM users_webauthn WHERE user_id = ?',
|
||||||
|
[$userId]
|
||||||
|
);
|
||||||
if ($is_2fa_activated) {
|
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]);
|
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 {
|
} 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]);
|
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)
|
public function getRegistrationChallenge(Request $request, Response $response)
|
||||||
{
|
{
|
||||||
global $container;
|
|
||||||
$userName = $_SESSION['auth_username'];
|
$userName = $_SESSION['auth_username'];
|
||||||
$userEmail = $_SESSION['auth_email'];
|
$userEmail = $_SESSION['auth_email'];
|
||||||
$userId = $_SESSION['auth_user_id'];
|
$userId = $_SESSION['auth_user_id'];
|
||||||
|
$hexUserId = dechex($userId);
|
||||||
// Convert the user ID to a hexadecimal string
|
// Ensure even length for the hexadecimal string
|
||||||
$userIdHex = dechex($userId);
|
if(strlen($hexUserId) % 2 != 0){
|
||||||
// Pad with a leading zero if the length is odd
|
$hexUserId = '0' . $hexUserId;
|
||||||
if (strlen($userIdHex) % 2 !== 0) {
|
|
||||||
$userIdHex = '0' . $userIdHex;
|
|
||||||
}
|
}
|
||||||
|
$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));
|
$response->getBody()->write(json_encode($createArgs));
|
||||||
|
$challenge = $this->webAuthn->getChallenge();
|
||||||
|
$_SESSION['challenge_data'] = $challenge->getBinaryString();
|
||||||
|
|
||||||
return $response->withHeader('Content-Type', 'application/json');
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
}
|
}
|
||||||
|
|
||||||
public function verifyRegistration(Request $request, Response $response)
|
public function verifyRegistration(Request $request, Response $response)
|
||||||
{
|
{
|
||||||
|
$challengeData = $_SESSION['challenge_data'];
|
||||||
|
$challenge = new \lbuchs\WebAuthn\Binary\ByteBuffer($challengeData);
|
||||||
|
|
||||||
global $container;
|
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 {
|
try {
|
||||||
// Decode the incoming data
|
// Decode the incoming data
|
||||||
$clientDataJSON = base64_decode($data->response->clientDataJSON);
|
$clientDataJSON = base64_decode($data->clientDataJSON);
|
||||||
$attestationObject = base64_decode($data->response->attestationObject);
|
$attestationObject = base64_decode($data->attestationObject);
|
||||||
|
|
||||||
// Retrieve the challenge from the session
|
// Retrieve the challenge from the session
|
||||||
$challenge = $_SESSION['webauthn_challenge'];
|
//$challenge = $_SESSION['challenge'];
|
||||||
|
|
||||||
// Process the WebAuthn response
|
// 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
|
// Store the credential data in the database
|
||||||
$db = $container->get('db');
|
$db = $container->get('db');
|
||||||
|
$counter = is_null($credential->signatureCounter) ? 0 : $credential->signatureCounter;
|
||||||
$db->insert(
|
$db->insert(
|
||||||
'users_webauthn',
|
'users_webauthn',
|
||||||
[
|
[
|
||||||
'user_id' => $_SESSION['auth_user_id'],
|
'user_id' => $_SESSION['auth_user_id'],
|
||||||
'credential_id' => base64_encode($credential->credentialId), // Binary data encoded in Base64
|
'credential_id' => base64_encode($credential->credentialId),
|
||||||
'public_key' => $credential->publicKey, // Text data
|
'public_key' => $credential->credentialPublicKey,
|
||||||
'attestation_object' => base64_encode($credential->attestationObject), // Binary data encoded in Base64
|
'attestation_object' => base64_encode($attestationObject),
|
||||||
'sign_count' => $credential->signCount // Integer
|
'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
|
// Send success response
|
||||||
$response->getBody()->write(json_encode(['success' => true]));
|
$response->getBody()->write(json_encode($return));
|
||||||
return $response->withHeader('Content-Type', 'application/json');
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
// Handle error, return an appropriate response
|
// Handle error, return an appropriate response
|
||||||
|
|
|
@ -13,6 +13,7 @@ return [
|
||||||
'name' => $_ENV['APP_NAME'] ?? 'CP',
|
'name' => $_ENV['APP_NAME'] ?? 'CP',
|
||||||
'url' => $_ENV['APP_URL'] ?? 'http://localhost',
|
'url' => $_ENV['APP_URL'] ?? 'http://localhost',
|
||||||
'domain' => $_ENV['APP_DOMAIN'] ?? 'example.com',
|
'domain' => $_ENV['APP_DOMAIN'] ?? 'example.com',
|
||||||
|
'root' => $_ENV['APP_ROOT'] ?? '/var/www/cp',
|
||||||
'timezone' => $_ENV['TIME_ZONE'] ?? 'UTC',
|
'timezone' => $_ENV['TIME_ZONE'] ?? 'UTC',
|
||||||
'default' => $_ENV['DB_DRIVER'] ?? 'mysql',
|
'default' => $_ENV['DB_DRIVER'] ?? 'mysql',
|
||||||
'connections' => [
|
'connections' => [
|
||||||
|
|
|
@ -2,6 +2,7 @@ APP_NAME='CP'
|
||||||
APP_ENV=public
|
APP_ENV=public
|
||||||
APP_URL=https://cp.example.com
|
APP_URL=https://cp.example.com
|
||||||
APP_DOMAIN=example.com
|
APP_DOMAIN=example.com
|
||||||
|
APP_ROOT=/var/www/cp
|
||||||
|
|
||||||
DB_DRIVER=mysql
|
DB_DRIVER=mysql
|
||||||
DB_HOST=localhost
|
DB_HOST=localhost
|
||||||
|
|
|
@ -151,13 +151,25 @@
|
||||||
<table class="table table-striped">
|
<table class="table table-striped">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Device Name</th>
|
<th>Device/Browser Info</th>
|
||||||
<th>Registration Date</th>
|
<th>Registration Date</th>
|
||||||
<th>Action</th>
|
<th>Action</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<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>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
@ -188,56 +200,102 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
|
||||||
connectButton.addEventListener('click', async function() {
|
connectButton.addEventListener('click', async function() {
|
||||||
try {
|
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
|
// check browser support
|
||||||
const challenge = Uint8Array.from(atob(data.publicKey.challenge), c => c.charCodeAt(0));
|
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
|
||||||
const userId = Uint8Array.from(atob(data.publicKey.user.id), c => c.charCodeAt(0));
|
throw new Error('Browser not supported.');
|
||||||
|
}
|
||||||
|
|
||||||
// Modify the data object to use the decoded challenge and user ID
|
// get create args
|
||||||
data.publicKey.challenge = challenge;
|
let rep = await window.fetch('/webauthn/register/challenge', {method:'GET', cache:'no-cache'});
|
||||||
data.publicKey.user.id = userId;
|
const createArgs = await rep.json();
|
||||||
|
|
||||||
// Step 2: Call WebAuthn API to create credentials
|
// error handling
|
||||||
const credentials = await navigator.credentials.create(data);
|
if (createArgs.success === false) {
|
||||||
|
throw new Error(createArgs.msg || 'unknown error occured');
|
||||||
|
}
|
||||||
|
|
||||||
// Prepare credentials response
|
// replace binary base64 data with ArrayBuffer. a other way to do this
|
||||||
const publicKeyCredential = {
|
// is the reviver function of JSON.parse()
|
||||||
id: credentials.id,
|
recursiveBase64StrToArrayBuffer(createArgs);
|
||||||
rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))),
|
|
||||||
type: credentials.type,
|
// create credentials
|
||||||
response: {
|
const cred = await navigator.credentials.create(createArgs);
|
||||||
attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))),
|
|
||||||
clientDataJSON: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.clientDataJSON)))
|
// create object
|
||||||
},
|
const authenticatorAttestationResponse = {
|
||||||
// Include CSRF tokens in the payload
|
transports: cred.response.getTransports ? cred.response.getTransports() : null,
|
||||||
csrf_name: '{{ csrf_name }}',
|
clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
|
||||||
csrf_value: '{{ csrf_value }}'
|
attestationObject: cred.response.attestationObject ? arrayBufferToBase64(cred.response.attestationObject) : null
|
||||||
};
|
};
|
||||||
|
|
||||||
// Step 3: Send the credentials back to the server for verification
|
// check auth on server side
|
||||||
const verificationResponse = await fetch('/webauthn/register/verify', {
|
rep = await window.fetch('/webauthn/register/verify', {
|
||||||
method: 'POST',
|
method : 'POST',
|
||||||
headers: {
|
body : JSON.stringify(authenticatorAttestationResponse),
|
||||||
'Content-Type': 'application/json'
|
cache : 'no-cache'
|
||||||
},
|
|
||||||
body: JSON.stringify(publicKeyCredential)
|
|
||||||
});
|
});
|
||||||
|
const authenticatorAttestationServerResponse = await rep.json();
|
||||||
|
|
||||||
if(verificationResponse.ok) {
|
// prompt server response
|
||||||
alert('Registration successful!');
|
if (authenticatorAttestationServerResponse.success) {
|
||||||
window.location.reload();
|
//location.reload();
|
||||||
|
window.alert(authenticatorAttestationServerResponse.msg || 'registration success');
|
||||||
} else {
|
} else {
|
||||||
const errorData = await verificationResponse.json();
|
throw new Error(authenticatorAttestationServerResponse.msg);
|
||||||
alert('Registration failed: ' + (errorData.error || 'Unknown error'));
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
|
||||||
console.error('Error during WebAuthn registration:', error);
|
} catch (err) {
|
||||||
alert('Error during registration: ' + error.message);
|
//location.reload();
|
||||||
|
window.alert(err.message || 'unknown error occured');
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
||||||
|
recursiveBase64StrToArrayBuffer(obj[key]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
|
@ -539,6 +539,7 @@ CREATE TABLE IF NOT EXISTS `registry`.`users_webauthn` (
|
||||||
`public_key` TEXT NOT NULL,
|
`public_key` TEXT NOT NULL,
|
||||||
`attestation_object` BLOB,
|
`attestation_object` BLOB,
|
||||||
`sign_count` BIGINT NOT NULL,
|
`sign_count` BIGINT NOT NULL,
|
||||||
|
`user_agent` VARCHAR(512),
|
||||||
`created_at` DATETIME(3) DEFAULT CURRENT_TIMESTAMP,
|
`created_at` DATETIME(3) DEFAULT CURRENT_TIMESTAMP,
|
||||||
`last_used_at` DATETIME(3) DEFAULT CURRENT_TIMESTAMP,
|
`last_used_at` DATETIME(3) DEFAULT CURRENT_TIMESTAMP,
|
||||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||||
|
|
|
@ -509,6 +509,7 @@ CREATE TABLE IF NOT EXISTS registry.users_webauthn (
|
||||||
"public_key" TEXT NOT NULL,
|
"public_key" TEXT NOT NULL,
|
||||||
"attestation_object" BYTEA,
|
"attestation_object" BYTEA,
|
||||||
"sign_count" BIGINT NOT NULL,
|
"sign_count" BIGINT NOT NULL,
|
||||||
|
"user_agent" TEXT,
|
||||||
"created_at" TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
"created_at" TIMESTAMP(3) WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
"last_used_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)
|
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue