More work on 2FA and WebAuthn

This commit is contained in:
Pinga 2023-11-20 18:37:39 +02:00
parent 6466545c90
commit 2b6bdc71e9
3 changed files with 125 additions and 75 deletions

View file

@ -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');
try {
$db->insert( $db->insert(
'users_webauthn', 'users_webauthn',
[ [
'user_id' => $_SESSION['auth_user_id'], 'user_id' => $_SESSION['auth_user_id'],
'credential_id' => $credential->getCredentialId(), // Binary data 'credential_id' => base64_encode($credential->credentialId), // Binary data encoded in Base64
'public_key' => $credential->getPublicKey(), // Text data 'public_key' => $credential->publicKey, // Text data
'attestation_object' => $credential->getAttestationObject(), // Binary data 'attestation_object' => base64_encode($credential->attestationObject), // Binary data encoded in Base64
'sign_count' => $credential->getSignCount() // Integer 'sign_count' => $credential->signCount // 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());
}
// Send success response
$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) {

View file

@ -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": {

View file

@ -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,18 +171,24 @@
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() {
try {
// Step 1: Get the registration challenge from the server // Step 1: Get the registration challenge from the server
fetch('/webauthn/register/challenge') const response = await fetch('/webauthn/register/challenge');
.then(response => response.json()) const data = await response.json();
.then(data => {
// 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));
// Modify the data object to use the decoded challenge and user ID
data.publicKey.challenge = challenge;
data.publicKey.user.id = userId;
// Step 2: Call WebAuthn API to create credentials // Step 2: Call WebAuthn API to create credentials
return navigator.credentials.create({ const credentials = await navigator.credentials.create(data);
publicKey: data
}); // Prepare credentials response
})
.then(credentials => {
// Step 3: Send the credentials back to the server for verification
const publicKeyCredential = { const publicKeyCredential = {
id: credentials.id, id: credentials.id,
rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))), rawId: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.rawId))),
@ -179,30 +196,32 @@ document.addEventListener('DOMContentLoaded', function() {
response: { response: {
attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))), attestationObject: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.attestationObject))),
clientDataJSON: btoa(String.fromCharCode.apply(null, new Uint8Array(credentials.response.clientDataJSON))) 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 }}'
}; };
return fetch('/webauthn/register/verify', { // Step 3: Send the credentials back to the server for verification
const verificationResponse = await fetch('/webauthn/register/verify', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}, },
body: JSON.stringify(publicKeyCredential) body: JSON.stringify(publicKeyCredential)
}); });
})
.then(response => { if(verificationResponse.ok) {
if(response.ok) {
// Handle successful registration, e.g., update the UI
alert('Registration successful!'); alert('Registration successful!');
window.location.reload(); window.location.reload();
} else { } else {
// Handle registration error const errorData = await verificationResponse.json();
alert('Registration failed: ' + (data.error || 'Unknown error')); alert('Registration failed: ' + (errorData.error || 'Unknown error'));
} }
}) } catch (error) {
.catch(error => {
console.error('Error during WebAuthn registration:', error); console.error('Error during WebAuthn registration:', error);
}); alert('Error during registration: ' + error.message);
}
}); });
}); });
</script> </script>