mirror of
https://github.com/getnamingo/registry.git
synced 2025-06-29 15:43:23 +02:00
More work on 2FA and WebAuthn
This commit is contained in:
parent
6466545c90
commit
2b6bdc71e9
3 changed files with 125 additions and 75 deletions
|
@ -26,6 +26,10 @@ class ProfileController extends Controller
|
||||||
$username = $_SESSION['auth_username'];
|
$username = $_SESSION['auth_username'];
|
||||||
$email = $_SESSION['auth_email'];
|
$email = $_SESSION['auth_email'];
|
||||||
$status = $_SESSION['auth_status'];
|
$status = $_SESSION['auth_status'];
|
||||||
|
$tfa = new \RobThree\Auth\TwoFactorAuth('Namingo');
|
||||||
|
$secret = $tfa->createSecret();
|
||||||
|
$qrcodeDataUri = $tfa->getQRCodeImageAsDataUri($email, $secret);
|
||||||
|
|
||||||
if ($status == 0) {
|
if ($status == 0) {
|
||||||
$status = "Confirmed";
|
$status = "Confirmed";
|
||||||
} else {
|
} else {
|
||||||
|
@ -38,51 +42,77 @@ class ProfileController extends Controller
|
||||||
$role = "Unknown";
|
$role = "Unknown";
|
||||||
}
|
}
|
||||||
|
|
||||||
return view($response,'admin/profile/profile.twig',['email' => $email, 'username' => $username, 'status' => $status, 'role' => $role]);
|
global $container;
|
||||||
|
$csrfName = $container->get('csrf')->getTokenName();
|
||||||
|
$csrfValue = $container->get('csrf')->getTokenValue();
|
||||||
|
|
||||||
|
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]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getRegistrationChallenge(Request $request, Response $response)
|
public function getRegistrationChallenge(Request $request, Response $response)
|
||||||
{
|
{
|
||||||
$username = $_SESSION['auth_username'];
|
$userName = $_SESSION['auth_username'];
|
||||||
$userEmail = $_SESSION['auth_email'];
|
$userEmail = $_SESSION['auth_email'];
|
||||||
|
$userId = $_SESSION['auth_user_id'];
|
||||||
|
|
||||||
$challenge = $this->webAuthn->prepareChallengeForRegistration($username, $userEmail);
|
// Convert the user ID to a hexadecimal string
|
||||||
$_SESSION['webauthn_challenge'] = $challenge; // Store the challenge in the session
|
$userIdHex = dechex($userId);
|
||||||
|
// Pad with a leading zero if the length is odd
|
||||||
|
if (strlen($userIdHex) % 2 !== 0) {
|
||||||
|
$userIdHex = '0' . $userIdHex;
|
||||||
|
}
|
||||||
|
|
||||||
$response->getBody()->write(json_encode($challenge));
|
// 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));
|
||||||
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)
|
||||||
{
|
{
|
||||||
$data = json_decode($request->getBody()->getContents(), true);
|
$data = json_decode($request->getBody()->getContents());
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$credential = $this->webAuthn->processCreate($data, $_SESSION['webauthn_challenge']);
|
// Decode the incoming data
|
||||||
unset($_SESSION['webauthn_challenge']);
|
$clientDataJSON = base64_decode($data->response->clientDataJSON);
|
||||||
|
$attestationObject = base64_decode($data->response->attestationObject);
|
||||||
|
|
||||||
|
// Retrieve the challenge from the session
|
||||||
|
$challenge = $_SESSION['webauthn_challenge'];
|
||||||
|
|
||||||
|
// Process the WebAuthn response
|
||||||
|
$credential = $this->webAuthn->processCreate($clientDataJSON, $attestationObject, $challenge, true, true, false);
|
||||||
|
|
||||||
|
// Store the credential data in the database
|
||||||
$db = $this->container->get('db');
|
$db = $this->container->get('db');
|
||||||
|
$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
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
try {
|
// Send success response
|
||||||
$db->insert(
|
|
||||||
'users_webauthn',
|
|
||||||
[
|
|
||||||
'user_id' => $_SESSION['auth_user_id'],
|
|
||||||
'credential_id' => $credential->getCredentialId(), // Binary data
|
|
||||||
'public_key' => $credential->getPublicKey(), // Text data
|
|
||||||
'attestation_object' => $credential->getAttestationObject(), // Binary data
|
|
||||||
'sign_count' => $credential->getSignCount() // Integer
|
|
||||||
]
|
|
||||||
);
|
|
||||||
} catch (IntegrityConstraintViolationException $e) {
|
|
||||||
// Handle the case where the insert operation violates a constraint
|
|
||||||
// For example, a duplicate credential_id
|
|
||||||
throw new \Exception('Could not store WebAuthn credentials: ' . $e->getMessage());
|
|
||||||
} catch (Error $e) {
|
|
||||||
// Handle other database errors
|
|
||||||
throw new \Exception('Database error: ' . $e->getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
$response->getBody()->write(json_encode(['success' => true]));
|
$response->getBody()->write(json_encode(['success' => true]));
|
||||||
return $response->withHeader('Content-Type', 'application/json');
|
return $response->withHeader('Content-Type', 'application/json');
|
||||||
} catch (\Exception $e) {
|
} catch (\Exception $e) {
|
||||||
|
|
|
@ -37,7 +37,8 @@
|
||||||
"league/iso3166": "^4.3",
|
"league/iso3166": "^4.3",
|
||||||
"stripe/stripe-php": "^13.3",
|
"stripe/stripe-php": "^13.3",
|
||||||
"robthree/twofactorauth": "^2.1",
|
"robthree/twofactorauth": "^2.1",
|
||||||
"lbuchs/webauthn": "^2.1"
|
"lbuchs/webauthn": "^2.1",
|
||||||
|
"bacon/bacon-qr-code": "^2.0"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
|
|
|
@ -101,12 +101,23 @@
|
||||||
<p>Set up 2FA for additional security. Scan the QR code with your authentication app and enter the provided code below to verify.</p>
|
<p>Set up 2FA for additional security. Scan the QR code with your authentication app and enter the provided code below to verify.</p>
|
||||||
<!-- QR Code Placeholder -->
|
<!-- QR Code Placeholder -->
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<img src="path/to/qr-code.png" alt="2FA QR Code" class="img-fluid">
|
<img src="{{ qrcodeDataUri }}" alt="2FA QR Code" class="img-fluid">
|
||||||
|
</div>
|
||||||
|
<!-- Secret for Manual Entry -->
|
||||||
|
<div class="mb-3">
|
||||||
|
<p class="font-weight-bold">Manual Entry Secret</p>
|
||||||
|
<code>{{ secret|split(4)|join(' ') }}</code>
|
||||||
|
<small class="form-text text-muted">
|
||||||
|
If you're unable to scan the QR code, enter this secret manually into your authentication app. The secret is case-sensitive and should be entered exactly as shown.
|
||||||
|
</small>
|
||||||
</div>
|
</div>
|
||||||
<!-- Verification Code Input -->
|
<!-- Verification Code Input -->
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
<label for="verificationCode" class="form-label">Verification Code</label>
|
<label for="verificationCode" class="form-label">Verification Code</label>
|
||||||
<input type="text" class="form-control" id="verificationCode" placeholder="Enter code">
|
<input type="text" class="form-control" id="verificationCode" placeholder="Enter code">
|
||||||
|
<small class="form-text text-muted">
|
||||||
|
Enter the code generated by your authentication app. This code verifies that your 2FA setup is working correctly. Once entered, click 'Save 2FA Settings' to activate two-factor authentication for your account.
|
||||||
|
</small>
|
||||||
</div>
|
</div>
|
||||||
<!-- Save Button -->
|
<!-- Save Button -->
|
||||||
<button type="button" class="btn btn-primary">Save 2FA Settings</button>
|
<button type="button" class="btn btn-primary">Save 2FA Settings</button>
|
||||||
|
@ -160,49 +171,57 @@
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
const connectButton = document.getElementById('connectWebAuthnButton');
|
const connectButton = document.getElementById('connectWebAuthnButton');
|
||||||
|
|
||||||
connectButton.addEventListener('click', function() {
|
connectButton.addEventListener('click', async function() {
|
||||||
// Step 1: Get the registration challenge from the server
|
try {
|
||||||
fetch('/webauthn/register/challenge')
|
// Step 1: Get the registration challenge from the server
|
||||||
.then(response => response.json())
|
const response = await fetch('/webauthn/register/challenge');
|
||||||
.then(data => {
|
const data = await response.json();
|
||||||
// Step 2: Call WebAuthn API to create credentials
|
|
||||||
return navigator.credentials.create({
|
|
||||||
publicKey: data
|
|
||||||
});
|
|
||||||
})
|
|
||||||
.then(credentials => {
|
|
||||||
// Step 3: Send the credentials back to the server for verification
|
|
||||||
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)))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return fetch('/webauthn/register/verify', {
|
// Decode the challenge and user ID from Base64 to Uint8Array
|
||||||
method: 'POST',
|
const challenge = Uint8Array.from(atob(data.publicKey.challenge), c => c.charCodeAt(0));
|
||||||
headers: {
|
const userId = Uint8Array.from(atob(data.publicKey.user.id), c => c.charCodeAt(0));
|
||||||
'Content-Type': 'application/json'
|
|
||||||
},
|
// Modify the data object to use the decoded challenge and user ID
|
||||||
body: JSON.stringify(publicKeyCredential)
|
data.publicKey.challenge = challenge;
|
||||||
});
|
data.publicKey.user.id = userId;
|
||||||
})
|
|
||||||
.then(response => {
|
// Step 2: Call WebAuthn API to create credentials
|
||||||
if(response.ok) {
|
const credentials = await navigator.credentials.create(data);
|
||||||
// Handle successful registration, e.g., update the UI
|
|
||||||
alert('Registration successful!');
|
// Prepare credentials response
|
||||||
window.location.reload();
|
const publicKeyCredential = {
|
||||||
} else {
|
id: credentials.id,
|
||||||
// Handle registration error
|
rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))),
|
||||||
alert('Registration failed: ' + (data.error || 'Unknown error'));
|
type: credentials.type,
|
||||||
}
|
response: {
|
||||||
})
|
attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))),
|
||||||
.catch(error => {
|
clientDataJSON: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.clientDataJSON)))
|
||||||
console.error('Error during WebAuthn registration:', error);
|
},
|
||||||
|
// Include CSRF tokens in the payload
|
||||||
|
csrf_name: '{{ csrf_name }}',
|
||||||
|
csrf_value: '{{ csrf_value }}'
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if(verificationResponse.ok) {
|
||||||
|
alert('Registration successful!');
|
||||||
|
window.location.reload();
|
||||||
|
} else {
|
||||||
|
const errorData = await verificationResponse.json();
|
||||||
|
alert('Registration failed: ' + (errorData.error || 'Unknown error'));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error during WebAuthn registration:', error);
|
||||||
|
alert('Error during registration: ' + error.message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue