Adding all the code i changed. It now supports mfa, passkeys and passwords
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1 +1,3 @@
|
||||
certs/
|
||||
config/
|
||||
app-code/config/
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
SSLEngine on
|
||||
SSLCertificateKeyFile /etc/apache2/certs/privkey.pem
|
||||
SSLCertificateFile /etc/apache2/certs/fullchain.pem
|
||||
# SSLCertificateChainFile /etc/apache2/certs/fullchain.pem
|
||||
SSLCertificateChainFile /etc/apache2/certs/fullchain.pem
|
||||
|
||||
<Directory /var/www/html>
|
||||
Options FollowSymLinks
|
||||
|
||||
534
app-code/account/index.php
Normal file
534
app-code/account/index.php
Normal file
@@ -0,0 +1,534 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Check if the user is logged in
|
||||
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
|
||||
header("LOCATION:/?send_to=/account/");
|
||||
exit();
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-bs-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Account Page</title>
|
||||
<!-- Bootstrap CSS -->
|
||||
<?php
|
||||
include "../assets/components.php";
|
||||
?>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Main Container -->
|
||||
<div class="container my-5">
|
||||
<div class="row">
|
||||
<!-- Profile Sidebar -->
|
||||
<div class="col-md-4">
|
||||
<div class="card">
|
||||
<div class="card-body text-center">
|
||||
<h3 id="user-name" class="card-title">Loading...</h3>
|
||||
<p id="user-email" class="text-muted">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Account Settings -->
|
||||
<div class="col-md-8">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<!-- Tabs for General and Password sections -->
|
||||
<ul class="nav nav-tabs" id="accountTab" role="tablist">
|
||||
<li class="nav-item" role="presentation">
|
||||
<a class="nav-link active" id="general-tab" data-bs-toggle="tab" href="#general" role="tab" aria-controls="general" aria-selected="true">General</a>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<a class="nav-link" id="password-tab" data-bs-toggle="tab" href="#password" role="tab" aria-controls="password" aria-selected="false">Password</a>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<a class="nav-link" id="2fa-tab" data-bs-toggle="tab" href="#2fa" role="tab" aria-controls="2fa" aria-selected="false">2fa</a>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<a class="nav-link" id="passkey-tab" data-bs-toggle="tab" href="#passkey" role="tab" aria-controls="passkey" aria-selected="false">Passkey</a>
|
||||
</li>
|
||||
<li class="nav-item" role="presentation">
|
||||
<a class="nav-link" href="/login/logout.php" role="tab" aria-selected="false">Logout</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<!-- Tab Content -->
|
||||
<div class="tab-content" id="accountTabContent">
|
||||
<!-- General Account Details -->
|
||||
<div class="tab-pane fade show active" id="general" role="tabpanel" aria-labelledby="general-tab">
|
||||
<form id="account-form">
|
||||
<!-- Name -->
|
||||
<div class="mb-3">
|
||||
<label for="name" class="form-label">Full Name</label>
|
||||
<input type="text" class="form-control" id="name" placeholder="Loading...">
|
||||
</div>
|
||||
|
||||
<!-- Email -->
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Email Address</label>
|
||||
<input type="email" class="form-control" id="email" placeholder="Set email">
|
||||
</div>
|
||||
|
||||
<!-- Telegram ID -->
|
||||
<div class="mb-3">
|
||||
<label for="telegram" class="form-label">Telegram ID</label>
|
||||
<input type="text" class="form-control" id="telegram" placeholder="Set telegram id">
|
||||
</div>
|
||||
|
||||
<!-- Save Changes Button -->
|
||||
<button type="button" id="save-button" class="btn btn-success">Save Changes</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Password Change Section -->
|
||||
<div class="tab-pane fade" id="password" role="tabpanel" aria-labelledby="password-tab">
|
||||
<form id="password-form">
|
||||
<!-- Old Password -->
|
||||
<div class="mb-3">
|
||||
<label for="old-password" class="form-label">Old Password</label>
|
||||
<input type="password" class="form-control" id="old-password" placeholder="Enter old password" required>
|
||||
</div>
|
||||
|
||||
<!-- New Password -->
|
||||
<div class="mb-3">
|
||||
<label for="new-password" class="form-label">New Password</label>
|
||||
<input type="password" class="form-control" id="new-password" placeholder="Enter new password" required>
|
||||
</div>
|
||||
|
||||
<!-- Confirm New Password -->
|
||||
<div class="mb-3">
|
||||
<label for="confirm-password" class="form-label">Confirm New Password</label>
|
||||
<input type="password" class="form-control" id="confirm-password" placeholder="Confirm new password" required>
|
||||
</div>
|
||||
|
||||
<!-- Change Password Button -->
|
||||
<button type="button" id="change-password-button" class="btn btn-warning">Change Password</button>
|
||||
</form>
|
||||
</div>
|
||||
<div class="tab-pane fade" id="2fa" role="tabpanel" aria-labelledby="2fa-tab">
|
||||
<p>If you enable this you will need to enter a pin before beeing able to log in.</p>
|
||||
<div class="form-check form-switch">
|
||||
<input class="form-check-input" type="checkbox" id="twofa-switch">
|
||||
<label class="form-check-label" for="twofa-switch">Enable 2FA</label>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="tab-pane fade" id="passkey" role="tabpanel" aria-labelledby="passkey-tab">
|
||||
<p>Using a passkey you can login with e.g. your fingerprint. If this is enabled you can still login using your password but using a passkey is faster.</p>
|
||||
<!--
|
||||
<div class="form-check form-switch">
|
||||
<input class="form-check-input" type="checkbox" id="passkey-switch">
|
||||
<label class="form-check-label" for="passkey-switch">Enable passkey</label>
|
||||
</div>
|
||||
-->
|
||||
<br>
|
||||
<button id="create-passkey" class="btn btn-primary" onclick="createRegistration()">Register passkey</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Error Modal -->
|
||||
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="errorModalLabel">Error</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body" id="errorModalMessage">
|
||||
<!-- Error message will go here -->
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Success Modal -->
|
||||
<div class="modal fade" id="successModal" tabindex="-1" aria-labelledby="successModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="successModalLabel">Success</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body" id="successModalMessage">
|
||||
<!-- Success message will go here -->
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- JavaScript -->
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Fetch user data from the backend API
|
||||
fetch('/api/account/get_user_data.php') // Replace with the actual API endpoint
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch user data');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(user => {
|
||||
// Populate the fields with user data
|
||||
document.getElementById('user-name').textContent = user.name;
|
||||
document.getElementById('user-email').textContent = user.email;
|
||||
|
||||
// Fill input fields
|
||||
document.getElementById('name').value = user.name;
|
||||
document.getElementById('email').value = user.email;
|
||||
document.getElementById('telegram').value = user.telegram_id;
|
||||
document.getElementById('twofa-switch').checked = user.twofa_enabled;
|
||||
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showErrorModal('Failed to load user data. Please try again later.');
|
||||
});
|
||||
|
||||
// Handle Save Changes button click
|
||||
const saveButton = document.getElementById('save-button');
|
||||
saveButton.addEventListener('click', () => {
|
||||
const updatedUser = {
|
||||
name: document.getElementById('name').value,
|
||||
email: document.getElementById('email').value,
|
||||
telegram_id: document.getElementById('telegram').value
|
||||
};
|
||||
|
||||
// Send updated data to the backend
|
||||
fetch('/api/account/update_user_data.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(updatedUser)
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to save user data');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
document.getElementById('user-name').textContent = updatedUser.name;
|
||||
document.getElementById('user-email').textContent = updatedUser.email;
|
||||
} else {
|
||||
showErrorModal('Failed to update user data. ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showErrorModal('Failed to save user data. Please try again later.');
|
||||
});
|
||||
});
|
||||
|
||||
// Handle Change Password button click
|
||||
const changePasswordButton = document.getElementById('change-password-button');
|
||||
changePasswordButton.addEventListener('click', () => {
|
||||
const oldPassword = document.getElementById('old-password').value;
|
||||
const newPassword = document.getElementById('new-password').value;
|
||||
const confirmPassword = document.getElementById('confirm-password').value;
|
||||
|
||||
// Validate password fields
|
||||
if (newPassword !== confirmPassword) {
|
||||
showErrorModal('New password and confirm password do not match.');
|
||||
return;
|
||||
}
|
||||
|
||||
const passwordData = {
|
||||
old_password: oldPassword,
|
||||
new_password: newPassword
|
||||
};
|
||||
|
||||
// Send password change request to the backend
|
||||
fetch('/api/account/update_pw.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(passwordData)
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to change password');
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showSuccessModal('Password updated.');
|
||||
} else {
|
||||
showErrorModal('Failed to update password. ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error:', error);
|
||||
showErrorModal('Failed to change password. Please try again later.');
|
||||
});
|
||||
});
|
||||
|
||||
// Function to show error modal
|
||||
function showErrorModal(message) {
|
||||
document.getElementById('errorModalMessage').textContent = message;
|
||||
const errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
|
||||
errorModal.show();
|
||||
}
|
||||
function showSuccessModal(message) {
|
||||
document.getElementById('successModalMessage').textContent = message;
|
||||
const errorModal = new bootstrap.Modal(document.getElementById('successModal'));
|
||||
errorModal.show();
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////
|
||||
const switchElement = document.getElementById('twofa-switch');
|
||||
|
||||
// Add an event listener for when the switch is changed
|
||||
switchElement.addEventListener('change', async function () {
|
||||
// Get the current state of the switch
|
||||
const isEnabled = switchElement.checked;
|
||||
|
||||
try {
|
||||
// Send the state to the backend using a POST request
|
||||
const response = await fetch('/api/account/update_2fa.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
enable_2fa: isEnabled, // Send the new state of 2FA
|
||||
}),
|
||||
});
|
||||
|
||||
// Check if the response is successful
|
||||
const result = await response.json();
|
||||
if (response.ok) {
|
||||
// Handle success
|
||||
showSuccessModal(result.message || (isEnabled ? '2FA enabled successfully.' : '2FA disabled successfully.'));
|
||||
} else {
|
||||
// Handle error
|
||||
showErrorModal('Error: ' + (result.message || 'An error occurred while updating 2FA.'));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
showErrorModal('Failed to send request. Please try again later.');
|
||||
}
|
||||
});
|
||||
});
|
||||
//webauthn js
|
||||
|
||||
async function createRegistration() {
|
||||
try {
|
||||
|
||||
// check browser support
|
||||
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
|
||||
throw new Error('Browser not supported.');
|
||||
}
|
||||
|
||||
// get create args
|
||||
let rep = await window.fetch('/api/account/update_passkey.php?fn=getCreateArgs' + getGetParams(), {method:'GET', cache:'no-cache'});
|
||||
//let rep = await window.fetch('/test/server.php?fn=getCreateArgs' + getGetParams(), {method:'GET', cache:'no-cache'});
|
||||
const createArgs = await rep.json();
|
||||
|
||||
// error handling
|
||||
if (createArgs.success === false) {
|
||||
throw new Error(createArgs.msg || 'unknown error occured');
|
||||
}
|
||||
|
||||
// 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
|
||||
};
|
||||
|
||||
// check auth on server side
|
||||
rep = await window.fetch('/api/account/update_passkey.php?fn=processCreate' + getGetParams(), {
|
||||
//rep = await window.fetch('/test/server.php?fn=processCreate' + getGetParams(), {
|
||||
method : 'POST',
|
||||
body : JSON.stringify(authenticatorAttestationResponse),
|
||||
cache : 'no-cache'
|
||||
});
|
||||
const authenticatorAttestationServerResponse = await rep.json();
|
||||
|
||||
// prompt server response
|
||||
if (authenticatorAttestationServerResponse.success) {
|
||||
reloadServerPreview();
|
||||
window.alert(authenticatorAttestationServerResponse.msg || 'registration success');
|
||||
} else {
|
||||
throw new Error(authenticatorAttestationServerResponse.msg);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
reloadServerPreview();
|
||||
window.alert(err.message || 'unknown error occured');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
function queryFidoMetaDataService() {
|
||||
window.fetch('/api/account/update_passkey.php?fn=queryFidoMetaDataService' + getGetParams(), {method:'GET',cache:'no-cache'}).then(function(response) {
|
||||
return response.json();
|
||||
|
||||
}).then(function(json) {
|
||||
if (json.success) {
|
||||
window.alert(json.msg);
|
||||
} else {
|
||||
throw new Error(json.msg);
|
||||
}
|
||||
}).catch(function(err) {
|
||||
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);
|
||||
}
|
||||
|
||||
function ascii_to_hex(str) {
|
||||
let hex = '';
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
let ascii = str.charCodeAt(i).toString(16);
|
||||
hex += ('00' + ascii).slice(-2); // Ensure each hex value is 2 characters long
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
/**
|
||||
* Get URL parameter
|
||||
* @returns {String}
|
||||
*/
|
||||
function getGetParams() {
|
||||
let url = '';
|
||||
|
||||
url += '&apple=1';
|
||||
url += '&yubico=1';
|
||||
url += '&solo=1'
|
||||
url += '&hypersecu=1';
|
||||
url += '&google=1';
|
||||
url += 'µsoft=1';
|
||||
url += '&mds=1';
|
||||
|
||||
url += '&requireResidentKey=0';
|
||||
|
||||
url += '&type_usb=1';
|
||||
url += '&type_nfc=1';
|
||||
url += '&type_ble=1';
|
||||
url += '&type_int=1';
|
||||
url += '&type_hybrid=1';
|
||||
|
||||
url += '&fmt_android-key=1';
|
||||
url += '&fmt_android-safetynet=1';
|
||||
url += '&fmt_apple=1';
|
||||
url += '&fmt_fido-u2f=1';
|
||||
url += '&fmt_none=1';
|
||||
url += '&fmt_packed=1';
|
||||
url += '&fmt_tpm=1';
|
||||
|
||||
url += '&rpId=auth.jakach.com';
|
||||
|
||||
url += '&userId=' + encodeURIComponent(ascii_to_hex('<?php echo($_SESSION["username"]);?>'));
|
||||
url += '&userName=' + encodeURIComponent('<?php echo($_SESSION["username"]);?>');
|
||||
url += '&userDisplayName=' + encodeURIComponent('<?php echo($_SESSION["username"]);?>');
|
||||
|
||||
url += '&userVerification=discouraged';
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
function reloadServerPreview() {
|
||||
//let iframe = document.getElementById('serverPreview');
|
||||
//iframe.src = iframe.src;
|
||||
}
|
||||
|
||||
function setAttestation(attestation) {
|
||||
let inputEls = document.getElementsByTagName('input');
|
||||
for (const inputEl of inputEls) {
|
||||
if (inputEl.id && inputEl.id.match(/^(fmt|cert)\_/)) {
|
||||
inputEl.disabled = !attestation;
|
||||
}
|
||||
if (inputEl.id && inputEl.id.match(/^fmt\_/)) {
|
||||
inputEl.checked = attestation ? inputEl.id !== 'fmt_none' : inputEl.id === 'fmt_none';
|
||||
}
|
||||
if (inputEl.id && inputEl.id.match(/^cert\_/)) {
|
||||
inputEl.checked = attestation ? inputEl.id === 'cert_mds' : false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* force https on load
|
||||
* @returns {undefined}
|
||||
*/
|
||||
window.onload = function() {
|
||||
if (location.protocol !== 'https:' && location.host !== 'localhost') {
|
||||
location.href = location.href.replace('http', 'https');
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
|
||||
179
app-code/api/account/Attestation/AttestationObject.php
Normal file
179
app-code/api/account/Attestation/AttestationObject.php
Normal file
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\CBOR\CborDecoder;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class AttestationObject {
|
||||
private $_authenticatorData;
|
||||
private $_attestationFormat;
|
||||
private $_attestationFormatName;
|
||||
|
||||
public function __construct($binary , $allowedFormats) {
|
||||
$enc = CborDecoder::decode($binary);
|
||||
// validation
|
||||
if (!\is_array($enc) || !\array_key_exists('fmt', $enc) || !is_string($enc['fmt'])) {
|
||||
throw new WebAuthnException('invalid attestation format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('attStmt', $enc) || !\is_array($enc['attStmt'])) {
|
||||
throw new WebAuthnException('invalid attestation format (attStmt not available)', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('authData', $enc) || !\is_object($enc['authData']) || !($enc['authData'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid attestation format (authData not available)', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_authenticatorData = new AuthenticatorData($enc['authData']->getBinaryString());
|
||||
$this->_attestationFormatName = $enc['fmt'];
|
||||
|
||||
// Format ok?
|
||||
if (!in_array($this->_attestationFormatName, $allowedFormats)) {
|
||||
throw new WebAuthnException('invalid atttestation format: ' . $this->_attestationFormatName, WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
|
||||
switch ($this->_attestationFormatName) {
|
||||
case 'android-key': $this->_attestationFormat = new Format\AndroidKey($enc, $this->_authenticatorData); break;
|
||||
case 'android-safetynet': $this->_attestationFormat = new Format\AndroidSafetyNet($enc, $this->_authenticatorData); break;
|
||||
case 'apple': $this->_attestationFormat = new Format\Apple($enc, $this->_authenticatorData); break;
|
||||
case 'fido-u2f': $this->_attestationFormat = new Format\U2f($enc, $this->_authenticatorData); break;
|
||||
case 'none': $this->_attestationFormat = new Format\None($enc, $this->_authenticatorData); break;
|
||||
case 'packed': $this->_attestationFormat = new Format\Packed($enc, $this->_authenticatorData); break;
|
||||
case 'tpm': $this->_attestationFormat = new Format\Tpm($enc, $this->_authenticatorData); break;
|
||||
default: throw new WebAuthnException('invalid attestation format: ' . $enc['fmt'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation format name
|
||||
* @return string
|
||||
*/
|
||||
public function getAttestationFormatName() {
|
||||
return $this->_attestationFormatName;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation format class
|
||||
* @return Format\FormatBase
|
||||
*/
|
||||
public function getAttestationFormat() {
|
||||
return $this->_attestationFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation public key in PEM format
|
||||
* @return AuthenticatorData
|
||||
*/
|
||||
public function getAuthenticatorData() {
|
||||
return $this->_authenticatorData;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the certificate chain as PEM
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificateChain() {
|
||||
return $this->_attestationFormat->getCertificateChain();
|
||||
}
|
||||
|
||||
/**
|
||||
* return the certificate issuer as string
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificateIssuer() {
|
||||
$pem = $this->getCertificatePem();
|
||||
$issuer = '';
|
||||
if ($pem) {
|
||||
$certInfo = \openssl_x509_parse($pem);
|
||||
if (\is_array($certInfo) && \array_key_exists('issuer', $certInfo) && \is_array($certInfo['issuer'])) {
|
||||
|
||||
$cn = $certInfo['issuer']['CN'] ?? '';
|
||||
$o = $certInfo['issuer']['O'] ?? '';
|
||||
$ou = $certInfo['issuer']['OU'] ?? '';
|
||||
|
||||
if ($cn) {
|
||||
$issuer .= $cn;
|
||||
}
|
||||
if ($issuer && ($o || $ou)) {
|
||||
$issuer .= ' (' . trim($o . ' ' . $ou) . ')';
|
||||
} else {
|
||||
$issuer .= trim($o . ' ' . $ou);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* return the certificate subject as string
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificateSubject() {
|
||||
$pem = $this->getCertificatePem();
|
||||
$subject = '';
|
||||
if ($pem) {
|
||||
$certInfo = \openssl_x509_parse($pem);
|
||||
if (\is_array($certInfo) && \array_key_exists('subject', $certInfo) && \is_array($certInfo['subject'])) {
|
||||
|
||||
$cn = $certInfo['subject']['CN'] ?? '';
|
||||
$o = $certInfo['subject']['O'] ?? '';
|
||||
$ou = $certInfo['subject']['OU'] ?? '';
|
||||
|
||||
if ($cn) {
|
||||
$subject .= $cn;
|
||||
}
|
||||
if ($subject && ($o || $ou)) {
|
||||
$subject .= ' (' . trim($o . ' ' . $ou) . ')';
|
||||
} else {
|
||||
$subject .= trim($o . ' ' . $ou);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_attestationFormat->getCertificatePem();
|
||||
}
|
||||
|
||||
/**
|
||||
* checks validity of the signature
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_attestationFormat->validateAttestation($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
return $this->_attestationFormat->validateRootCertificate($rootCas);
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if the RpId-Hash is valid
|
||||
* @param string$rpIdHash
|
||||
* @return bool
|
||||
*/
|
||||
public function validateRpIdHash($rpIdHash) {
|
||||
return $rpIdHash === $this->_authenticatorData->getRpIdHash();
|
||||
}
|
||||
}
|
||||
481
app-code/api/account/Attestation/AuthenticatorData.php
Normal file
481
app-code/api/account/Attestation/AuthenticatorData.php
Normal file
@@ -0,0 +1,481 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\CBOR\CborDecoder;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class AuthenticatorData {
|
||||
protected $_binary;
|
||||
protected $_rpIdHash;
|
||||
protected $_flags;
|
||||
protected $_signCount;
|
||||
protected $_attestedCredentialData;
|
||||
protected $_extensionData;
|
||||
|
||||
|
||||
|
||||
// Cose encoded keys
|
||||
private static $_COSE_KTY = 1;
|
||||
private static $_COSE_ALG = 3;
|
||||
|
||||
// Cose curve
|
||||
private static $_COSE_CRV = -1;
|
||||
private static $_COSE_X = -2;
|
||||
private static $_COSE_Y = -3;
|
||||
|
||||
// Cose RSA PS256
|
||||
private static $_COSE_N = -1;
|
||||
private static $_COSE_E = -2;
|
||||
|
||||
// EC2 key type
|
||||
private static $_EC2_TYPE = 2;
|
||||
private static $_EC2_ES256 = -7;
|
||||
private static $_EC2_P256 = 1;
|
||||
|
||||
// RSA key type
|
||||
private static $_RSA_TYPE = 3;
|
||||
private static $_RSA_RS256 = -257;
|
||||
|
||||
// OKP key type
|
||||
private static $_OKP_TYPE = 1;
|
||||
private static $_OKP_ED25519 = 6;
|
||||
private static $_OKP_EDDSA = -8;
|
||||
|
||||
/**
|
||||
* Parsing the authenticatorData binary.
|
||||
* @param string $binary
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function __construct($binary) {
|
||||
if (!\is_string($binary) || \strlen($binary) < 37) {
|
||||
throw new WebAuthnException('Invalid authenticatorData input', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
$this->_binary = $binary;
|
||||
|
||||
// Read infos from binary
|
||||
// https://www.w3.org/TR/webauthn/#sec-authenticator-data
|
||||
|
||||
// RP ID
|
||||
$this->_rpIdHash = \substr($binary, 0, 32);
|
||||
|
||||
// flags (1 byte)
|
||||
$flags = \unpack('Cflags', \substr($binary, 32, 1))['flags'];
|
||||
$this->_flags = $this->_readFlags($flags);
|
||||
|
||||
// signature counter: 32-bit unsigned big-endian integer.
|
||||
$this->_signCount = \unpack('Nsigncount', \substr($binary, 33, 4))['signcount'];
|
||||
|
||||
$offset = 37;
|
||||
// https://www.w3.org/TR/webauthn/#sec-attested-credential-data
|
||||
if ($this->_flags->attestedDataIncluded) {
|
||||
$this->_attestedCredentialData = $this->_readAttestData($binary, $offset);
|
||||
}
|
||||
|
||||
if ($this->_flags->extensionDataIncluded) {
|
||||
$this->_readExtensionData(\substr($binary, $offset));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticator Attestation Globally Unique Identifier, a unique number
|
||||
* that identifies the model of the authenticator (not the specific instance
|
||||
* of the authenticator)
|
||||
* The aaguid may be 0 if the user is using a old u2f device and/or if
|
||||
* the browser is using the fido-u2f format.
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function getAAGUID() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
return $this->_attestedCredentialData->aaguid;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the authenticatorData as binary
|
||||
* @return string
|
||||
*/
|
||||
public function getBinary() {
|
||||
return $this->_binary;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the credentialId
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function getCredentialId() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass)) {
|
||||
throw new WebAuthnException('credential id not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
return $this->_attestedCredentialData->credentialId;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the public key in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getPublicKeyPem() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$der = null;
|
||||
switch ($this->_attestedCredentialData->credentialPublicKey->kty ?? null) {
|
||||
case self::$_EC2_TYPE: $der = $this->_getEc2Der(); break;
|
||||
case self::$_RSA_TYPE: $der = $this->_getRsaDer(); break;
|
||||
case self::$_OKP_TYPE: $der = $this->_getOkpDer(); break;
|
||||
default: throw new WebAuthnException('invalid key type', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$pem = '-----BEGIN PUBLIC KEY-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($der), 64, "\n");
|
||||
$pem .= '-----END PUBLIC KEY-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the public key in U2F format
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function getPublicKeyU2F() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
if (($this->_attestedCredentialData->credentialPublicKey->kty ?? null) !== self::$_EC2_TYPE) {
|
||||
throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
return "\x04" . // ECC uncompressed
|
||||
$this->_attestedCredentialData->credentialPublicKey->x .
|
||||
$this->_attestedCredentialData->credentialPublicKey->y;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the SHA256 hash of the relying party id (=hostname)
|
||||
* @return string
|
||||
*/
|
||||
public function getRpIdHash() {
|
||||
return $this->_rpIdHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the sign counter
|
||||
* @return int
|
||||
*/
|
||||
public function getSignCount() {
|
||||
return $this->_signCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if the user is present
|
||||
* @return boolean
|
||||
*/
|
||||
public function getUserPresent() {
|
||||
return $this->_flags->userPresent;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if the user is verified
|
||||
* @return boolean
|
||||
*/
|
||||
public function getUserVerified() {
|
||||
return $this->_flags->userVerified;
|
||||
}
|
||||
|
||||
// -----------------------------------------------
|
||||
// PRIVATE
|
||||
// -----------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns DER encoded EC2 key
|
||||
* @return string
|
||||
*/
|
||||
private function _getEc2Der() {
|
||||
return $this->_der_sequence(
|
||||
$this->_der_sequence(
|
||||
$this->_der_oid("\x2A\x86\x48\xCE\x3D\x02\x01") . // OID 1.2.840.10045.2.1 ecPublicKey
|
||||
$this->_der_oid("\x2A\x86\x48\xCE\x3D\x03\x01\x07") // 1.2.840.10045.3.1.7 prime256v1
|
||||
) .
|
||||
$this->_der_bitString($this->getPublicKeyU2F())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns DER encoded EdDSA key
|
||||
* @return string
|
||||
*/
|
||||
private function _getOkpDer() {
|
||||
return $this->_der_sequence(
|
||||
$this->_der_sequence(
|
||||
$this->_der_oid("\x2B\x65\x70") // OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
|
||||
) .
|
||||
$this->_der_bitString($this->_attestedCredentialData->credentialPublicKey->x)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns DER encoded RSA key
|
||||
* @return string
|
||||
*/
|
||||
private function _getRsaDer() {
|
||||
return $this->_der_sequence(
|
||||
$this->_der_sequence(
|
||||
$this->_der_oid("\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01") . // OID 1.2.840.113549.1.1.1 rsaEncryption
|
||||
$this->_der_nullValue()
|
||||
) .
|
||||
$this->_der_bitString(
|
||||
$this->_der_sequence(
|
||||
$this->_der_unsignedInteger($this->_attestedCredentialData->credentialPublicKey->n) .
|
||||
$this->_der_unsignedInteger($this->_attestedCredentialData->credentialPublicKey->e)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* reads the flags from flag byte
|
||||
* @param string $binFlag
|
||||
* @return \stdClass
|
||||
*/
|
||||
private function _readFlags($binFlag) {
|
||||
$flags = new \stdClass();
|
||||
|
||||
$flags->bit_0 = !!($binFlag & 1);
|
||||
$flags->bit_1 = !!($binFlag & 2);
|
||||
$flags->bit_2 = !!($binFlag & 4);
|
||||
$flags->bit_3 = !!($binFlag & 8);
|
||||
$flags->bit_4 = !!($binFlag & 16);
|
||||
$flags->bit_5 = !!($binFlag & 32);
|
||||
$flags->bit_6 = !!($binFlag & 64);
|
||||
$flags->bit_7 = !!($binFlag & 128);
|
||||
|
||||
// named flags
|
||||
$flags->userPresent = $flags->bit_0;
|
||||
$flags->userVerified = $flags->bit_2;
|
||||
$flags->attestedDataIncluded = $flags->bit_6;
|
||||
$flags->extensionDataIncluded = $flags->bit_7;
|
||||
return $flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* read attested data
|
||||
* @param string $binary
|
||||
* @param int $endOffset
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readAttestData($binary, &$endOffset) {
|
||||
$attestedCData = new \stdClass();
|
||||
if (\strlen($binary) <= 55) {
|
||||
throw new WebAuthnException('Attested data should be present but is missing', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// The AAGUID of the authenticator
|
||||
$attestedCData->aaguid = \substr($binary, 37, 16);
|
||||
|
||||
//Byte length L of Credential ID, 16-bit unsigned big-endian integer.
|
||||
$length = \unpack('nlength', \substr($binary, 53, 2))['length'];
|
||||
$attestedCData->credentialId = \substr($binary, 55, $length);
|
||||
|
||||
// set end offset
|
||||
$endOffset = 55 + $length;
|
||||
|
||||
// extract public key
|
||||
$attestedCData->credentialPublicKey = $this->_readCredentialPublicKey($binary, 55 + $length, $endOffset);
|
||||
|
||||
return $attestedCData;
|
||||
}
|
||||
|
||||
/**
|
||||
* reads COSE key-encoded elliptic curve public key in EC2 format
|
||||
* @param string $binary
|
||||
* @param int $endOffset
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKey($binary, $offset, &$endOffset) {
|
||||
$enc = CborDecoder::decodeInPlace($binary, $offset, $endOffset);
|
||||
|
||||
// COSE key-encoded elliptic curve public key in EC2 format
|
||||
$credPKey = new \stdClass();
|
||||
$credPKey->kty = $enc[self::$_COSE_KTY];
|
||||
$credPKey->alg = $enc[self::$_COSE_ALG];
|
||||
|
||||
switch ($credPKey->alg) {
|
||||
case self::$_EC2_ES256: $this->_readCredentialPublicKeyES256($credPKey, $enc); break;
|
||||
case self::$_RSA_RS256: $this->_readCredentialPublicKeyRS256($credPKey, $enc); break;
|
||||
case self::$_OKP_EDDSA: $this->_readCredentialPublicKeyEDDSA($credPKey, $enc); break;
|
||||
}
|
||||
|
||||
return $credPKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* extract EDDSA informations from cose
|
||||
* @param \stdClass $credPKey
|
||||
* @param \stdClass $enc
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKeyEDDSA(&$credPKey, $enc) {
|
||||
$credPKey->crv = $enc[self::$_COSE_CRV];
|
||||
$credPKey->x = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
// Validation
|
||||
if ($credPKey->kty !== self::$_OKP_TYPE) {
|
||||
throw new WebAuthnException('public key not in OKP format', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->alg !== self::$_OKP_EDDSA) {
|
||||
throw new WebAuthnException('signature algorithm not EdDSA', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->crv !== self::$_OKP_ED25519) {
|
||||
throw new WebAuthnException('curve not Ed25519', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->x) !== 32) {
|
||||
throw new WebAuthnException('Invalid X-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* extract ES256 informations from cose
|
||||
* @param \stdClass $credPKey
|
||||
* @param \stdClass $enc
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKeyES256(&$credPKey, $enc) {
|
||||
$credPKey->crv = $enc[self::$_COSE_CRV];
|
||||
$credPKey->x = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
|
||||
$credPKey->y = $enc[self::$_COSE_Y] instanceof ByteBuffer ? $enc[self::$_COSE_Y]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
// Validation
|
||||
if ($credPKey->kty !== self::$_EC2_TYPE) {
|
||||
throw new WebAuthnException('public key not in EC2 format', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->alg !== self::$_EC2_ES256) {
|
||||
throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->crv !== self::$_EC2_P256) {
|
||||
throw new WebAuthnException('curve not P-256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->x) !== 32) {
|
||||
throw new WebAuthnException('Invalid X-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->y) !== 32) {
|
||||
throw new WebAuthnException('Invalid Y-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* extract RS256 informations from COSE
|
||||
* @param \stdClass $credPKey
|
||||
* @param \stdClass $enc
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKeyRS256(&$credPKey, $enc) {
|
||||
$credPKey->n = $enc[self::$_COSE_N] instanceof ByteBuffer ? $enc[self::$_COSE_N]->getBinaryString() : null;
|
||||
$credPKey->e = $enc[self::$_COSE_E] instanceof ByteBuffer ? $enc[self::$_COSE_E]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
// Validation
|
||||
if ($credPKey->kty !== self::$_RSA_TYPE) {
|
||||
throw new WebAuthnException('public key not in RSA format', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->alg !== self::$_RSA_RS256) {
|
||||
throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->n) !== 256) {
|
||||
throw new WebAuthnException('Invalid RSA modulus', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->e) !== 3) {
|
||||
throw new WebAuthnException('Invalid RSA public exponent', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* reads cbor encoded extension data.
|
||||
* @param string $binary
|
||||
* @return array
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readExtensionData($binary) {
|
||||
$ext = CborDecoder::decode($binary);
|
||||
if (!\is_array($ext)) {
|
||||
throw new WebAuthnException('invalid extension data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
return $ext;
|
||||
}
|
||||
|
||||
|
||||
// ---------------
|
||||
// DER functions
|
||||
// ---------------
|
||||
|
||||
private function _der_length($len) {
|
||||
if ($len < 128) {
|
||||
return \chr($len);
|
||||
}
|
||||
$lenBytes = '';
|
||||
while ($len > 0) {
|
||||
$lenBytes = \chr($len % 256) . $lenBytes;
|
||||
$len = \intdiv($len, 256);
|
||||
}
|
||||
return \chr(0x80 | \strlen($lenBytes)) . $lenBytes;
|
||||
}
|
||||
|
||||
private function _der_sequence($contents) {
|
||||
return "\x30" . $this->_der_length(\strlen($contents)) . $contents;
|
||||
}
|
||||
|
||||
private function _der_oid($encoded) {
|
||||
return "\x06" . $this->_der_length(\strlen($encoded)) . $encoded;
|
||||
}
|
||||
|
||||
private function _der_bitString($bytes) {
|
||||
return "\x03" . $this->_der_length(\strlen($bytes) + 1) . "\x00" . $bytes;
|
||||
}
|
||||
|
||||
private function _der_nullValue() {
|
||||
return "\x05\x00";
|
||||
}
|
||||
|
||||
private function _der_unsignedInteger($bytes) {
|
||||
$len = \strlen($bytes);
|
||||
|
||||
// Remove leading zero bytes
|
||||
for ($i = 0; $i < ($len - 1); $i++) {
|
||||
if (\ord($bytes[$i]) !== 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($i !== 0) {
|
||||
$bytes = \substr($bytes, $i);
|
||||
}
|
||||
|
||||
// If most significant bit is set, prefix with another zero to prevent it being seen as negative number
|
||||
if ((\ord($bytes[0]) & 0x80) !== 0) {
|
||||
$bytes = "\x00" . $bytes;
|
||||
}
|
||||
|
||||
return "\x02" . $this->_der_length(\strlen($bytes)) . $bytes;
|
||||
}
|
||||
}
|
||||
96
app-code/api/account/Attestation/Format/AndroidKey.php
Normal file
96
app-code/api/account/Attestation/Format/AndroidKey.php
Normal file
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class AndroidKey extends FormatBase {
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check u2f data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('x5c', $attStmt) || !\is_array($attStmt['x5c']) || \count($attStmt['x5c']) < 1) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\is_object($attStmt['x5c'][0]) || !($attStmt['x5c'][0] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_x5c = $attStmt['x5c'][0]->getBinaryString();
|
||||
|
||||
if (count($attStmt['x5c']) > 1) {
|
||||
for ($i=1; $i<count($attStmt['x5c']); $i++) {
|
||||
$this->_x5c_chain[] = $attStmt['x5c'][$i]->getBinaryString();
|
||||
}
|
||||
unset ($i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the attestation public key in attestnCert with the algorithm specified in alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
|
||||
152
app-code/api/account/Attestation/Format/AndroidSafetyNet.php
Normal file
152
app-code/api/account/Attestation/Format/AndroidSafetyNet.php
Normal file
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class AndroidSafetyNet extends FormatBase {
|
||||
private $_signature;
|
||||
private $_signedValue;
|
||||
private $_x5c;
|
||||
private $_payload;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('ver', $attStmt) || !$attStmt['ver']) {
|
||||
throw new WebAuthnException('invalid Android Safety Net Format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('response', $attStmt) || !($attStmt['response'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid Android Safety Net Format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$response = $attStmt['response']->getBinaryString();
|
||||
|
||||
// Response is a JWS [RFC7515] object in Compact Serialization.
|
||||
// JWSs have three segments separated by two period ('.') characters
|
||||
$parts = \explode('.', $response);
|
||||
unset ($response);
|
||||
if (\count($parts) !== 3) {
|
||||
throw new WebAuthnException('invalid JWS data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$header = $this->_base64url_decode($parts[0]);
|
||||
$payload = $this->_base64url_decode($parts[1]);
|
||||
$this->_signature = $this->_base64url_decode($parts[2]);
|
||||
$this->_signedValue = $parts[0] . '.' . $parts[1];
|
||||
unset ($parts);
|
||||
|
||||
$header = \json_decode($header);
|
||||
$payload = \json_decode($payload);
|
||||
|
||||
if (!($header instanceof \stdClass)) {
|
||||
throw new WebAuthnException('invalid JWS header', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
if (!($payload instanceof \stdClass)) {
|
||||
throw new WebAuthnException('invalid JWS payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!isset($header->x5c) || !is_array($header->x5c) || count($header->x5c) === 0) {
|
||||
throw new WebAuthnException('No X.509 signature in JWS Header', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// algorithm
|
||||
if (!\in_array($header->alg, array('RS256', 'ES256'))) {
|
||||
throw new WebAuthnException('invalid JWS algorithm ' . $header->alg, WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = \base64_decode($header->x5c[0]);
|
||||
$this->_payload = $payload;
|
||||
|
||||
if (count($header->x5c) > 1) {
|
||||
for ($i=1; $i<count($header->x5c); $i++) {
|
||||
$this->_x5c_chain[] = \base64_decode($header->x5c[$i]);
|
||||
}
|
||||
unset ($i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ctsProfileMatch: A stricter verdict of device integrity.
|
||||
* If the value of ctsProfileMatch is true, then the profile of the device running your app matches
|
||||
* the profile of a device that has passed Android compatibility testing and
|
||||
* has been approved as a Google-certified Android device.
|
||||
* @return bool
|
||||
*/
|
||||
public function ctsProfileMatch() {
|
||||
return isset($this->_payload->ctsProfileMatch) ? !!$this->_payload->ctsProfileMatch : false;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
// Verify that the nonce in the response is identical to the Base64 encoding
|
||||
// of the SHA-256 hash of the concatenation of authenticatorData and clientDataHash.
|
||||
if (empty($this->_payload->nonce) || $this->_payload->nonce !== \base64_encode(\hash('SHA256', $this->_authenticatorData->getBinary() . $clientDataHash, true))) {
|
||||
throw new WebAuthnException('invalid nonce in JWS payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that attestationCert is issued to the hostname "attest.android.com"
|
||||
$certInfo = \openssl_x509_parse($this->getCertificatePem());
|
||||
if (!\is_array($certInfo) || ($certInfo['subject']['CN'] ?? '') !== 'attest.android.com') {
|
||||
throw new WebAuthnException('invalid certificate CN in JWS (' . ($certInfo['subject']['CN'] ?? '-'). ')', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that the basicIntegrity attribute in the payload of response is true.
|
||||
if (empty($this->_payload->basicIntegrity)) {
|
||||
throw new WebAuthnException('invalid basicIntegrity in payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($this->_signedValue, $this->_signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* decode base64 url
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
private function _base64url_decode($data) {
|
||||
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
|
||||
}
|
||||
}
|
||||
|
||||
139
app-code/api/account/Attestation/Format/Apple.php
Normal file
139
app-code/api/account/Attestation/Format/Apple.php
Normal file
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Apple extends FormatBase {
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new WebAuthnException('invalid Apple attestation statement: missing x5c', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Concatenate authenticatorData and clientDataHash to form nonceToHash.
|
||||
$nonceToHash = $this->_authenticatorData->getBinary();
|
||||
$nonceToHash .= $clientDataHash;
|
||||
|
||||
// Perform SHA-256 hash of nonceToHash to produce nonce
|
||||
$nonce = hash('SHA256', $nonceToHash, true);
|
||||
|
||||
$credCert = openssl_x509_read($this->getCertificatePem());
|
||||
if ($credCert === false) {
|
||||
throw new WebAuthnException('invalid x5c certificate: ' . \openssl_error_string(), WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$keyData = openssl_pkey_get_details(openssl_pkey_get_public($credCert));
|
||||
$key = is_array($keyData) && array_key_exists('key', $keyData) ? $keyData['key'] : null;
|
||||
|
||||
|
||||
// Verify that nonce equals the value of the extension with OID ( 1.2.840.113635.100.8.2 ) in credCert.
|
||||
$parsedCredCert = openssl_x509_parse($credCert);
|
||||
$nonceExtension = $parsedCredCert['extensions']['1.2.840.113635.100.8.2'] ?? '';
|
||||
|
||||
// nonce padded by ASN.1 string: 30 24 A1 22 04 20
|
||||
// 30 — type tag indicating sequence
|
||||
// 24 — 36 byte following
|
||||
// A1 — Enumerated [1]
|
||||
// 22 — 34 byte following
|
||||
// 04 — type tag indicating octet string
|
||||
// 20 — 32 byte following
|
||||
|
||||
$asn1Padding = "\x30\x24\xA1\x22\x04\x20";
|
||||
if (substr($nonceExtension, 0, strlen($asn1Padding)) === $asn1Padding) {
|
||||
$nonceExtension = substr($nonceExtension, strlen($asn1Padding));
|
||||
}
|
||||
|
||||
if ($nonceExtension !== $nonce) {
|
||||
throw new WebAuthnException('nonce doesn\'t equal the value of the extension with OID 1.2.840.113635.100.8.2', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that the credential public key equals the Subject Public Key of credCert.
|
||||
$authKeyData = openssl_pkey_get_details(openssl_pkey_get_public($this->_authenticatorData->getPublicKeyPem()));
|
||||
$authKey = is_array($authKeyData) && array_key_exists('key', $authKeyData) ? $authKeyData['key'] : null;
|
||||
|
||||
if ($key === null || $key !== $authKey) {
|
||||
throw new WebAuthnException('credential public key doesn\'t equal the Subject Public Key of credCert', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
193
app-code/api/account/Attestation/Format/FormatBase.php
Normal file
193
app-code/api/account/Attestation/Format/FormatBase.php
Normal file
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
|
||||
|
||||
abstract class FormatBase {
|
||||
protected $_attestationObject = null;
|
||||
protected $_authenticatorData = null;
|
||||
protected $_x5c_chain = array();
|
||||
protected $_x5c_tempFile = null;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Array $AttestionObject
|
||||
* @param AuthenticatorData $authenticatorData
|
||||
*/
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
$this->_attestationObject = $AttestionObject;
|
||||
$this->_authenticatorData = $authenticatorData;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __destruct() {
|
||||
// delete X.509 chain certificate file after use
|
||||
if ($this->_x5c_tempFile && \is_file($this->_x5c_tempFile)) {
|
||||
\unlink($this->_x5c_tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the certificate chain in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificateChain() {
|
||||
if ($this->_x5c_tempFile && \is_file($this->_x5c_tempFile)) {
|
||||
return \file_get_contents($this->_x5c_tempFile);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the key X.509 certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
// need to be overwritten
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* checks validity of the signature
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
// need to be overwritten
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
// need to be overwritten
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* create a PEM encoded certificate with X.509 binary data
|
||||
* @param string $x5c
|
||||
* @return string
|
||||
*/
|
||||
protected function _createCertificatePem($x5c) {
|
||||
$pem = '-----BEGIN CERTIFICATE-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($x5c), 64, "\n");
|
||||
$pem .= '-----END CERTIFICATE-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* creates a PEM encoded chain file
|
||||
* @return type
|
||||
*/
|
||||
protected function _createX5cChainFile() {
|
||||
$content = '';
|
||||
if (\is_array($this->_x5c_chain) && \count($this->_x5c_chain) > 0) {
|
||||
foreach ($this->_x5c_chain as $x5c) {
|
||||
$certInfo = \openssl_x509_parse($this->_createCertificatePem($x5c));
|
||||
|
||||
// check if certificate is self signed
|
||||
if (\is_array($certInfo) && \is_array($certInfo['issuer']) && \is_array($certInfo['subject'])) {
|
||||
$selfSigned = false;
|
||||
|
||||
$subjectKeyIdentifier = $certInfo['extensions']['subjectKeyIdentifier'] ?? null;
|
||||
$authorityKeyIdentifier = $certInfo['extensions']['authorityKeyIdentifier'] ?? null;
|
||||
|
||||
if ($authorityKeyIdentifier && substr($authorityKeyIdentifier, 0, 6) === 'keyid:') {
|
||||
$authorityKeyIdentifier = substr($authorityKeyIdentifier, 6);
|
||||
}
|
||||
if ($subjectKeyIdentifier && substr($subjectKeyIdentifier, 0, 6) === 'keyid:') {
|
||||
$subjectKeyIdentifier = substr($subjectKeyIdentifier, 6);
|
||||
}
|
||||
|
||||
if (($subjectKeyIdentifier && !$authorityKeyIdentifier) || ($authorityKeyIdentifier && $authorityKeyIdentifier === $subjectKeyIdentifier)) {
|
||||
$selfSigned = true;
|
||||
}
|
||||
|
||||
if (!$selfSigned) {
|
||||
$content .= "\n" . $this->_createCertificatePem($x5c) . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($content) {
|
||||
$this->_x5c_tempFile = \tempnam(\sys_get_temp_dir(), 'x5c_');
|
||||
if (\file_put_contents($this->_x5c_tempFile, $content) !== false) {
|
||||
return $this->_x5c_tempFile;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns the name and openssl key for provided cose number.
|
||||
* @param int $coseNumber
|
||||
* @return \stdClass|null
|
||||
*/
|
||||
protected function _getCoseAlgorithm($coseNumber) {
|
||||
// https://www.iana.org/assignments/cose/cose.xhtml#algorithms
|
||||
$coseAlgorithms = array(
|
||||
array(
|
||||
'hash' => 'SHA1',
|
||||
'openssl' => OPENSSL_ALGO_SHA1,
|
||||
'cose' => array(
|
||||
-65535 // RS1
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA256',
|
||||
'openssl' => OPENSSL_ALGO_SHA256,
|
||||
'cose' => array(
|
||||
-257, // RS256
|
||||
-37, // PS256
|
||||
-7, // ES256
|
||||
5 // HMAC256
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA384',
|
||||
'openssl' => OPENSSL_ALGO_SHA384,
|
||||
'cose' => array(
|
||||
-258, // RS384
|
||||
-38, // PS384
|
||||
-35, // ES384
|
||||
6 // HMAC384
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA512',
|
||||
'openssl' => OPENSSL_ALGO_SHA512,
|
||||
'cose' => array(
|
||||
-259, // RS512
|
||||
-39, // PS512
|
||||
-36, // ES512
|
||||
7 // HMAC512
|
||||
))
|
||||
);
|
||||
|
||||
foreach ($coseAlgorithms as $coseAlgorithm) {
|
||||
if (\in_array($coseNumber, $coseAlgorithm['cose'], true)) {
|
||||
$return = new \stdClass();
|
||||
$return->hash = $coseAlgorithm['hash'];
|
||||
$return->openssl = $coseAlgorithm['openssl'];
|
||||
return $return;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
41
app-code/api/account/Attestation/Format/None.php
Normal file
41
app-code/api/account/Attestation/Format/None.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
|
||||
class None extends FormatBase {
|
||||
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates.
|
||||
* Format 'none' does not contain any ca, so always false.
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
139
app-code/api/account/Attestation/Format/Packed.php
Normal file
139
app-code/api/account/Attestation/Format/Packed.php
Normal file
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Packed extends FormatBase {
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
if (!$this->_x5c) {
|
||||
return null;
|
||||
}
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
if ($this->_x5c) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
} else {
|
||||
return $this->_validateSelfAttestation($clientDataHash);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
if (!$this->_x5c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the attestation public key in attestnCert with the algorithm specified in alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if self attestation is in use
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
*/
|
||||
protected function _validateSelfAttestation($clientDataHash) {
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the credential public key with alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$publicKey = $this->_authenticatorData->getPublicKeyPem();
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
}
|
||||
|
||||
180
app-code/api/account/Attestation/Format/Tpm.php
Normal file
180
app-code/api/account/Attestation/Format/Tpm.php
Normal file
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Tpm extends FormatBase {
|
||||
private $_TPM_GENERATED_VALUE = "\xFF\x54\x43\x47";
|
||||
private $_TPM_ST_ATTEST_CERTIFY = "\x80\x17";
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_pubArea;
|
||||
private $_x5c;
|
||||
|
||||
/**
|
||||
* @var ByteBuffer
|
||||
*/
|
||||
private $_certInfo;
|
||||
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('ver', $attStmt) || $attStmt['ver'] !== '2.0') {
|
||||
throw new WebAuthnException('invalid tpm version: ' . $attStmt['ver'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('signature not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('certInfo', $attStmt) || !\is_object($attStmt['certInfo']) || !($attStmt['certInfo'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('certInfo not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('pubArea', $attStmt) || !\is_object($attStmt['pubArea']) || !($attStmt['pubArea'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('pubArea not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_certInfo = $attStmt['certInfo'];
|
||||
$this->_pubArea = $attStmt['pubArea'];
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new WebAuthnException('no x5c certificate found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
if (!$this->_x5c) {
|
||||
return null;
|
||||
}
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
if (!$this->_x5c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Concatenate authenticatorData and clientDataHash to form attToBeSigned.
|
||||
$attToBeSigned = $this->_authenticatorData->getBinary();
|
||||
$attToBeSigned .= $clientDataHash;
|
||||
|
||||
// Validate that certInfo is valid:
|
||||
|
||||
// Verify that magic is set to TPM_GENERATED_VALUE.
|
||||
if ($this->_certInfo->getBytes(0, 4) !== $this->_TPM_GENERATED_VALUE) {
|
||||
throw new WebAuthnException('tpm magic not TPM_GENERATED_VALUE', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that type is set to TPM_ST_ATTEST_CERTIFY.
|
||||
if ($this->_certInfo->getBytes(4, 2) !== $this->_TPM_ST_ATTEST_CERTIFY) {
|
||||
throw new WebAuthnException('tpm type not TPM_ST_ATTEST_CERTIFY', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$offset = 6;
|
||||
$qualifiedSigner = $this->_tpmReadLengthPrefixed($this->_certInfo, $offset);
|
||||
$extraData = $this->_tpmReadLengthPrefixed($this->_certInfo, $offset);
|
||||
$coseAlg = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// Verify that extraData is set to the hash of attToBeSigned using the hash algorithm employed in "alg".
|
||||
if ($extraData->getBinaryString() !== \hash($coseAlg->hash, $attToBeSigned, true)) {
|
||||
throw new WebAuthnException('certInfo:extraData not hash of attToBeSigned', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify the sig is a valid signature over certInfo using the attestation
|
||||
// public key in aikCert with the algorithm specified in alg.
|
||||
return \openssl_verify($this->_certInfo->getBinaryString(), $this->_signature, $publicKey, $coseAlg->openssl) === 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns next part of ByteBuffer
|
||||
* @param ByteBuffer $buffer
|
||||
* @param int $offset
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
protected function _tpmReadLengthPrefixed(ByteBuffer $buffer, &$offset) {
|
||||
$len = $buffer->getUint16Val($offset);
|
||||
$data = $buffer->getBytes($offset + 2, $len);
|
||||
$offset += (2 + $len);
|
||||
|
||||
return new ByteBuffer($data);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
93
app-code/api/account/Attestation/Format/U2f.php
Normal file
93
app-code/api/account/Attestation/Format/U2f.php
Normal file
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class U2f extends FormatBase {
|
||||
private $_alg = -7;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check u2f data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (\array_key_exists('alg', $attStmt) && $attStmt['alg'] !== $this->_alg) {
|
||||
throw new WebAuthnException('u2f only accepts algorithm -7 ("ES256"), but got ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('x5c', $attStmt) || !\is_array($attStmt['x5c']) || \count($attStmt['x5c']) !== 1) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\is_object($attStmt['x5c'][0]) || !($attStmt['x5c'][0] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_x5c = $attStmt['x5c'][0]->getBinaryString();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
$pem = '-----BEGIN CERTIFICATE-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($this->_x5c), 64, "\n");
|
||||
$pem .= '-----END CERTIFICATE-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Let verificationData be the concatenation of (0x00 || rpIdHash || clientDataHash || credentialId || publicKeyU2F)
|
||||
$dataToVerify = "\x00";
|
||||
$dataToVerify .= $this->_authenticatorData->getRpIdHash();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
$dataToVerify .= $this->_authenticatorData->getCredentialId();
|
||||
$dataToVerify .= $this->_authenticatorData->getPublicKeyU2F();
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
300
app-code/api/account/Binary/ByteBuffer.php
Normal file
300
app-code/api/account/Binary/ByteBuffer.php
Normal file
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Binary;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
|
||||
/**
|
||||
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/ByteBuffer.php
|
||||
* Copyright © 2018 Thomas Bleeker - MIT licensed
|
||||
* Modified by Lukas Buchs
|
||||
* Thanks Thomas for your work!
|
||||
*/
|
||||
class ByteBuffer implements \JsonSerializable, \Serializable {
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
public static $useBase64UrlEncoding = false;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $_data;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $_length;
|
||||
|
||||
public function __construct($binaryData) {
|
||||
$this->_data = (string)$binaryData;
|
||||
$this->_length = \strlen($binaryData);
|
||||
}
|
||||
|
||||
|
||||
// -----------------------
|
||||
// PUBLIC STATIC
|
||||
// -----------------------
|
||||
|
||||
/**
|
||||
* create a ByteBuffer from a base64 url encoded string
|
||||
* @param string $base64url
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public static function fromBase64Url($base64url): ByteBuffer {
|
||||
$bin = self::_base64url_decode($base64url);
|
||||
if ($bin === false) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid base64 url string', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return new ByteBuffer($bin);
|
||||
}
|
||||
|
||||
/**
|
||||
* create a ByteBuffer from a base64 url encoded string
|
||||
* @param string $hex
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public static function fromHex($hex): ByteBuffer {
|
||||
$bin = \hex2bin($hex);
|
||||
if ($bin === false) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid hex string', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return new ByteBuffer($bin);
|
||||
}
|
||||
|
||||
/**
|
||||
* create a random ByteBuffer
|
||||
* @param string $length
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public static function randomBuffer($length): ByteBuffer {
|
||||
if (\function_exists('random_bytes')) { // >PHP 7.0
|
||||
return new ByteBuffer(\random_bytes($length));
|
||||
|
||||
} else if (\function_exists('openssl_random_pseudo_bytes')) {
|
||||
return new ByteBuffer(\openssl_random_pseudo_bytes($length));
|
||||
|
||||
} else {
|
||||
throw new WebAuthnException('ByteBuffer: cannot generate random bytes', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------
|
||||
// PUBLIC
|
||||
// -----------------------
|
||||
|
||||
public function getBytes($offset, $length): string {
|
||||
if ($offset < 0 || $length < 0 || ($offset + $length > $this->_length)) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset or length', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return \substr($this->_data, $offset, $length);
|
||||
}
|
||||
|
||||
public function getByteVal($offset): int {
|
||||
if ($offset < 0 || $offset >= $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return \ord(\substr($this->_data, $offset, 1));
|
||||
}
|
||||
|
||||
public function getJson($jsonFlags=0) {
|
||||
$data = \json_decode($this->getBinaryString(), null, 512, $jsonFlags);
|
||||
if (\json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new WebAuthnException(\json_last_error_msg(), WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function getLength(): int {
|
||||
return $this->_length;
|
||||
}
|
||||
|
||||
public function getUint16Val($offset) {
|
||||
if ($offset < 0 || ($offset + 2) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return unpack('n', $this->_data, $offset)[1];
|
||||
}
|
||||
|
||||
public function getUint32Val($offset) {
|
||||
if ($offset < 0 || ($offset + 4) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
$val = unpack('N', $this->_data, $offset)[1];
|
||||
|
||||
// Signed integer overflow causes signed negative numbers
|
||||
if ($val < 0) {
|
||||
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return $val;
|
||||
}
|
||||
|
||||
public function getUint64Val($offset) {
|
||||
if (PHP_INT_SIZE < 8) {
|
||||
throw new WebAuthnException('ByteBuffer: 64-bit values not supported by this system', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
if ($offset < 0 || ($offset + 8) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
$val = unpack('J', $this->_data, $offset)[1];
|
||||
|
||||
// Signed integer overflow causes signed negative numbers
|
||||
if ($val < 0) {
|
||||
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
|
||||
return $val;
|
||||
}
|
||||
|
||||
public function getHalfFloatVal($offset) {
|
||||
//FROM spec pseudo decode_half(unsigned char *halfp)
|
||||
$half = $this->getUint16Val($offset);
|
||||
|
||||
$exp = ($half >> 10) & 0x1f;
|
||||
$mant = $half & 0x3ff;
|
||||
|
||||
if ($exp === 0) {
|
||||
$val = $mant * (2 ** -24);
|
||||
} elseif ($exp !== 31) {
|
||||
$val = ($mant + 1024) * (2 ** ($exp - 25));
|
||||
} else {
|
||||
$val = ($mant === 0) ? INF : NAN;
|
||||
}
|
||||
|
||||
return ($half & 0x8000) ? -$val : $val;
|
||||
}
|
||||
|
||||
public function getFloatVal($offset) {
|
||||
if ($offset < 0 || ($offset + 4) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return unpack('G', $this->_data, $offset)[1];
|
||||
}
|
||||
|
||||
public function getDoubleVal($offset) {
|
||||
if ($offset < 0 || ($offset + 8) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return unpack('E', $this->_data, $offset)[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getBinaryString(): string {
|
||||
return $this->_data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|ByteBuffer $buffer
|
||||
* @return bool
|
||||
*/
|
||||
public function equals($buffer): bool {
|
||||
if (is_object($buffer) && $buffer instanceof ByteBuffer) {
|
||||
return $buffer->getBinaryString() === $this->getBinaryString();
|
||||
|
||||
} else if (is_string($buffer)) {
|
||||
return $buffer === $this->getBinaryString();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getHex(): string {
|
||||
return \bin2hex($this->_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isEmpty(): bool {
|
||||
return $this->_length === 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* jsonSerialize interface
|
||||
* return binary data in RFC 1342-Like serialized string
|
||||
* @return string
|
||||
*/
|
||||
public function jsonSerialize(): string {
|
||||
if (ByteBuffer::$useBase64UrlEncoding) {
|
||||
return self::_base64url_encode($this->_data);
|
||||
|
||||
} else {
|
||||
return '=?BINARY?B?' . \base64_encode($this->_data) . '?=';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializable-Interface
|
||||
* @return string
|
||||
*/
|
||||
public function serialize(): string {
|
||||
return \serialize($this->_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializable-Interface
|
||||
* @param string $serialized
|
||||
*/
|
||||
public function unserialize($serialized) {
|
||||
$this->_data = \unserialize($serialized);
|
||||
$this->_length = \strlen($this->_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* (PHP 8 deprecates Serializable-Interface)
|
||||
* @return array
|
||||
*/
|
||||
public function __serialize(): array {
|
||||
return [
|
||||
'data' => \serialize($this->_data)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* object to string
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string {
|
||||
return $this->getHex();
|
||||
}
|
||||
|
||||
/**
|
||||
* (PHP 8 deprecates Serializable-Interface)
|
||||
* @param array $data
|
||||
* @return void
|
||||
*/
|
||||
public function __unserialize($data) {
|
||||
if ($data && isset($data['data'])) {
|
||||
$this->_data = \unserialize($data['data']);
|
||||
$this->_length = \strlen($this->_data);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------
|
||||
// PROTECTED STATIC
|
||||
// -----------------------
|
||||
|
||||
/**
|
||||
* base64 url decoding
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
protected static function _base64url_decode($data): string {
|
||||
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
|
||||
}
|
||||
|
||||
/**
|
||||
* base64 url encoding
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
protected static function _base64url_encode($data): string {
|
||||
return \rtrim(\strtr(\base64_encode($data), '+/', '-_'), '=');
|
||||
}
|
||||
}
|
||||
220
app-code/api/account/CBOR/CborDecoder.php
Normal file
220
app-code/api/account/CBOR/CborDecoder.php
Normal file
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\CBOR;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/CborDecoder.php
|
||||
* Copyright © 2018 Thomas Bleeker - MIT licensed
|
||||
* Modified by Lukas Buchs
|
||||
* Thanks Thomas for your work!
|
||||
*/
|
||||
class CborDecoder {
|
||||
const CBOR_MAJOR_UNSIGNED_INT = 0;
|
||||
const CBOR_MAJOR_TEXT_STRING = 3;
|
||||
const CBOR_MAJOR_FLOAT_SIMPLE = 7;
|
||||
const CBOR_MAJOR_NEGATIVE_INT = 1;
|
||||
const CBOR_MAJOR_ARRAY = 4;
|
||||
const CBOR_MAJOR_TAG = 6;
|
||||
const CBOR_MAJOR_MAP = 5;
|
||||
const CBOR_MAJOR_BYTE_STRING = 2;
|
||||
|
||||
/**
|
||||
* @param ByteBuffer|string $bufOrBin
|
||||
* @return mixed
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public static function decode($bufOrBin) {
|
||||
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
|
||||
|
||||
$offset = 0;
|
||||
$result = self::_parseItem($buf, $offset);
|
||||
if ($offset !== $buf->getLength()) {
|
||||
throw new WebAuthnException('Unused bytes after data item.', WebAuthnException::CBOR);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ByteBuffer|string $bufOrBin
|
||||
* @param int $startOffset
|
||||
* @param int|null $endOffset
|
||||
* @return mixed
|
||||
*/
|
||||
public static function decodeInPlace($bufOrBin, $startOffset, &$endOffset = null) {
|
||||
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
|
||||
|
||||
$offset = $startOffset;
|
||||
$data = self::_parseItem($buf, $offset);
|
||||
$endOffset = $offset;
|
||||
return $data;
|
||||
}
|
||||
|
||||
// ---------------------
|
||||
// protected
|
||||
// ---------------------
|
||||
|
||||
/**
|
||||
* @param ByteBuffer $buf
|
||||
* @param int $offset
|
||||
* @return mixed
|
||||
*/
|
||||
protected static function _parseItem(ByteBuffer $buf, &$offset) {
|
||||
$first = $buf->getByteVal($offset++);
|
||||
$type = $first >> 5;
|
||||
$val = $first & 0b11111;
|
||||
|
||||
if ($type === self::CBOR_MAJOR_FLOAT_SIMPLE) {
|
||||
return self::_parseFloatSimple($val, $buf, $offset);
|
||||
}
|
||||
|
||||
$val = self::_parseExtraLength($val, $buf, $offset);
|
||||
|
||||
return self::_parseItemData($type, $val, $buf, $offset);
|
||||
}
|
||||
|
||||
protected static function _parseFloatSimple($val, ByteBuffer $buf, &$offset) {
|
||||
switch ($val) {
|
||||
case 24:
|
||||
$val = $buf->getByteVal($offset);
|
||||
$offset++;
|
||||
return self::_parseSimple($val);
|
||||
|
||||
case 25:
|
||||
$floatValue = $buf->getHalfFloatVal($offset);
|
||||
$offset += 2;
|
||||
return $floatValue;
|
||||
|
||||
case 26:
|
||||
$floatValue = $buf->getFloatVal($offset);
|
||||
$offset += 4;
|
||||
return $floatValue;
|
||||
|
||||
case 27:
|
||||
$floatValue = $buf->getDoubleVal($offset);
|
||||
$offset += 8;
|
||||
return $floatValue;
|
||||
|
||||
case 28:
|
||||
case 29:
|
||||
case 30:
|
||||
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
|
||||
|
||||
case 31:
|
||||
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
return self::_parseSimple($val);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $val
|
||||
* @return mixed
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected static function _parseSimple($val) {
|
||||
if ($val === 20) {
|
||||
return false;
|
||||
}
|
||||
if ($val === 21) {
|
||||
return true;
|
||||
}
|
||||
if ($val === 22) {
|
||||
return null;
|
||||
}
|
||||
throw new WebAuthnException(sprintf('Unsupported simple value %d.', $val), WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
protected static function _parseExtraLength($val, ByteBuffer $buf, &$offset) {
|
||||
switch ($val) {
|
||||
case 24:
|
||||
$val = $buf->getByteVal($offset);
|
||||
$offset++;
|
||||
break;
|
||||
|
||||
case 25:
|
||||
$val = $buf->getUint16Val($offset);
|
||||
$offset += 2;
|
||||
break;
|
||||
|
||||
case 26:
|
||||
$val = $buf->getUint32Val($offset);
|
||||
$offset += 4;
|
||||
break;
|
||||
|
||||
case 27:
|
||||
$val = $buf->getUint64Val($offset);
|
||||
$offset += 8;
|
||||
break;
|
||||
|
||||
case 28:
|
||||
case 29:
|
||||
case 30:
|
||||
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
|
||||
|
||||
case 31:
|
||||
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
return $val;
|
||||
}
|
||||
|
||||
protected static function _parseItemData($type, $val, ByteBuffer $buf, &$offset) {
|
||||
switch ($type) {
|
||||
case self::CBOR_MAJOR_UNSIGNED_INT: // uint
|
||||
return $val;
|
||||
|
||||
case self::CBOR_MAJOR_NEGATIVE_INT:
|
||||
return -1 - $val;
|
||||
|
||||
case self::CBOR_MAJOR_BYTE_STRING:
|
||||
$data = $buf->getBytes($offset, $val);
|
||||
$offset += $val;
|
||||
return new ByteBuffer($data); // bytes
|
||||
|
||||
case self::CBOR_MAJOR_TEXT_STRING:
|
||||
$data = $buf->getBytes($offset, $val);
|
||||
$offset += $val;
|
||||
return $data; // UTF-8
|
||||
|
||||
case self::CBOR_MAJOR_ARRAY:
|
||||
return self::_parseArray($buf, $offset, $val);
|
||||
|
||||
case self::CBOR_MAJOR_MAP:
|
||||
return self::_parseMap($buf, $offset, $val);
|
||||
|
||||
case self::CBOR_MAJOR_TAG:
|
||||
return self::_parseItem($buf, $offset); // 1 embedded data item
|
||||
}
|
||||
|
||||
// This should never be reached
|
||||
throw new WebAuthnException(sprintf('Unknown major type %d.', $type), WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
protected static function _parseMap(ByteBuffer $buf, &$offset, $count) {
|
||||
$map = array();
|
||||
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$mapKey = self::_parseItem($buf, $offset);
|
||||
$mapVal = self::_parseItem($buf, $offset);
|
||||
|
||||
if (!\is_int($mapKey) && !\is_string($mapKey)) {
|
||||
throw new WebAuthnException('Can only use strings or integers as map keys', WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
$map[$mapKey] = $mapVal; // todo dup
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
|
||||
protected static function _parseArray(ByteBuffer $buf, &$offset, $count) {
|
||||
$arr = array();
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$arr[] = self::_parseItem($buf, $offset);
|
||||
}
|
||||
|
||||
return $arr;
|
||||
}
|
||||
}
|
||||
677
app-code/api/account/WebAuthn.php
Normal file
677
app-code/api/account/WebAuthn.php
Normal file
@@ -0,0 +1,677 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
require_once 'WebAuthnException.php';
|
||||
require_once 'Binary/ByteBuffer.php';
|
||||
require_once 'Attestation/AttestationObject.php';
|
||||
require_once 'Attestation/AuthenticatorData.php';
|
||||
require_once 'Attestation/Format/FormatBase.php';
|
||||
require_once 'Attestation/Format/None.php';
|
||||
require_once 'Attestation/Format/AndroidKey.php';
|
||||
require_once 'Attestation/Format/AndroidSafetyNet.php';
|
||||
require_once 'Attestation/Format/Apple.php';
|
||||
require_once 'Attestation/Format/Packed.php';
|
||||
require_once 'Attestation/Format/Tpm.php';
|
||||
require_once 'Attestation/Format/U2f.php';
|
||||
require_once 'CBOR/CborDecoder.php';
|
||||
|
||||
/**
|
||||
* WebAuthn
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class WebAuthn {
|
||||
// relying party
|
||||
private $_rpName;
|
||||
private $_rpId;
|
||||
private $_rpIdHash;
|
||||
private $_challenge;
|
||||
private $_signatureCounter;
|
||||
private $_caFiles;
|
||||
private $_formats;
|
||||
|
||||
/**
|
||||
* Initialize a new WebAuthn server
|
||||
* @param string $rpName the relying party name
|
||||
* @param string $rpId the relying party ID = the domain name
|
||||
* @param bool $useBase64UrlEncoding true to use base64 url encoding for binary data in json objects. Default is a RFC 1342-Like serialized string.
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function __construct($rpName, $rpId, $allowedFormats=null, $useBase64UrlEncoding=false) {
|
||||
$this->_rpName = $rpName;
|
||||
$this->_rpId = $rpId;
|
||||
$this->_rpIdHash = \hash('sha256', $rpId, true);
|
||||
ByteBuffer::$useBase64UrlEncoding = !!$useBase64UrlEncoding;
|
||||
$supportedFormats = array('android-key', 'android-safetynet', 'apple', 'fido-u2f', 'none', 'packed', 'tpm');
|
||||
|
||||
if (!\function_exists('\openssl_open')) {
|
||||
throw new WebAuthnException('OpenSSL-Module not installed');
|
||||
}
|
||||
|
||||
if (!\in_array('SHA256', \array_map('\strtoupper', \openssl_get_md_methods()))) {
|
||||
throw new WebAuthnException('SHA256 not supported by this openssl installation.');
|
||||
}
|
||||
|
||||
// default: all format
|
||||
if (!is_array($allowedFormats)) {
|
||||
$allowedFormats = $supportedFormats;
|
||||
}
|
||||
$this->_formats = $allowedFormats;
|
||||
|
||||
// validate formats
|
||||
$invalidFormats = \array_diff($this->_formats, $supportedFormats);
|
||||
if (!$this->_formats || $invalidFormats) {
|
||||
throw new WebAuthnException('invalid formats on construct: ' . implode(', ', $invalidFormats));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* add a root certificate to verify new registrations
|
||||
* @param string $path file path of / directory with root certificates
|
||||
* @param array|null $certFileExtensions if adding a direction, all files with provided extension are added. default: pem, crt, cer, der
|
||||
*/
|
||||
public function addRootCertificates($path, $certFileExtensions=null) {
|
||||
if (!\is_array($this->_caFiles)) {
|
||||
$this->_caFiles = [];
|
||||
}
|
||||
if ($certFileExtensions === null) {
|
||||
$certFileExtensions = array('pem', 'crt', 'cer', 'der');
|
||||
}
|
||||
$path = \rtrim(\trim($path), '\\/');
|
||||
if (\is_dir($path)) {
|
||||
foreach (\scandir($path) as $ca) {
|
||||
if (\is_file($path . DIRECTORY_SEPARATOR . $ca) && \in_array(\strtolower(\pathinfo($ca, PATHINFO_EXTENSION)), $certFileExtensions)) {
|
||||
$this->addRootCertificates($path . DIRECTORY_SEPARATOR . $ca);
|
||||
}
|
||||
}
|
||||
} else if (\is_file($path) && !\in_array(\realpath($path), $this->_caFiles)) {
|
||||
$this->_caFiles[] = \realpath($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the generated challenge to save for later validation
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public function getChallenge() {
|
||||
return $this->_challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates the object for a key registration
|
||||
* provide this data to navigator.credentials.create
|
||||
* @param string $userId
|
||||
* @param string $userName
|
||||
* @param string $userDisplayName
|
||||
* @param int $timeout timeout in seconds
|
||||
* @param bool|string $requireResidentKey 'required', if the key should be stored by the authentication device
|
||||
* Valid values:
|
||||
* true = required
|
||||
* false = preferred
|
||||
* string 'required' 'preferred' 'discouraged'
|
||||
* @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
|
||||
* if the response does not have the UV flag set.
|
||||
* Valid values:
|
||||
* true = required
|
||||
* false = preferred
|
||||
* string 'required' 'preferred' 'discouraged'
|
||||
* @param bool|null $crossPlatformAttachment true for cross-platform devices (eg. fido usb),
|
||||
* false for platform devices (eg. windows hello, android safetynet),
|
||||
* null for both
|
||||
* @param array $excludeCredentialIds a array of ids, which are already registered, to prevent re-registration
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function getCreateArgs($userId, $userName, $userDisplayName, $timeout=20, $requireResidentKey=false, $requireUserVerification=false, $crossPlatformAttachment=null, $excludeCredentialIds=[]) {
|
||||
|
||||
$args = new \stdClass();
|
||||
$args->publicKey = new \stdClass();
|
||||
|
||||
// relying party
|
||||
$args->publicKey->rp = new \stdClass();
|
||||
$args->publicKey->rp->name = $this->_rpName;
|
||||
$args->publicKey->rp->id = $this->_rpId;
|
||||
|
||||
$args->publicKey->authenticatorSelection = new \stdClass();
|
||||
$args->publicKey->authenticatorSelection->userVerification = 'preferred';
|
||||
|
||||
// validate User Verification Requirement
|
||||
if (\is_bool($requireUserVerification)) {
|
||||
$args->publicKey->authenticatorSelection->userVerification = $requireUserVerification ? 'required' : 'preferred';
|
||||
|
||||
} else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
|
||||
$args->publicKey->authenticatorSelection->userVerification = \strtolower($requireUserVerification);
|
||||
}
|
||||
|
||||
// validate Resident Key Requirement
|
||||
if (\is_bool($requireResidentKey) && $requireResidentKey) {
|
||||
$args->publicKey->authenticatorSelection->requireResidentKey = true;
|
||||
$args->publicKey->authenticatorSelection->residentKey = 'required';
|
||||
|
||||
} else if (\is_string($requireResidentKey) && \in_array(\strtolower($requireResidentKey), ['required', 'preferred', 'discouraged'])) {
|
||||
$requireResidentKey = \strtolower($requireResidentKey);
|
||||
$args->publicKey->authenticatorSelection->residentKey = $requireResidentKey;
|
||||
$args->publicKey->authenticatorSelection->requireResidentKey = $requireResidentKey === 'required';
|
||||
}
|
||||
|
||||
// filte authenticators attached with the specified authenticator attachment modality
|
||||
if (\is_bool($crossPlatformAttachment)) {
|
||||
$args->publicKey->authenticatorSelection->authenticatorAttachment = $crossPlatformAttachment ? 'cross-platform' : 'platform';
|
||||
}
|
||||
|
||||
// user
|
||||
$args->publicKey->user = new \stdClass();
|
||||
$args->publicKey->user->id = new ByteBuffer($userId); // binary
|
||||
$args->publicKey->user->name = $userName;
|
||||
$args->publicKey->user->displayName = $userDisplayName;
|
||||
|
||||
// supported algorithms
|
||||
$args->publicKey->pubKeyCredParams = [];
|
||||
|
||||
if (function_exists('sodium_crypto_sign_verify_detached') || \in_array('ed25519', \openssl_get_curve_names(), true)) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -8; // EdDSA
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
|
||||
if (\in_array('prime256v1', \openssl_get_curve_names(), true)) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -7; // ES256
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -257; // RS256
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
|
||||
// if there are root certificates added, we need direct attestation to validate
|
||||
// against the root certificate. If there are no root-certificates added,
|
||||
// anonymization ca are also accepted, because we can't validate the root anyway.
|
||||
$attestation = 'indirect';
|
||||
if (\is_array($this->_caFiles)) {
|
||||
$attestation = 'direct';
|
||||
}
|
||||
|
||||
$args->publicKey->attestation = \count($this->_formats) === 1 && \in_array('none', $this->_formats) ? 'none' : $attestation;
|
||||
$args->publicKey->extensions = new \stdClass();
|
||||
$args->publicKey->extensions->exts = true;
|
||||
$args->publicKey->timeout = $timeout * 1000; // microseconds
|
||||
$args->publicKey->challenge = $this->_createChallenge(); // binary
|
||||
|
||||
//prevent re-registration by specifying existing credentials
|
||||
$args->publicKey->excludeCredentials = [];
|
||||
|
||||
if (is_array($excludeCredentialIds)) {
|
||||
foreach ($excludeCredentialIds as $id) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id); // binary
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->transports = array('usb', 'nfc', 'ble', 'hybrid', 'internal');
|
||||
$args->publicKey->excludeCredentials[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
}
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates the object for key validation
|
||||
* Provide this data to navigator.credentials.get
|
||||
* @param array $credentialIds binary
|
||||
* @param int $timeout timeout in seconds
|
||||
* @param bool $allowUsb allow removable USB
|
||||
* @param bool $allowNfc allow Near Field Communication (NFC)
|
||||
* @param bool $allowBle allow Bluetooth
|
||||
* @param bool $allowHybrid allow a combination of (often separate) data-transport and proximity mechanisms.
|
||||
* @param bool $allowInternal allow client device-specific transport. These authenticators are not removable from the client device.
|
||||
* @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
|
||||
* if the response does not have the UV flag set.
|
||||
* Valid values:
|
||||
* true = required
|
||||
* false = preferred
|
||||
* string 'required' 'preferred' 'discouraged'
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function getGetArgs($credentialIds=[], $timeout=20, $allowUsb=true, $allowNfc=true, $allowBle=true, $allowHybrid=true, $allowInternal=true, $requireUserVerification=false) {
|
||||
|
||||
// validate User Verification Requirement
|
||||
if (\is_bool($requireUserVerification)) {
|
||||
$requireUserVerification = $requireUserVerification ? 'required' : 'preferred';
|
||||
} else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
|
||||
$requireUserVerification = \strtolower($requireUserVerification);
|
||||
} else {
|
||||
$requireUserVerification = 'preferred';
|
||||
}
|
||||
|
||||
$args = new \stdClass();
|
||||
$args->publicKey = new \stdClass();
|
||||
$args->publicKey->timeout = $timeout * 1000; // microseconds
|
||||
$args->publicKey->challenge = $this->_createChallenge(); // binary
|
||||
$args->publicKey->userVerification = $requireUserVerification;
|
||||
$args->publicKey->rpId = $this->_rpId;
|
||||
|
||||
if (\is_array($credentialIds) && \count($credentialIds) > 0) {
|
||||
$args->publicKey->allowCredentials = [];
|
||||
|
||||
foreach ($credentialIds as $id) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id); // binary
|
||||
$tmp->transports = [];
|
||||
|
||||
if ($allowUsb) {
|
||||
$tmp->transports[] = 'usb';
|
||||
}
|
||||
if ($allowNfc) {
|
||||
$tmp->transports[] = 'nfc';
|
||||
}
|
||||
if ($allowBle) {
|
||||
$tmp->transports[] = 'ble';
|
||||
}
|
||||
if ($allowHybrid) {
|
||||
$tmp->transports[] = 'hybrid';
|
||||
}
|
||||
if ($allowInternal) {
|
||||
$tmp->transports[] = 'internal';
|
||||
}
|
||||
|
||||
$tmp->type = 'public-key';
|
||||
$args->publicKey->allowCredentials[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
}
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the new signature counter value.
|
||||
* returns null if there is no counter
|
||||
* @return ?int
|
||||
*/
|
||||
public function getSignatureCounter() {
|
||||
return \is_int($this->_signatureCounter) ? $this->_signatureCounter : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* process a create request and returns data to save for future logins
|
||||
* @param string $clientDataJSON binary from browser
|
||||
* @param string $attestationObject binary from browser
|
||||
* @param string|ByteBuffer $challenge binary used challange
|
||||
* @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
|
||||
* @param bool $requireUserPresent false, if the device must NOT check user presence (e.g. by pressing a button)
|
||||
* @param bool $failIfRootMismatch false, if there should be no error thrown if root certificate doesn't match
|
||||
* @param bool $requireCtsProfileMatch false, if you don't want to check if the device is approved as a Google-certified Android device.
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function processCreate($clientDataJSON, $attestationObject, $challenge, $requireUserVerification=false, $requireUserPresent=true, $failIfRootMismatch=true, $requireCtsProfileMatch=true) {
|
||||
$clientDataHash = \hash('sha256', $clientDataJSON, true);
|
||||
$clientData = \json_decode($clientDataJSON);
|
||||
$challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
|
||||
|
||||
// security: https://www.w3.org/TR/webauthn/#registering-a-new-credential
|
||||
|
||||
// 2. Let C, the client data claimed as collected during the credential creation,
|
||||
// be the result of running an implementation-specific JSON parser on JSONtext.
|
||||
if (!\is_object($clientData)) {
|
||||
throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// 3. Verify that the value of C.type is webauthn.create.
|
||||
if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.create') {
|
||||
throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
|
||||
}
|
||||
|
||||
// 4. Verify that the value of C.challenge matches the challenge that was sent to the authenticator in the create() call.
|
||||
if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
|
||||
throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
|
||||
}
|
||||
|
||||
// 5. Verify that the value of C.origin matches the Relying Party's origin.
|
||||
if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
|
||||
throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// Attestation
|
||||
$attestationObject = new Attestation\AttestationObject($attestationObject, $this->_formats);
|
||||
|
||||
// 9. Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
|
||||
if (!$attestationObject->validateRpIdHash($this->_rpIdHash)) {
|
||||
throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
|
||||
}
|
||||
|
||||
// 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature
|
||||
if (!$attestationObject->validateAttestation($clientDataHash)) {
|
||||
throw new WebAuthnException('invalid certificate signature', WebAuthnException::INVALID_SIGNATURE);
|
||||
}
|
||||
|
||||
// Android-SafetyNet: if required, check for Compatibility Testing Suite (CTS).
|
||||
if ($requireCtsProfileMatch && $attestationObject->getAttestationFormat() instanceof Attestation\Format\AndroidSafetyNet) {
|
||||
if (!$attestationObject->getAttestationFormat()->ctsProfileMatch()) {
|
||||
throw new WebAuthnException('invalid ctsProfileMatch: device is not approved as a Google-certified Android device.', WebAuthnException::ANDROID_NOT_TRUSTED);
|
||||
}
|
||||
}
|
||||
|
||||
// 15. If validation is successful, obtain a list of acceptable trust anchors
|
||||
$rootValid = is_array($this->_caFiles) ? $attestationObject->validateRootCertificate($this->_caFiles) : null;
|
||||
if ($failIfRootMismatch && is_array($this->_caFiles) && !$rootValid) {
|
||||
throw new WebAuthnException('invalid root certificate', WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
|
||||
// 10. Verify that the User Present bit of the flags in authData is set.
|
||||
$userPresent = $attestationObject->getAuthenticatorData()->getUserPresent();
|
||||
if ($requireUserPresent && !$userPresent) {
|
||||
throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
|
||||
}
|
||||
|
||||
// 11. If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
|
||||
$userVerified = $attestationObject->getAuthenticatorData()->getUserVerified();
|
||||
if ($requireUserVerification && !$userVerified) {
|
||||
throw new WebAuthnException('user not verified during authentication', WebAuthnException::USER_VERIFICATED);
|
||||
}
|
||||
|
||||
$signCount = $attestationObject->getAuthenticatorData()->getSignCount();
|
||||
if ($signCount > 0) {
|
||||
$this->_signatureCounter = $signCount;
|
||||
}
|
||||
|
||||
// prepare data to store for future logins
|
||||
$data = new \stdClass();
|
||||
$data->rpId = $this->_rpId;
|
||||
$data->attestationFormat = $attestationObject->getAttestationFormatName();
|
||||
$data->credentialId = $attestationObject->getAuthenticatorData()->getCredentialId();
|
||||
$data->credentialPublicKey = $attestationObject->getAuthenticatorData()->getPublicKeyPem();
|
||||
$data->certificateChain = $attestationObject->getCertificateChain();
|
||||
$data->certificate = $attestationObject->getCertificatePem();
|
||||
$data->certificateIssuer = $attestationObject->getCertificateIssuer();
|
||||
$data->certificateSubject = $attestationObject->getCertificateSubject();
|
||||
$data->signatureCounter = $this->_signatureCounter;
|
||||
$data->AAGUID = $attestationObject->getAuthenticatorData()->getAAGUID();
|
||||
$data->rootValid = $rootValid;
|
||||
$data->userPresent = $userPresent;
|
||||
$data->userVerified = $userVerified;
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* process a get request
|
||||
* @param string $clientDataJSON binary from browser
|
||||
* @param string $authenticatorData binary from browser
|
||||
* @param string $signature binary from browser
|
||||
* @param string $credentialPublicKey string PEM-formated public key from used credentialId
|
||||
* @param string|ByteBuffer $challenge binary from used challange
|
||||
* @param int $prevSignatureCnt signature count value of the last login
|
||||
* @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
|
||||
* @param bool $requireUserPresent true, if the device must check user presence (e.g. by pressing a button)
|
||||
* @return boolean true if get is successful
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function processGet($clientDataJSON, $authenticatorData, $signature, $credentialPublicKey, $challenge, $prevSignatureCnt=null, $requireUserVerification=false, $requireUserPresent=true) {
|
||||
$authenticatorObj = new Attestation\AuthenticatorData($authenticatorData);
|
||||
$clientDataHash = \hash('sha256', $clientDataJSON, true);
|
||||
$clientData = \json_decode($clientDataJSON);
|
||||
$challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
|
||||
|
||||
// https://www.w3.org/TR/webauthn/#verifying-assertion
|
||||
|
||||
// 1. If the allowCredentials option was given when this authentication ceremony was initiated,
|
||||
// verify that credential.id identifies one of the public key credentials that were listed in allowCredentials.
|
||||
// -> TO BE VERIFIED BY IMPLEMENTATION
|
||||
|
||||
// 2. If credential.response.userHandle is present, verify that the user identified
|
||||
// by this value is the owner of the public key credential identified by credential.id.
|
||||
// -> TO BE VERIFIED BY IMPLEMENTATION
|
||||
|
||||
// 3. Using credential’s id attribute (or the corresponding rawId, if base64url encoding is
|
||||
// inappropriate for your use case), look up the corresponding credential public key.
|
||||
// -> TO BE LOOKED UP BY IMPLEMENTATION
|
||||
|
||||
// 5. Let JSONtext be the result of running UTF-8 decode on the value of cData.
|
||||
if (!\is_object($clientData)) {
|
||||
throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// 7. Verify that the value of C.type is the string webauthn.get.
|
||||
if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.get') {
|
||||
throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
|
||||
}
|
||||
|
||||
// 8. Verify that the value of C.challenge matches the challenge that was sent to the
|
||||
// authenticator in the PublicKeyCredentialRequestOptions passed to the get() call.
|
||||
if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
|
||||
throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
|
||||
}
|
||||
|
||||
// 9. Verify that the value of C.origin matches the Relying Party's origin.
|
||||
if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
|
||||
throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// 11. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party.
|
||||
if ($authenticatorObj->getRpIdHash() !== $this->_rpIdHash) {
|
||||
throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
|
||||
}
|
||||
|
||||
// 12. Verify that the User Present bit of the flags in authData is set
|
||||
if ($requireUserPresent && !$authenticatorObj->getUserPresent()) {
|
||||
throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
|
||||
}
|
||||
|
||||
// 13. If user verification is required for this assertion, verify that the User Verified bit of the flags in authData is set.
|
||||
if ($requireUserVerification && !$authenticatorObj->getUserVerified()) {
|
||||
throw new WebAuthnException('user not verificated during authentication', WebAuthnException::USER_VERIFICATED);
|
||||
}
|
||||
|
||||
// 14. Verify the values of the client extension outputs
|
||||
// (extensions not implemented)
|
||||
|
||||
// 16. Using the credential public key looked up in step 3, verify that sig is a valid signature
|
||||
// over the binary concatenation of authData and hash.
|
||||
$dataToVerify = '';
|
||||
$dataToVerify .= $authenticatorData;
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
if (!$this->_verifySignature($dataToVerify, $signature, $credentialPublicKey)) {
|
||||
throw new WebAuthnException('invalid signature', WebAuthnException::INVALID_SIGNATURE);
|
||||
}
|
||||
|
||||
$signatureCounter = $authenticatorObj->getSignCount();
|
||||
if ($signatureCounter !== 0) {
|
||||
$this->_signatureCounter = $signatureCounter;
|
||||
}
|
||||
|
||||
// 17. If either of the signature counter value authData.signCount or
|
||||
// previous signature count is nonzero, and if authData.signCount
|
||||
// less than or equal to previous signature count, it's a signal
|
||||
// that the authenticator may be cloned
|
||||
if ($prevSignatureCnt !== null) {
|
||||
if ($signatureCounter !== 0 || $prevSignatureCnt !== 0) {
|
||||
if ($prevSignatureCnt >= $signatureCounter) {
|
||||
throw new WebAuthnException('signature counter not valid', WebAuthnException::SIGNATURE_COUNTER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads root certificates from FIDO Alliance Metadata Service (MDS) to a specific folder
|
||||
* https://fidoalliance.org/metadata/
|
||||
* @param string $certFolder Folder path to save the certificates in PEM format.
|
||||
* @param bool $deleteCerts delete certificates in the target folder before adding the new ones.
|
||||
* @return int number of cetificates
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function queryFidoMetaDataService($certFolder, $deleteCerts=true) {
|
||||
$url = 'https://mds.fidoalliance.org/';
|
||||
$raw = null;
|
||||
if (\function_exists('curl_init')) {
|
||||
$ch = \curl_init($url);
|
||||
\curl_setopt($ch, CURLOPT_HEADER, false);
|
||||
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
\curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
||||
\curl_setopt($ch, CURLOPT_USERAGENT, 'github.com/lbuchs/WebAuthn - A simple PHP WebAuthn server library');
|
||||
$raw = \curl_exec($ch);
|
||||
\curl_close($ch);
|
||||
} else {
|
||||
$raw = \file_get_contents($url);
|
||||
}
|
||||
|
||||
$certFolder = \rtrim(\realpath($certFolder), '\\/');
|
||||
if (!is_dir($certFolder)) {
|
||||
throw new WebAuthnException('Invalid folder path for query FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
if (!\is_string($raw)) {
|
||||
throw new WebAuthnException('Unable to query FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
$jwt = \explode('.', $raw);
|
||||
if (\count($jwt) !== 3) {
|
||||
throw new WebAuthnException('Invalid JWT from FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
if ($deleteCerts) {
|
||||
foreach (\scandir($certFolder) as $ca) {
|
||||
if (\substr($ca, -4) === '.pem') {
|
||||
if (\unlink($certFolder . DIRECTORY_SEPARATOR . $ca) === false) {
|
||||
throw new WebAuthnException('Cannot delete certs in folder for FIDO Alliance Metadata Service');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list($header, $payload, $hash) = $jwt;
|
||||
$payload = Binary\ByteBuffer::fromBase64Url($payload)->getJson();
|
||||
|
||||
$count = 0;
|
||||
if (\is_object($payload) && \property_exists($payload, 'entries') && \is_array($payload->entries)) {
|
||||
foreach ($payload->entries as $entry) {
|
||||
if (\is_object($entry) && \property_exists($entry, 'metadataStatement') && \is_object($entry->metadataStatement)) {
|
||||
$description = $entry->metadataStatement->description ?? null;
|
||||
$attestationRootCertificates = $entry->metadataStatement->attestationRootCertificates ?? null;
|
||||
|
||||
if ($description && $attestationRootCertificates) {
|
||||
|
||||
// create filename
|
||||
$certFilename = \preg_replace('/[^a-z0-9]/i', '_', $description);
|
||||
$certFilename = \trim(\preg_replace('/\_{2,}/i', '_', $certFilename),'_') . '.pem';
|
||||
$certFilename = \strtolower($certFilename);
|
||||
|
||||
// add certificate
|
||||
$certContent = $description . "\n";
|
||||
$certContent .= \str_repeat('-', \mb_strlen($description)) . "\n";
|
||||
|
||||
foreach ($attestationRootCertificates as $attestationRootCertificate) {
|
||||
$attestationRootCertificate = \str_replace(["\n", "\r", ' '], '', \trim($attestationRootCertificate));
|
||||
$count++;
|
||||
$certContent .= "\n-----BEGIN CERTIFICATE-----\n";
|
||||
$certContent .= \chunk_split($attestationRootCertificate, 64, "\n");
|
||||
$certContent .= "-----END CERTIFICATE-----\n";
|
||||
}
|
||||
|
||||
if (\file_put_contents($certFolder . DIRECTORY_SEPARATOR . $certFilename, $certContent) === false) {
|
||||
throw new WebAuthnException('unable to save certificate from FIDO Alliance Metadata Service');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
// -----------------------------------------------
|
||||
// PRIVATE
|
||||
// -----------------------------------------------
|
||||
|
||||
/**
|
||||
* checks if the origin matchs the RP ID
|
||||
* @param string $origin
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _checkOrigin($origin) {
|
||||
// https://www.w3.org/TR/webauthn/#rp-id
|
||||
|
||||
// The origin's scheme must be https
|
||||
if ($this->_rpId !== 'localhost' && \parse_url($origin, PHP_URL_SCHEME) !== 'https') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// extract host from origin
|
||||
$host = \parse_url($origin, PHP_URL_HOST);
|
||||
$host = \trim($host, '.');
|
||||
|
||||
// The RP ID must be equal to the origin's effective domain, or a registrable
|
||||
// domain suffix of the origin's effective domain.
|
||||
return \preg_match('/' . \preg_quote($this->_rpId) . '$/i', $host) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates a new challange
|
||||
* @param int $length
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _createChallenge($length = 32) {
|
||||
if (!$this->_challenge) {
|
||||
$this->_challenge = ByteBuffer::randomBuffer($length);
|
||||
}
|
||||
return $this->_challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if the signature is valid.
|
||||
* @param string $dataToVerify
|
||||
* @param string $signature
|
||||
* @param string $credentialPublicKey PEM format
|
||||
* @return bool
|
||||
*/
|
||||
private function _verifySignature($dataToVerify, $signature, $credentialPublicKey) {
|
||||
|
||||
// Use Sodium to verify EdDSA 25519 as its not yet supported by openssl
|
||||
if (\function_exists('sodium_crypto_sign_verify_detached') && !\in_array('ed25519', \openssl_get_curve_names(), true)) {
|
||||
$pkParts = [];
|
||||
if (\preg_match('/BEGIN PUBLIC KEY\-+(?:\s|\n|\r)+([^\-]+)(?:\s|\n|\r)*\-+END PUBLIC KEY/i', $credentialPublicKey, $pkParts)) {
|
||||
$rawPk = \base64_decode($pkParts[1]);
|
||||
|
||||
// 30 = der sequence
|
||||
// 2a = length 42 byte
|
||||
// 30 = der sequence
|
||||
// 05 = lenght 5 byte
|
||||
// 06 = der OID
|
||||
// 03 = OID length 3 byte
|
||||
// 2b 65 70 = OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
|
||||
// 03 = der bit string
|
||||
// 21 = length 33 byte
|
||||
// 00 = null padding
|
||||
// [...] = 32 byte x-curve
|
||||
$okpPrefix = "\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00";
|
||||
|
||||
if ($rawPk && \strlen($rawPk) === 44 && \substr($rawPk,0, \strlen($okpPrefix)) === $okpPrefix) {
|
||||
$publicKeyXCurve = \substr($rawPk, \strlen($okpPrefix));
|
||||
|
||||
return \sodium_crypto_sign_verify_detached($signature, $dataToVerify, $publicKeyXCurve);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// verify with openSSL
|
||||
$publicKey = \openssl_pkey_get_public($credentialPublicKey);
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('public key invalid', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
return \openssl_verify($dataToVerify, $signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
}
|
||||
28
app-code/api/account/WebAuthnException.php
Normal file
28
app-code/api/account/WebAuthnException.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
namespace lbuchs\WebAuthn;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class WebAuthnException extends \Exception {
|
||||
const INVALID_DATA = 1;
|
||||
const INVALID_TYPE = 2;
|
||||
const INVALID_CHALLENGE = 3;
|
||||
const INVALID_ORIGIN = 4;
|
||||
const INVALID_RELYING_PARTY = 5;
|
||||
const INVALID_SIGNATURE = 6;
|
||||
const INVALID_PUBLIC_KEY = 7;
|
||||
const CERTIFICATE_NOT_TRUSTED = 8;
|
||||
const USER_PRESENT = 9;
|
||||
const USER_VERIFICATED = 10;
|
||||
const SIGNATURE_COUNTER = 11;
|
||||
const CRYPTO_STRONG = 13;
|
||||
const BYTEBUFFER = 14;
|
||||
const CBOR = 15;
|
||||
const ANDROID_NOT_TRUSTED = 16;
|
||||
|
||||
public function __construct($message = "", $code = 0, $previous = null) {
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
||||
41
app-code/api/account/get_user_data.php
Normal file
41
app-code/api/account/get_user_data.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
// Simulate fetching user data from a database
|
||||
session_start();
|
||||
header('Content-Type: application/json');
|
||||
if($_SESSION["logged_in"]!==true){
|
||||
$data=[
|
||||
'status' => 'error',
|
||||
'message' => 'not logged in'
|
||||
];
|
||||
echo json_encode($user_data);
|
||||
exit();
|
||||
}
|
||||
|
||||
include "../../config/config.php";
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
|
||||
|
||||
$username=$_SESSION["username"];
|
||||
$sql="SELECT id, email, telegram_id, auth_method_enabled_2fa FROM users WHERE username = ?";
|
||||
$id=0;
|
||||
$email="";
|
||||
$telegram_id="";
|
||||
$twofa_enabled="";
|
||||
$stmt = mysqli_prepare($conn, $sql);
|
||||
mysqli_stmt_bind_param($stmt, 's', $username);
|
||||
mysqli_stmt_execute($stmt);
|
||||
mysqli_stmt_store_result($stmt);
|
||||
mysqli_stmt_bind_result($stmt, $id,$email,$telegram_id,$twofa_enabled);
|
||||
mysqli_stmt_fetch($stmt);
|
||||
|
||||
$_SESSION["id"]=$id;
|
||||
// Sample user data
|
||||
$user_data = [
|
||||
"name" => $username,
|
||||
"email" => $email,
|
||||
"telegram_id" => $telegram_id,
|
||||
"twofa_enabled" => $twofa_enabled
|
||||
];
|
||||
|
||||
// Send JSON response
|
||||
echo json_encode($user_data);
|
||||
?>
|
||||
71
app-code/api/account/update_2fa.php
Normal file
71
app-code/api/account/update_2fa.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
session_start();
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Check if the user is logged in
|
||||
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Not logged in'
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Include database configuration
|
||||
include "../../config/config.php";
|
||||
include "../utils/create_key.php";
|
||||
include "../utils/generate_pin.php";
|
||||
|
||||
// Create a new database connection
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
|
||||
|
||||
// Check for database connection errors
|
||||
if ($conn->connect_error) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Database connection failed: ' . $conn->connect_error
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Get the logged-in user's ID and username from the session
|
||||
$id = $_SESSION["id"];
|
||||
$username = $_SESSION["username"];
|
||||
|
||||
// Get the raw POST data (JSON)
|
||||
$data = json_decode(file_get_contents("php://input"));
|
||||
if($data->enable_2fa==true){
|
||||
//create 2fa secret key
|
||||
$twofa_secret=generateBase32Secret();
|
||||
$sql="UPDATE users SET 2fa = ?, auth_method_enabled_2fa = 1, auth_method_required_2fa = 1 WHERE id = ?";
|
||||
if ($update_stmt = $conn->prepare($sql)) {
|
||||
$update_stmt->bind_param("si", $twofa_secret, $id);
|
||||
if ($update_stmt->execute()) {
|
||||
echo json_encode(['success' => true, 'message' => '2FA enabled. Your 2fa secret is: '.$twofa_secret.'']);
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Failed to enable 2fa.']);
|
||||
}
|
||||
$update_stmt->close();
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Database error.']);
|
||||
}
|
||||
}
|
||||
|
||||
if($data->enable_2fa==false){
|
||||
//create 2fa secret key
|
||||
$sql="UPDATE users SET auth_method_enabled_2fa = 0, auth_method_required_2fa = 0 WHERE id = ?";
|
||||
if ($update_stmt = $conn->prepare($sql)) {
|
||||
$update_stmt->bind_param("i",$id);
|
||||
if ($update_stmt->execute()) {
|
||||
echo json_encode(['success' => true, 'message' => '2FA disabled.']);
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Failed to disable 2fa.']);
|
||||
}
|
||||
$update_stmt->close();
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Database error.']);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
|
||||
200
app-code/api/account/update_passkey.php
Normal file
200
app-code/api/account/update_passkey.php
Normal file
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
//with db:
|
||||
header('Content-Type: application/json');
|
||||
|
||||
|
||||
|
||||
require_once 'WebAuthn.php';
|
||||
|
||||
// Assuming you've already established a database connection here
|
||||
include "../../config/config.php";
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD,$DB_DATABASE);
|
||||
if ($conn->connect_error) {
|
||||
$success=0;
|
||||
die("Connection failed: " . $conn->connect_error);
|
||||
}
|
||||
|
||||
try {
|
||||
session_start();
|
||||
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Not logged in'
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
|
||||
// read get argument and post body
|
||||
$fn = filter_input(INPUT_GET, 'fn');
|
||||
$requireResidentKey = !!filter_input(INPUT_GET, 'requireResidentKey');
|
||||
$userVerification = filter_input(INPUT_GET, 'userVerification', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
|
||||
$userId = filter_input(INPUT_GET, 'userId', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
$userName = filter_input(INPUT_GET, 'userName', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
$userDisplayName = filter_input(INPUT_GET, 'userDisplayName', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
|
||||
$userId = preg_replace('/[^0-9a-f]/i', '', $userId);
|
||||
$userName = preg_replace('/[^0-9a-z]/i', '', $_SESSION["username"]);
|
||||
$userDisplayName = preg_replace('/[^0-9a-z öüäéèàÖÜÄÉÈÀÂÊÎÔÛâêîôû]/i', '', $userDisplayName);
|
||||
|
||||
$post = trim(file_get_contents('php://input'));
|
||||
if ($post) {
|
||||
$post = json_decode($post, null, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
if ($fn !== 'getStoredDataHtml') {
|
||||
|
||||
// Formats
|
||||
$formats = [];
|
||||
//if (filter_input(INPUT_GET, 'fmt_android-key')) {
|
||||
$formats[] = 'android-key';
|
||||
//}
|
||||
///if (filter_input(INPUT_GET, 'fmt_android-safetynet')) {
|
||||
$formats[] = 'android-safetynet';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_apple')) {
|
||||
$formats[] = 'apple';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_fido-u2f')) {
|
||||
$formats[] = 'fido-u2f';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_none')) {
|
||||
$formats[] = 'none';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_packed')) {
|
||||
$formats[] = 'packed';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_tpm')) {
|
||||
$formats[] = 'tpm';
|
||||
//}
|
||||
|
||||
$rpId=$_SERVER['SERVER_NAME'];
|
||||
|
||||
$typeUsb = true;
|
||||
$typeNfc = true;
|
||||
$typeBle = true;
|
||||
$typeInt = true;
|
||||
$typeHyb = true;
|
||||
|
||||
// cross-platform: true, if type internal is not allowed
|
||||
// false, if only internal is allowed
|
||||
// null, if internal and cross-platform is allowed
|
||||
$crossPlatformAttachment = null;
|
||||
if (($typeUsb || $typeNfc || $typeBle || $typeHyb) && !$typeInt) {
|
||||
$crossPlatformAttachment = true;
|
||||
|
||||
} else if (!$typeUsb && !$typeNfc && !$typeBle && !$typeHyb && $typeInt) {
|
||||
$crossPlatformAttachment = false;
|
||||
}
|
||||
|
||||
|
||||
// new Instance of the server library.
|
||||
// make sure that $rpId is the domain name.
|
||||
$WebAuthn = new lbuchs\WebAuthn\WebAuthn('WebAuthn Library', $rpId, $formats);
|
||||
|
||||
// add root certificates to validate new registrations
|
||||
//if (filter_input(INPUT_GET, 'solo')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/solo.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'apple')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/apple.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'yubico')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/yubico.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'hypersecu')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/hypersecu.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'google')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/globalSign.pem');
|
||||
$WebAuthn->addRootCertificates('rootCertificates/googleHardware.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'microsoft')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/microsoftTpmCollection.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'mds')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/mds');
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
// Handle different functions
|
||||
if ($fn === 'getCreateArgs') {
|
||||
$createArgs = $WebAuthn->getCreateArgs(\hex2bin($userId), $userName, $userDisplayName, 60*4, $requireResidentKey, $userVerification, $crossPlatformAttachment);
|
||||
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($createArgs));
|
||||
|
||||
// save challange to session. you have to deliver it to processGet later.
|
||||
$_SESSION['challenge'] = $WebAuthn->getChallenge();
|
||||
|
||||
} else if ($fn === 'getGetArgs') {
|
||||
$ids = [];
|
||||
|
||||
if ($requireResidentKey) {
|
||||
if (!isset($_SESSION['registrations']) || !is_array($_SESSION['registrations']) || count($_SESSION['registrations']) === 0) {
|
||||
throw new Exception('we do not have any registrations in session to check the registration');
|
||||
}
|
||||
|
||||
} else {
|
||||
// load registrations from session stored there by processCreate.
|
||||
// normaly you have to load the credential Id's for a username
|
||||
// from the database.
|
||||
if (isset($_SESSION['registrations']) && is_array($_SESSION['registrations'])) {
|
||||
foreach ($_SESSION['registrations'] as $reg) {
|
||||
if ($reg->userId === $userId) {
|
||||
$ids[] = $reg->credentialId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (count($ids) === 0) {
|
||||
throw new Exception('no registrations in session for userId ' . $userId);
|
||||
}
|
||||
}
|
||||
|
||||
$getArgs = $WebAuthn->getGetArgs($ids, 60*4, $typeUsb, $typeNfc, $typeBle, $typeHyb, $typeInt, $userVerification);
|
||||
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($getArgs));
|
||||
|
||||
// save challange to session. you have to deliver it to processGet later.
|
||||
$_SESSION['challenge'] = $WebAuthn->getChallenge();
|
||||
} else if ($fn === 'processCreate') {
|
||||
// Process create
|
||||
$challenge = $_SESSION['challenge'];
|
||||
$clientDataJSON = base64_decode($post->clientDataJSON);
|
||||
$attestationObject = base64_decode($post->attestationObject);
|
||||
|
||||
// Process create and store data in the database
|
||||
$data = $WebAuthn->processCreate($clientDataJSON, $attestationObject, $challenge, $userVerification === 'required', true, false);
|
||||
|
||||
// add user infos
|
||||
$data->userId = $userId;
|
||||
$data->userName = $userName;
|
||||
$data->userDisplayName = $userDisplayName;
|
||||
|
||||
// Store registration data in the database
|
||||
$stmt = $conn->prepare("UPDATE users set credential_id = ?, public_key = ?, counter = ?, auth_method_enabled_passkey = 1, auth_method_required_passkey = 1 WHERE username = ?");
|
||||
//$stmt = $conn->prepare("INSERT INTO users (user_hex_id, credential_id, public_key, counter) VALUES (?, ?, ?, ?)");
|
||||
//var_dump($data);
|
||||
$stmt->execute([ $data->credentialId, $data->credentialPublicKey, $data->signatureCounter,$userName]);
|
||||
|
||||
$msg = 'registration success.';
|
||||
$return = new stdClass();
|
||||
$return->success = true;
|
||||
$return->msg = $msg;
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($return));
|
||||
}
|
||||
|
||||
} catch (Throwable $ex) {
|
||||
$return = new stdClass();
|
||||
$return->success = false;
|
||||
$return->msg = $ex->getMessage();
|
||||
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($return));
|
||||
}
|
||||
?>
|
||||
98
app-code/api/account/update_pw.php
Normal file
98
app-code/api/account/update_pw.php
Normal file
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
session_start();
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Check if the user is logged in
|
||||
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Not logged in'
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Include database configuration
|
||||
include "../../config/config.php";
|
||||
|
||||
// Create a new database connection
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
|
||||
|
||||
// Check for database connection errors
|
||||
if ($conn->connect_error) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Database connection failed: ' . $conn->connect_error
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Get the logged-in user's ID and username from the session
|
||||
$id = $_SESSION["id"];
|
||||
$username = $_SESSION["username"];
|
||||
|
||||
// Get the raw POST data (JSON)
|
||||
$data = json_decode(file_get_contents("php://input"));
|
||||
|
||||
// Check if the required fields are present
|
||||
if (isset($data->old_password) && isset($data->new_password)) {
|
||||
// Get the user ID (this should be taken from the session or JWT token)
|
||||
session_start();
|
||||
$user_id = $_SESSION['id']; // Assuming user_id is stored in session
|
||||
|
||||
// Sanitize inputs
|
||||
$old_password = htmlspecialchars($data->old_password);
|
||||
$new_password = htmlspecialchars($data->new_password);
|
||||
|
||||
// Check password strength (optional but recommended)
|
||||
if (strlen($new_password) < 12) {
|
||||
echo json_encode(['success' => false, 'message' => 'Password must be at least 12 characters long.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Fetch the current password from the database
|
||||
$sql = "SELECT password, pepper FROM users WHERE id = ?";
|
||||
if ($stmt = $conn->prepare($sql)) {
|
||||
$stmt->bind_param("i", $user_id);
|
||||
$stmt->execute();
|
||||
$stmt->store_result();
|
||||
$stmt->bind_result($current_password, $current_pepper);
|
||||
|
||||
if ($stmt->fetch()) {
|
||||
// Verify the old password
|
||||
if (password_verify($old_password.$current_pepper, $current_password)) {
|
||||
// Hash the new password
|
||||
$new_pepper=bin2hex(random_bytes(32));
|
||||
// Hash the password / a salt is added automaticly
|
||||
$hashed_password = password_hash($new_password.$new_pepper, PASSWORD_BCRYPT);
|
||||
|
||||
// Update the password in the database
|
||||
$update_sql = "UPDATE users SET password = ?, pepper = ? WHERE id = ?";
|
||||
if ($update_stmt = $conn->prepare($update_sql)) {
|
||||
$update_stmt->bind_param("ssi", $hashed_password, $new_pepper, $user_id);
|
||||
if ($update_stmt->execute()) {
|
||||
echo json_encode(['success' => true, 'message' => 'Password updated successfully.']);
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Failed to update password.']);
|
||||
}
|
||||
$update_stmt->close();
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Database error.']);
|
||||
}
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Old password is incorrect.']);
|
||||
}
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'User not found.']);
|
||||
}
|
||||
$stmt->close();
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Database error.']);
|
||||
}
|
||||
|
||||
// Close the database connection
|
||||
$conn->close();
|
||||
} else {
|
||||
echo json_encode(['success' => false, 'message' => 'Missing required fields.']);
|
||||
}
|
||||
?>
|
||||
|
||||
116
app-code/api/account/update_user_data.php
Normal file
116
app-code/api/account/update_user_data.php
Normal file
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
session_start();
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Check if the user is logged in
|
||||
if (!isset($_SESSION["logged_in"]) || $_SESSION["logged_in"] !== true) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Not logged in'
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Include database configuration
|
||||
include "../../config/config.php";
|
||||
|
||||
// Create a new database connection
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
|
||||
|
||||
// Check for database connection errors
|
||||
if ($conn->connect_error) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Database connection failed: ' . $conn->connect_error
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Get the logged-in user's ID and username from the session
|
||||
$id = $_SESSION["id"];
|
||||
$username = $_SESSION["username"];
|
||||
|
||||
// Check if the request method is POST
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
// Get the raw JSON input
|
||||
$input = file_get_contents('php://input');
|
||||
$data = json_decode($input, true);
|
||||
|
||||
// Validate the input
|
||||
if (!isset($data['name']) || !isset($data['email']) || !isset($data['telegram_id'])) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Invalid input: Missing fields'
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Sanitize and validate the input
|
||||
$name = preg_replace("/[^a-zA-Z0-9_]/", "", $data['name']); // Allow only letters, numbers, and underscores
|
||||
$email = filter_var($data['email'], FILTER_SANITIZE_EMAIL); // Sanitize email
|
||||
$telegram_id = htmlspecialchars($data['telegram_id'], ENT_QUOTES, 'UTF-8'); // Escape special characters
|
||||
|
||||
//check if username is allready taken
|
||||
$id_check=0;
|
||||
$sql="SELECT id FROM users WHERE username = ?";
|
||||
$stmt = mysqli_prepare($conn, $sql);
|
||||
mysqli_stmt_bind_param($stmt, 's', $name);
|
||||
mysqli_stmt_execute($stmt);
|
||||
mysqli_stmt_store_result($stmt);
|
||||
mysqli_stmt_bind_result($stmt, $id_check);
|
||||
mysqli_stmt_fetch($stmt);
|
||||
if(mysqli_stmt_num_rows($stmt) > 0 && $username!==$name){
|
||||
//this username is allready taken
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Username allready taken. Please choose another username.'
|
||||
]);
|
||||
exit();
|
||||
|
||||
}
|
||||
mysqli_stmt_close($stmt);
|
||||
// Prepare the SQL query
|
||||
$sql = "UPDATE users SET email = ?, username = ?, telegram_id = ? WHERE id = ?";
|
||||
$stmt = $conn->prepare($sql);
|
||||
|
||||
// Check if the statement was prepared successfully
|
||||
if (!$stmt) {
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Failed to prepare statement: ' . $conn->error
|
||||
]);
|
||||
exit();
|
||||
}
|
||||
|
||||
// Bind parameters to the prepared statement
|
||||
$stmt->bind_param('sssi', $email, $name, $telegram_id, $id);
|
||||
|
||||
// Execute the statement
|
||||
if ($stmt->execute()) {
|
||||
// Respond with success
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'message' => 'User data updated successfully'
|
||||
]);
|
||||
$_SESSION["username"]=$name;
|
||||
} else {
|
||||
// Respond with failure
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Failed to update user data: ' . $stmt->error
|
||||
]);
|
||||
}
|
||||
|
||||
// Close the statement
|
||||
$stmt->close();
|
||||
} else {
|
||||
// Respond with error for invalid request method
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'message' => 'Invalid request method'
|
||||
]);
|
||||
}
|
||||
|
||||
// Close the database connection
|
||||
$conn->close();
|
||||
?>
|
||||
179
app-code/api/login/Attestation/AttestationObject.php
Normal file
179
app-code/api/login/Attestation/AttestationObject.php
Normal file
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\CBOR\CborDecoder;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class AttestationObject {
|
||||
private $_authenticatorData;
|
||||
private $_attestationFormat;
|
||||
private $_attestationFormatName;
|
||||
|
||||
public function __construct($binary , $allowedFormats) {
|
||||
$enc = CborDecoder::decode($binary);
|
||||
// validation
|
||||
if (!\is_array($enc) || !\array_key_exists('fmt', $enc) || !is_string($enc['fmt'])) {
|
||||
throw new WebAuthnException('invalid attestation format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('attStmt', $enc) || !\is_array($enc['attStmt'])) {
|
||||
throw new WebAuthnException('invalid attestation format (attStmt not available)', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('authData', $enc) || !\is_object($enc['authData']) || !($enc['authData'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid attestation format (authData not available)', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_authenticatorData = new AuthenticatorData($enc['authData']->getBinaryString());
|
||||
$this->_attestationFormatName = $enc['fmt'];
|
||||
|
||||
// Format ok?
|
||||
if (!in_array($this->_attestationFormatName, $allowedFormats)) {
|
||||
throw new WebAuthnException('invalid atttestation format: ' . $this->_attestationFormatName, WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
|
||||
switch ($this->_attestationFormatName) {
|
||||
case 'android-key': $this->_attestationFormat = new Format\AndroidKey($enc, $this->_authenticatorData); break;
|
||||
case 'android-safetynet': $this->_attestationFormat = new Format\AndroidSafetyNet($enc, $this->_authenticatorData); break;
|
||||
case 'apple': $this->_attestationFormat = new Format\Apple($enc, $this->_authenticatorData); break;
|
||||
case 'fido-u2f': $this->_attestationFormat = new Format\U2f($enc, $this->_authenticatorData); break;
|
||||
case 'none': $this->_attestationFormat = new Format\None($enc, $this->_authenticatorData); break;
|
||||
case 'packed': $this->_attestationFormat = new Format\Packed($enc, $this->_authenticatorData); break;
|
||||
case 'tpm': $this->_attestationFormat = new Format\Tpm($enc, $this->_authenticatorData); break;
|
||||
default: throw new WebAuthnException('invalid attestation format: ' . $enc['fmt'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation format name
|
||||
* @return string
|
||||
*/
|
||||
public function getAttestationFormatName() {
|
||||
return $this->_attestationFormatName;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation format class
|
||||
* @return Format\FormatBase
|
||||
*/
|
||||
public function getAttestationFormat() {
|
||||
return $this->_attestationFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the attestation public key in PEM format
|
||||
* @return AuthenticatorData
|
||||
*/
|
||||
public function getAuthenticatorData() {
|
||||
return $this->_authenticatorData;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the certificate chain as PEM
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificateChain() {
|
||||
return $this->_attestationFormat->getCertificateChain();
|
||||
}
|
||||
|
||||
/**
|
||||
* return the certificate issuer as string
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificateIssuer() {
|
||||
$pem = $this->getCertificatePem();
|
||||
$issuer = '';
|
||||
if ($pem) {
|
||||
$certInfo = \openssl_x509_parse($pem);
|
||||
if (\is_array($certInfo) && \array_key_exists('issuer', $certInfo) && \is_array($certInfo['issuer'])) {
|
||||
|
||||
$cn = $certInfo['issuer']['CN'] ?? '';
|
||||
$o = $certInfo['issuer']['O'] ?? '';
|
||||
$ou = $certInfo['issuer']['OU'] ?? '';
|
||||
|
||||
if ($cn) {
|
||||
$issuer .= $cn;
|
||||
}
|
||||
if ($issuer && ($o || $ou)) {
|
||||
$issuer .= ' (' . trim($o . ' ' . $ou) . ')';
|
||||
} else {
|
||||
$issuer .= trim($o . ' ' . $ou);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* return the certificate subject as string
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificateSubject() {
|
||||
$pem = $this->getCertificatePem();
|
||||
$subject = '';
|
||||
if ($pem) {
|
||||
$certInfo = \openssl_x509_parse($pem);
|
||||
if (\is_array($certInfo) && \array_key_exists('subject', $certInfo) && \is_array($certInfo['subject'])) {
|
||||
|
||||
$cn = $certInfo['subject']['CN'] ?? '';
|
||||
$o = $certInfo['subject']['O'] ?? '';
|
||||
$ou = $certInfo['subject']['OU'] ?? '';
|
||||
|
||||
if ($cn) {
|
||||
$subject .= $cn;
|
||||
}
|
||||
if ($subject && ($o || $ou)) {
|
||||
$subject .= ' (' . trim($o . ' ' . $ou) . ')';
|
||||
} else {
|
||||
$subject .= trim($o . ' ' . $ou);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $subject;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_attestationFormat->getCertificatePem();
|
||||
}
|
||||
|
||||
/**
|
||||
* checks validity of the signature
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_attestationFormat->validateAttestation($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
return $this->_attestationFormat->validateRootCertificate($rootCas);
|
||||
}
|
||||
|
||||
/**
|
||||
* checks if the RpId-Hash is valid
|
||||
* @param string$rpIdHash
|
||||
* @return bool
|
||||
*/
|
||||
public function validateRpIdHash($rpIdHash) {
|
||||
return $rpIdHash === $this->_authenticatorData->getRpIdHash();
|
||||
}
|
||||
}
|
||||
481
app-code/api/login/Attestation/AuthenticatorData.php
Normal file
481
app-code/api/login/Attestation/AuthenticatorData.php
Normal file
@@ -0,0 +1,481 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\CBOR\CborDecoder;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class AuthenticatorData {
|
||||
protected $_binary;
|
||||
protected $_rpIdHash;
|
||||
protected $_flags;
|
||||
protected $_signCount;
|
||||
protected $_attestedCredentialData;
|
||||
protected $_extensionData;
|
||||
|
||||
|
||||
|
||||
// Cose encoded keys
|
||||
private static $_COSE_KTY = 1;
|
||||
private static $_COSE_ALG = 3;
|
||||
|
||||
// Cose curve
|
||||
private static $_COSE_CRV = -1;
|
||||
private static $_COSE_X = -2;
|
||||
private static $_COSE_Y = -3;
|
||||
|
||||
// Cose RSA PS256
|
||||
private static $_COSE_N = -1;
|
||||
private static $_COSE_E = -2;
|
||||
|
||||
// EC2 key type
|
||||
private static $_EC2_TYPE = 2;
|
||||
private static $_EC2_ES256 = -7;
|
||||
private static $_EC2_P256 = 1;
|
||||
|
||||
// RSA key type
|
||||
private static $_RSA_TYPE = 3;
|
||||
private static $_RSA_RS256 = -257;
|
||||
|
||||
// OKP key type
|
||||
private static $_OKP_TYPE = 1;
|
||||
private static $_OKP_ED25519 = 6;
|
||||
private static $_OKP_EDDSA = -8;
|
||||
|
||||
/**
|
||||
* Parsing the authenticatorData binary.
|
||||
* @param string $binary
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function __construct($binary) {
|
||||
if (!\is_string($binary) || \strlen($binary) < 37) {
|
||||
throw new WebAuthnException('Invalid authenticatorData input', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
$this->_binary = $binary;
|
||||
|
||||
// Read infos from binary
|
||||
// https://www.w3.org/TR/webauthn/#sec-authenticator-data
|
||||
|
||||
// RP ID
|
||||
$this->_rpIdHash = \substr($binary, 0, 32);
|
||||
|
||||
// flags (1 byte)
|
||||
$flags = \unpack('Cflags', \substr($binary, 32, 1))['flags'];
|
||||
$this->_flags = $this->_readFlags($flags);
|
||||
|
||||
// signature counter: 32-bit unsigned big-endian integer.
|
||||
$this->_signCount = \unpack('Nsigncount', \substr($binary, 33, 4))['signcount'];
|
||||
|
||||
$offset = 37;
|
||||
// https://www.w3.org/TR/webauthn/#sec-attested-credential-data
|
||||
if ($this->_flags->attestedDataIncluded) {
|
||||
$this->_attestedCredentialData = $this->_readAttestData($binary, $offset);
|
||||
}
|
||||
|
||||
if ($this->_flags->extensionDataIncluded) {
|
||||
$this->_readExtensionData(\substr($binary, $offset));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticator Attestation Globally Unique Identifier, a unique number
|
||||
* that identifies the model of the authenticator (not the specific instance
|
||||
* of the authenticator)
|
||||
* The aaguid may be 0 if the user is using a old u2f device and/or if
|
||||
* the browser is using the fido-u2f format.
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function getAAGUID() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
return $this->_attestedCredentialData->aaguid;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the authenticatorData as binary
|
||||
* @return string
|
||||
*/
|
||||
public function getBinary() {
|
||||
return $this->_binary;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the credentialId
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function getCredentialId() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass)) {
|
||||
throw new WebAuthnException('credential id not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
return $this->_attestedCredentialData->credentialId;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the public key in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getPublicKeyPem() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$der = null;
|
||||
switch ($this->_attestedCredentialData->credentialPublicKey->kty ?? null) {
|
||||
case self::$_EC2_TYPE: $der = $this->_getEc2Der(); break;
|
||||
case self::$_RSA_TYPE: $der = $this->_getRsaDer(); break;
|
||||
case self::$_OKP_TYPE: $der = $this->_getOkpDer(); break;
|
||||
default: throw new WebAuthnException('invalid key type', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$pem = '-----BEGIN PUBLIC KEY-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($der), 64, "\n");
|
||||
$pem .= '-----END PUBLIC KEY-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the public key in U2F format
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function getPublicKeyU2F() {
|
||||
if (!($this->_attestedCredentialData instanceof \stdClass) || !isset($this->_attestedCredentialData->credentialPublicKey)) {
|
||||
throw new WebAuthnException('credential data not included in authenticator data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
if (($this->_attestedCredentialData->credentialPublicKey->kty ?? null) !== self::$_EC2_TYPE) {
|
||||
throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
return "\x04" . // ECC uncompressed
|
||||
$this->_attestedCredentialData->credentialPublicKey->x .
|
||||
$this->_attestedCredentialData->credentialPublicKey->y;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the SHA256 hash of the relying party id (=hostname)
|
||||
* @return string
|
||||
*/
|
||||
public function getRpIdHash() {
|
||||
return $this->_rpIdHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the sign counter
|
||||
* @return int
|
||||
*/
|
||||
public function getSignCount() {
|
||||
return $this->_signCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if the user is present
|
||||
* @return boolean
|
||||
*/
|
||||
public function getUserPresent() {
|
||||
return $this->_flags->userPresent;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns true if the user is verified
|
||||
* @return boolean
|
||||
*/
|
||||
public function getUserVerified() {
|
||||
return $this->_flags->userVerified;
|
||||
}
|
||||
|
||||
// -----------------------------------------------
|
||||
// PRIVATE
|
||||
// -----------------------------------------------
|
||||
|
||||
/**
|
||||
* Returns DER encoded EC2 key
|
||||
* @return string
|
||||
*/
|
||||
private function _getEc2Der() {
|
||||
return $this->_der_sequence(
|
||||
$this->_der_sequence(
|
||||
$this->_der_oid("\x2A\x86\x48\xCE\x3D\x02\x01") . // OID 1.2.840.10045.2.1 ecPublicKey
|
||||
$this->_der_oid("\x2A\x86\x48\xCE\x3D\x03\x01\x07") // 1.2.840.10045.3.1.7 prime256v1
|
||||
) .
|
||||
$this->_der_bitString($this->getPublicKeyU2F())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns DER encoded EdDSA key
|
||||
* @return string
|
||||
*/
|
||||
private function _getOkpDer() {
|
||||
return $this->_der_sequence(
|
||||
$this->_der_sequence(
|
||||
$this->_der_oid("\x2B\x65\x70") // OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
|
||||
) .
|
||||
$this->_der_bitString($this->_attestedCredentialData->credentialPublicKey->x)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns DER encoded RSA key
|
||||
* @return string
|
||||
*/
|
||||
private function _getRsaDer() {
|
||||
return $this->_der_sequence(
|
||||
$this->_der_sequence(
|
||||
$this->_der_oid("\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01") . // OID 1.2.840.113549.1.1.1 rsaEncryption
|
||||
$this->_der_nullValue()
|
||||
) .
|
||||
$this->_der_bitString(
|
||||
$this->_der_sequence(
|
||||
$this->_der_unsignedInteger($this->_attestedCredentialData->credentialPublicKey->n) .
|
||||
$this->_der_unsignedInteger($this->_attestedCredentialData->credentialPublicKey->e)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* reads the flags from flag byte
|
||||
* @param string $binFlag
|
||||
* @return \stdClass
|
||||
*/
|
||||
private function _readFlags($binFlag) {
|
||||
$flags = new \stdClass();
|
||||
|
||||
$flags->bit_0 = !!($binFlag & 1);
|
||||
$flags->bit_1 = !!($binFlag & 2);
|
||||
$flags->bit_2 = !!($binFlag & 4);
|
||||
$flags->bit_3 = !!($binFlag & 8);
|
||||
$flags->bit_4 = !!($binFlag & 16);
|
||||
$flags->bit_5 = !!($binFlag & 32);
|
||||
$flags->bit_6 = !!($binFlag & 64);
|
||||
$flags->bit_7 = !!($binFlag & 128);
|
||||
|
||||
// named flags
|
||||
$flags->userPresent = $flags->bit_0;
|
||||
$flags->userVerified = $flags->bit_2;
|
||||
$flags->attestedDataIncluded = $flags->bit_6;
|
||||
$flags->extensionDataIncluded = $flags->bit_7;
|
||||
return $flags;
|
||||
}
|
||||
|
||||
/**
|
||||
* read attested data
|
||||
* @param string $binary
|
||||
* @param int $endOffset
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readAttestData($binary, &$endOffset) {
|
||||
$attestedCData = new \stdClass();
|
||||
if (\strlen($binary) <= 55) {
|
||||
throw new WebAuthnException('Attested data should be present but is missing', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// The AAGUID of the authenticator
|
||||
$attestedCData->aaguid = \substr($binary, 37, 16);
|
||||
|
||||
//Byte length L of Credential ID, 16-bit unsigned big-endian integer.
|
||||
$length = \unpack('nlength', \substr($binary, 53, 2))['length'];
|
||||
$attestedCData->credentialId = \substr($binary, 55, $length);
|
||||
|
||||
// set end offset
|
||||
$endOffset = 55 + $length;
|
||||
|
||||
// extract public key
|
||||
$attestedCData->credentialPublicKey = $this->_readCredentialPublicKey($binary, 55 + $length, $endOffset);
|
||||
|
||||
return $attestedCData;
|
||||
}
|
||||
|
||||
/**
|
||||
* reads COSE key-encoded elliptic curve public key in EC2 format
|
||||
* @param string $binary
|
||||
* @param int $endOffset
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKey($binary, $offset, &$endOffset) {
|
||||
$enc = CborDecoder::decodeInPlace($binary, $offset, $endOffset);
|
||||
|
||||
// COSE key-encoded elliptic curve public key in EC2 format
|
||||
$credPKey = new \stdClass();
|
||||
$credPKey->kty = $enc[self::$_COSE_KTY];
|
||||
$credPKey->alg = $enc[self::$_COSE_ALG];
|
||||
|
||||
switch ($credPKey->alg) {
|
||||
case self::$_EC2_ES256: $this->_readCredentialPublicKeyES256($credPKey, $enc); break;
|
||||
case self::$_RSA_RS256: $this->_readCredentialPublicKeyRS256($credPKey, $enc); break;
|
||||
case self::$_OKP_EDDSA: $this->_readCredentialPublicKeyEDDSA($credPKey, $enc); break;
|
||||
}
|
||||
|
||||
return $credPKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* extract EDDSA informations from cose
|
||||
* @param \stdClass $credPKey
|
||||
* @param \stdClass $enc
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKeyEDDSA(&$credPKey, $enc) {
|
||||
$credPKey->crv = $enc[self::$_COSE_CRV];
|
||||
$credPKey->x = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
// Validation
|
||||
if ($credPKey->kty !== self::$_OKP_TYPE) {
|
||||
throw new WebAuthnException('public key not in OKP format', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->alg !== self::$_OKP_EDDSA) {
|
||||
throw new WebAuthnException('signature algorithm not EdDSA', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->crv !== self::$_OKP_ED25519) {
|
||||
throw new WebAuthnException('curve not Ed25519', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->x) !== 32) {
|
||||
throw new WebAuthnException('Invalid X-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* extract ES256 informations from cose
|
||||
* @param \stdClass $credPKey
|
||||
* @param \stdClass $enc
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKeyES256(&$credPKey, $enc) {
|
||||
$credPKey->crv = $enc[self::$_COSE_CRV];
|
||||
$credPKey->x = $enc[self::$_COSE_X] instanceof ByteBuffer ? $enc[self::$_COSE_X]->getBinaryString() : null;
|
||||
$credPKey->y = $enc[self::$_COSE_Y] instanceof ByteBuffer ? $enc[self::$_COSE_Y]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
// Validation
|
||||
if ($credPKey->kty !== self::$_EC2_TYPE) {
|
||||
throw new WebAuthnException('public key not in EC2 format', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->alg !== self::$_EC2_ES256) {
|
||||
throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->crv !== self::$_EC2_P256) {
|
||||
throw new WebAuthnException('curve not P-256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->x) !== 32) {
|
||||
throw new WebAuthnException('Invalid X-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->y) !== 32) {
|
||||
throw new WebAuthnException('Invalid Y-coordinate', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* extract RS256 informations from COSE
|
||||
* @param \stdClass $credPKey
|
||||
* @param \stdClass $enc
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readCredentialPublicKeyRS256(&$credPKey, $enc) {
|
||||
$credPKey->n = $enc[self::$_COSE_N] instanceof ByteBuffer ? $enc[self::$_COSE_N]->getBinaryString() : null;
|
||||
$credPKey->e = $enc[self::$_COSE_E] instanceof ByteBuffer ? $enc[self::$_COSE_E]->getBinaryString() : null;
|
||||
unset ($enc);
|
||||
|
||||
// Validation
|
||||
if ($credPKey->kty !== self::$_RSA_TYPE) {
|
||||
throw new WebAuthnException('public key not in RSA format', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if ($credPKey->alg !== self::$_RSA_RS256) {
|
||||
throw new WebAuthnException('signature algorithm not ES256', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->n) !== 256) {
|
||||
throw new WebAuthnException('Invalid RSA modulus', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
if (\strlen($credPKey->e) !== 3) {
|
||||
throw new WebAuthnException('Invalid RSA public exponent', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* reads cbor encoded extension data.
|
||||
* @param string $binary
|
||||
* @return array
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _readExtensionData($binary) {
|
||||
$ext = CborDecoder::decode($binary);
|
||||
if (!\is_array($ext)) {
|
||||
throw new WebAuthnException('invalid extension data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
return $ext;
|
||||
}
|
||||
|
||||
|
||||
// ---------------
|
||||
// DER functions
|
||||
// ---------------
|
||||
|
||||
private function _der_length($len) {
|
||||
if ($len < 128) {
|
||||
return \chr($len);
|
||||
}
|
||||
$lenBytes = '';
|
||||
while ($len > 0) {
|
||||
$lenBytes = \chr($len % 256) . $lenBytes;
|
||||
$len = \intdiv($len, 256);
|
||||
}
|
||||
return \chr(0x80 | \strlen($lenBytes)) . $lenBytes;
|
||||
}
|
||||
|
||||
private function _der_sequence($contents) {
|
||||
return "\x30" . $this->_der_length(\strlen($contents)) . $contents;
|
||||
}
|
||||
|
||||
private function _der_oid($encoded) {
|
||||
return "\x06" . $this->_der_length(\strlen($encoded)) . $encoded;
|
||||
}
|
||||
|
||||
private function _der_bitString($bytes) {
|
||||
return "\x03" . $this->_der_length(\strlen($bytes) + 1) . "\x00" . $bytes;
|
||||
}
|
||||
|
||||
private function _der_nullValue() {
|
||||
return "\x05\x00";
|
||||
}
|
||||
|
||||
private function _der_unsignedInteger($bytes) {
|
||||
$len = \strlen($bytes);
|
||||
|
||||
// Remove leading zero bytes
|
||||
for ($i = 0; $i < ($len - 1); $i++) {
|
||||
if (\ord($bytes[$i]) !== 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($i !== 0) {
|
||||
$bytes = \substr($bytes, $i);
|
||||
}
|
||||
|
||||
// If most significant bit is set, prefix with another zero to prevent it being seen as negative number
|
||||
if ((\ord($bytes[0]) & 0x80) !== 0) {
|
||||
$bytes = "\x00" . $bytes;
|
||||
}
|
||||
|
||||
return "\x02" . $this->_der_length(\strlen($bytes)) . $bytes;
|
||||
}
|
||||
}
|
||||
96
app-code/api/login/Attestation/Format/AndroidKey.php
Normal file
96
app-code/api/login/Attestation/Format/AndroidKey.php
Normal file
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class AndroidKey extends FormatBase {
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check u2f data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('x5c', $attStmt) || !\is_array($attStmt['x5c']) || \count($attStmt['x5c']) < 1) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\is_object($attStmt['x5c'][0]) || !($attStmt['x5c'][0] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_x5c = $attStmt['x5c'][0]->getBinaryString();
|
||||
|
||||
if (count($attStmt['x5c']) > 1) {
|
||||
for ($i=1; $i<count($attStmt['x5c']); $i++) {
|
||||
$this->_x5c_chain[] = $attStmt['x5c'][$i]->getBinaryString();
|
||||
}
|
||||
unset ($i);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the attestation public key in attestnCert with the algorithm specified in alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
|
||||
152
app-code/api/login/Attestation/Format/AndroidSafetyNet.php
Normal file
152
app-code/api/login/Attestation/Format/AndroidSafetyNet.php
Normal file
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class AndroidSafetyNet extends FormatBase {
|
||||
private $_signature;
|
||||
private $_signedValue;
|
||||
private $_x5c;
|
||||
private $_payload;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('ver', $attStmt) || !$attStmt['ver']) {
|
||||
throw new WebAuthnException('invalid Android Safety Net Format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('response', $attStmt) || !($attStmt['response'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid Android Safety Net Format', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$response = $attStmt['response']->getBinaryString();
|
||||
|
||||
// Response is a JWS [RFC7515] object in Compact Serialization.
|
||||
// JWSs have three segments separated by two period ('.') characters
|
||||
$parts = \explode('.', $response);
|
||||
unset ($response);
|
||||
if (\count($parts) !== 3) {
|
||||
throw new WebAuthnException('invalid JWS data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$header = $this->_base64url_decode($parts[0]);
|
||||
$payload = $this->_base64url_decode($parts[1]);
|
||||
$this->_signature = $this->_base64url_decode($parts[2]);
|
||||
$this->_signedValue = $parts[0] . '.' . $parts[1];
|
||||
unset ($parts);
|
||||
|
||||
$header = \json_decode($header);
|
||||
$payload = \json_decode($payload);
|
||||
|
||||
if (!($header instanceof \stdClass)) {
|
||||
throw new WebAuthnException('invalid JWS header', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
if (!($payload instanceof \stdClass)) {
|
||||
throw new WebAuthnException('invalid JWS payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!isset($header->x5c) || !is_array($header->x5c) || count($header->x5c) === 0) {
|
||||
throw new WebAuthnException('No X.509 signature in JWS Header', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// algorithm
|
||||
if (!\in_array($header->alg, array('RS256', 'ES256'))) {
|
||||
throw new WebAuthnException('invalid JWS algorithm ' . $header->alg, WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = \base64_decode($header->x5c[0]);
|
||||
$this->_payload = $payload;
|
||||
|
||||
if (count($header->x5c) > 1) {
|
||||
for ($i=1; $i<count($header->x5c); $i++) {
|
||||
$this->_x5c_chain[] = \base64_decode($header->x5c[$i]);
|
||||
}
|
||||
unset ($i);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ctsProfileMatch: A stricter verdict of device integrity.
|
||||
* If the value of ctsProfileMatch is true, then the profile of the device running your app matches
|
||||
* the profile of a device that has passed Android compatibility testing and
|
||||
* has been approved as a Google-certified Android device.
|
||||
* @return bool
|
||||
*/
|
||||
public function ctsProfileMatch() {
|
||||
return isset($this->_payload->ctsProfileMatch) ? !!$this->_payload->ctsProfileMatch : false;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
// Verify that the nonce in the response is identical to the Base64 encoding
|
||||
// of the SHA-256 hash of the concatenation of authenticatorData and clientDataHash.
|
||||
if (empty($this->_payload->nonce) || $this->_payload->nonce !== \base64_encode(\hash('SHA256', $this->_authenticatorData->getBinary() . $clientDataHash, true))) {
|
||||
throw new WebAuthnException('invalid nonce in JWS payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that attestationCert is issued to the hostname "attest.android.com"
|
||||
$certInfo = \openssl_x509_parse($this->getCertificatePem());
|
||||
if (!\is_array($certInfo) || ($certInfo['subject']['CN'] ?? '') !== 'attest.android.com') {
|
||||
throw new WebAuthnException('invalid certificate CN in JWS (' . ($certInfo['subject']['CN'] ?? '-'). ')', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that the basicIntegrity attribute in the payload of response is true.
|
||||
if (empty($this->_payload->basicIntegrity)) {
|
||||
throw new WebAuthnException('invalid basicIntegrity in payload', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($this->_signedValue, $this->_signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* decode base64 url
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
private function _base64url_decode($data) {
|
||||
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
|
||||
}
|
||||
}
|
||||
|
||||
139
app-code/api/login/Attestation/Format/Apple.php
Normal file
139
app-code/api/login/Attestation/Format/Apple.php
Normal file
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Apple extends FormatBase {
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new WebAuthnException('invalid Apple attestation statement: missing x5c', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Concatenate authenticatorData and clientDataHash to form nonceToHash.
|
||||
$nonceToHash = $this->_authenticatorData->getBinary();
|
||||
$nonceToHash .= $clientDataHash;
|
||||
|
||||
// Perform SHA-256 hash of nonceToHash to produce nonce
|
||||
$nonce = hash('SHA256', $nonceToHash, true);
|
||||
|
||||
$credCert = openssl_x509_read($this->getCertificatePem());
|
||||
if ($credCert === false) {
|
||||
throw new WebAuthnException('invalid x5c certificate: ' . \openssl_error_string(), WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$keyData = openssl_pkey_get_details(openssl_pkey_get_public($credCert));
|
||||
$key = is_array($keyData) && array_key_exists('key', $keyData) ? $keyData['key'] : null;
|
||||
|
||||
|
||||
// Verify that nonce equals the value of the extension with OID ( 1.2.840.113635.100.8.2 ) in credCert.
|
||||
$parsedCredCert = openssl_x509_parse($credCert);
|
||||
$nonceExtension = $parsedCredCert['extensions']['1.2.840.113635.100.8.2'] ?? '';
|
||||
|
||||
// nonce padded by ASN.1 string: 30 24 A1 22 04 20
|
||||
// 30 — type tag indicating sequence
|
||||
// 24 — 36 byte following
|
||||
// A1 — Enumerated [1]
|
||||
// 22 — 34 byte following
|
||||
// 04 — type tag indicating octet string
|
||||
// 20 — 32 byte following
|
||||
|
||||
$asn1Padding = "\x30\x24\xA1\x22\x04\x20";
|
||||
if (substr($nonceExtension, 0, strlen($asn1Padding)) === $asn1Padding) {
|
||||
$nonceExtension = substr($nonceExtension, strlen($asn1Padding));
|
||||
}
|
||||
|
||||
if ($nonceExtension !== $nonce) {
|
||||
throw new WebAuthnException('nonce doesn\'t equal the value of the extension with OID 1.2.840.113635.100.8.2', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that the credential public key equals the Subject Public Key of credCert.
|
||||
$authKeyData = openssl_pkey_get_details(openssl_pkey_get_public($this->_authenticatorData->getPublicKeyPem()));
|
||||
$authKey = is_array($authKeyData) && array_key_exists('key', $authKeyData) ? $authKeyData['key'] : null;
|
||||
|
||||
if ($key === null || $key !== $authKey) {
|
||||
throw new WebAuthnException('credential public key doesn\'t equal the Subject Public Key of credCert', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
193
app-code/api/login/Attestation/Format/FormatBase.php
Normal file
193
app-code/api/login/Attestation/Format/FormatBase.php
Normal file
@@ -0,0 +1,193 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
|
||||
|
||||
abstract class FormatBase {
|
||||
protected $_attestationObject = null;
|
||||
protected $_authenticatorData = null;
|
||||
protected $_x5c_chain = array();
|
||||
protected $_x5c_tempFile = null;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param Array $AttestionObject
|
||||
* @param AuthenticatorData $authenticatorData
|
||||
*/
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
$this->_attestationObject = $AttestionObject;
|
||||
$this->_authenticatorData = $authenticatorData;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public function __destruct() {
|
||||
// delete X.509 chain certificate file after use
|
||||
if ($this->_x5c_tempFile && \is_file($this->_x5c_tempFile)) {
|
||||
\unlink($this->_x5c_tempFile);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the certificate chain in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificateChain() {
|
||||
if ($this->_x5c_tempFile && \is_file($this->_x5c_tempFile)) {
|
||||
return \file_get_contents($this->_x5c_tempFile);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the key X.509 certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
// need to be overwritten
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* checks validity of the signature
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
// need to be overwritten
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
// need to be overwritten
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* create a PEM encoded certificate with X.509 binary data
|
||||
* @param string $x5c
|
||||
* @return string
|
||||
*/
|
||||
protected function _createCertificatePem($x5c) {
|
||||
$pem = '-----BEGIN CERTIFICATE-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($x5c), 64, "\n");
|
||||
$pem .= '-----END CERTIFICATE-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* creates a PEM encoded chain file
|
||||
* @return type
|
||||
*/
|
||||
protected function _createX5cChainFile() {
|
||||
$content = '';
|
||||
if (\is_array($this->_x5c_chain) && \count($this->_x5c_chain) > 0) {
|
||||
foreach ($this->_x5c_chain as $x5c) {
|
||||
$certInfo = \openssl_x509_parse($this->_createCertificatePem($x5c));
|
||||
|
||||
// check if certificate is self signed
|
||||
if (\is_array($certInfo) && \is_array($certInfo['issuer']) && \is_array($certInfo['subject'])) {
|
||||
$selfSigned = false;
|
||||
|
||||
$subjectKeyIdentifier = $certInfo['extensions']['subjectKeyIdentifier'] ?? null;
|
||||
$authorityKeyIdentifier = $certInfo['extensions']['authorityKeyIdentifier'] ?? null;
|
||||
|
||||
if ($authorityKeyIdentifier && substr($authorityKeyIdentifier, 0, 6) === 'keyid:') {
|
||||
$authorityKeyIdentifier = substr($authorityKeyIdentifier, 6);
|
||||
}
|
||||
if ($subjectKeyIdentifier && substr($subjectKeyIdentifier, 0, 6) === 'keyid:') {
|
||||
$subjectKeyIdentifier = substr($subjectKeyIdentifier, 6);
|
||||
}
|
||||
|
||||
if (($subjectKeyIdentifier && !$authorityKeyIdentifier) || ($authorityKeyIdentifier && $authorityKeyIdentifier === $subjectKeyIdentifier)) {
|
||||
$selfSigned = true;
|
||||
}
|
||||
|
||||
if (!$selfSigned) {
|
||||
$content .= "\n" . $this->_createCertificatePem($x5c) . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($content) {
|
||||
$this->_x5c_tempFile = \tempnam(\sys_get_temp_dir(), 'x5c_');
|
||||
if (\file_put_contents($this->_x5c_tempFile, $content) !== false) {
|
||||
return $this->_x5c_tempFile;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns the name and openssl key for provided cose number.
|
||||
* @param int $coseNumber
|
||||
* @return \stdClass|null
|
||||
*/
|
||||
protected function _getCoseAlgorithm($coseNumber) {
|
||||
// https://www.iana.org/assignments/cose/cose.xhtml#algorithms
|
||||
$coseAlgorithms = array(
|
||||
array(
|
||||
'hash' => 'SHA1',
|
||||
'openssl' => OPENSSL_ALGO_SHA1,
|
||||
'cose' => array(
|
||||
-65535 // RS1
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA256',
|
||||
'openssl' => OPENSSL_ALGO_SHA256,
|
||||
'cose' => array(
|
||||
-257, // RS256
|
||||
-37, // PS256
|
||||
-7, // ES256
|
||||
5 // HMAC256
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA384',
|
||||
'openssl' => OPENSSL_ALGO_SHA384,
|
||||
'cose' => array(
|
||||
-258, // RS384
|
||||
-38, // PS384
|
||||
-35, // ES384
|
||||
6 // HMAC384
|
||||
)),
|
||||
|
||||
array(
|
||||
'hash' => 'SHA512',
|
||||
'openssl' => OPENSSL_ALGO_SHA512,
|
||||
'cose' => array(
|
||||
-259, // RS512
|
||||
-39, // PS512
|
||||
-36, // ES512
|
||||
7 // HMAC512
|
||||
))
|
||||
);
|
||||
|
||||
foreach ($coseAlgorithms as $coseAlgorithm) {
|
||||
if (\in_array($coseNumber, $coseAlgorithm['cose'], true)) {
|
||||
$return = new \stdClass();
|
||||
$return->hash = $coseAlgorithm['hash'];
|
||||
$return->openssl = $coseAlgorithm['openssl'];
|
||||
return $return;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
41
app-code/api/login/Attestation/Format/None.php
Normal file
41
app-code/api/login/Attestation/Format/None.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
|
||||
class None extends FormatBase {
|
||||
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates.
|
||||
* Format 'none' does not contain any ca, so always false.
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
139
app-code/api/login/Attestation/Format/Packed.php
Normal file
139
app-code/api/login/Attestation/Format/Packed.php
Normal file
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Packed extends FormatBase {
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
if (!$this->_x5c) {
|
||||
return null;
|
||||
}
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
if ($this->_x5c) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
} else {
|
||||
return $this->_validateSelfAttestation($clientDataHash);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
if (!$this->_x5c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the attestation public key in attestnCert with the algorithm specified in alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if self attestation is in use
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
*/
|
||||
protected function _validateSelfAttestation($clientDataHash) {
|
||||
// Verify that sig is a valid signature over the concatenation of authenticatorData and clientDataHash
|
||||
// using the credential public key with alg.
|
||||
$dataToVerify = $this->_authenticatorData->getBinary();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
$publicKey = $this->_authenticatorData->getPublicKeyPem();
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
}
|
||||
|
||||
180
app-code/api/login/Attestation/Format/Tpm.php
Normal file
180
app-code/api/login/Attestation/Format/Tpm.php
Normal file
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class Tpm extends FormatBase {
|
||||
private $_TPM_GENERATED_VALUE = "\xFF\x54\x43\x47";
|
||||
private $_TPM_ST_ATTEST_CERTIFY = "\x80\x17";
|
||||
private $_alg;
|
||||
private $_signature;
|
||||
private $_pubArea;
|
||||
private $_x5c;
|
||||
|
||||
/**
|
||||
* @var ByteBuffer
|
||||
*/
|
||||
private $_certInfo;
|
||||
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check packed data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (!\array_key_exists('ver', $attStmt) || $attStmt['ver'] !== '2.0') {
|
||||
throw new WebAuthnException('invalid tpm version: ' . $attStmt['ver'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('alg', $attStmt) || $this->_getCoseAlgorithm($attStmt['alg']) === null) {
|
||||
throw new WebAuthnException('unsupported alg: ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('signature not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('certInfo', $attStmt) || !\is_object($attStmt['certInfo']) || !($attStmt['certInfo'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('certInfo not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('pubArea', $attStmt) || !\is_object($attStmt['pubArea']) || !($attStmt['pubArea'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('pubArea not found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_alg = $attStmt['alg'];
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_certInfo = $attStmt['certInfo'];
|
||||
$this->_pubArea = $attStmt['pubArea'];
|
||||
|
||||
// certificate for validation
|
||||
if (\array_key_exists('x5c', $attStmt) && \is_array($attStmt['x5c']) && \count($attStmt['x5c']) > 0) {
|
||||
|
||||
// The attestation certificate attestnCert MUST be the first element in the array
|
||||
$attestnCert = array_shift($attStmt['x5c']);
|
||||
|
||||
if (!($attestnCert instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_x5c = $attestnCert->getBinaryString();
|
||||
|
||||
// certificate chain
|
||||
foreach ($attStmt['x5c'] as $chain) {
|
||||
if ($chain instanceof ByteBuffer) {
|
||||
$this->_x5c_chain[] = $chain->getBinaryString();
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new WebAuthnException('no x5c certificate found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string|null
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
if (!$this->_x5c) {
|
||||
return null;
|
||||
}
|
||||
return $this->_createCertificatePem($this->_x5c);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
return $this->_validateOverX5c($clientDataHash);
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
if (!$this->_x5c) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* validate if x5c is present
|
||||
* @param string $clientDataHash
|
||||
* @return bool
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected function _validateOverX5c($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Concatenate authenticatorData and clientDataHash to form attToBeSigned.
|
||||
$attToBeSigned = $this->_authenticatorData->getBinary();
|
||||
$attToBeSigned .= $clientDataHash;
|
||||
|
||||
// Validate that certInfo is valid:
|
||||
|
||||
// Verify that magic is set to TPM_GENERATED_VALUE.
|
||||
if ($this->_certInfo->getBytes(0, 4) !== $this->_TPM_GENERATED_VALUE) {
|
||||
throw new WebAuthnException('tpm magic not TPM_GENERATED_VALUE', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify that type is set to TPM_ST_ATTEST_CERTIFY.
|
||||
if ($this->_certInfo->getBytes(4, 2) !== $this->_TPM_ST_ATTEST_CERTIFY) {
|
||||
throw new WebAuthnException('tpm type not TPM_ST_ATTEST_CERTIFY', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$offset = 6;
|
||||
$qualifiedSigner = $this->_tpmReadLengthPrefixed($this->_certInfo, $offset);
|
||||
$extraData = $this->_tpmReadLengthPrefixed($this->_certInfo, $offset);
|
||||
$coseAlg = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// Verify that extraData is set to the hash of attToBeSigned using the hash algorithm employed in "alg".
|
||||
if ($extraData->getBinaryString() !== \hash($coseAlg->hash, $attToBeSigned, true)) {
|
||||
throw new WebAuthnException('certInfo:extraData not hash of attToBeSigned', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// Verify the sig is a valid signature over certInfo using the attestation
|
||||
// public key in aikCert with the algorithm specified in alg.
|
||||
return \openssl_verify($this->_certInfo->getBinaryString(), $this->_signature, $publicKey, $coseAlg->openssl) === 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* returns next part of ByteBuffer
|
||||
* @param ByteBuffer $buffer
|
||||
* @param int $offset
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
protected function _tpmReadLengthPrefixed(ByteBuffer $buffer, &$offset) {
|
||||
$len = $buffer->getUint16Val($offset);
|
||||
$data = $buffer->getBytes($offset + 2, $len);
|
||||
$offset += (2 + $len);
|
||||
|
||||
return new ByteBuffer($data);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
93
app-code/api/login/Attestation/Format/U2f.php
Normal file
93
app-code/api/login/Attestation/Format/U2f.php
Normal file
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Attestation\Format;
|
||||
use lbuchs\WebAuthn\Attestation\AuthenticatorData;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
class U2f extends FormatBase {
|
||||
private $_alg = -7;
|
||||
private $_signature;
|
||||
private $_x5c;
|
||||
|
||||
public function __construct($AttestionObject, AuthenticatorData $authenticatorData) {
|
||||
parent::__construct($AttestionObject, $authenticatorData);
|
||||
|
||||
// check u2f data
|
||||
$attStmt = $this->_attestationObject['attStmt'];
|
||||
|
||||
if (\array_key_exists('alg', $attStmt) && $attStmt['alg'] !== $this->_alg) {
|
||||
throw new WebAuthnException('u2f only accepts algorithm -7 ("ES256"), but got ' . $attStmt['alg'], WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('sig', $attStmt) || !\is_object($attStmt['sig']) || !($attStmt['sig'] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('no signature found', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\array_key_exists('x5c', $attStmt) || !\is_array($attStmt['x5c']) || \count($attStmt['x5c']) !== 1) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
if (!\is_object($attStmt['x5c'][0]) || !($attStmt['x5c'][0] instanceof ByteBuffer)) {
|
||||
throw new WebAuthnException('invalid x5c certificate', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
$this->_signature = $attStmt['sig']->getBinaryString();
|
||||
$this->_x5c = $attStmt['x5c'][0]->getBinaryString();
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* returns the key certificate in PEM format
|
||||
* @return string
|
||||
*/
|
||||
public function getCertificatePem() {
|
||||
$pem = '-----BEGIN CERTIFICATE-----' . "\n";
|
||||
$pem .= \chunk_split(\base64_encode($this->_x5c), 64, "\n");
|
||||
$pem .= '-----END CERTIFICATE-----' . "\n";
|
||||
return $pem;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $clientDataHash
|
||||
*/
|
||||
public function validateAttestation($clientDataHash) {
|
||||
$publicKey = \openssl_pkey_get_public($this->getCertificatePem());
|
||||
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('invalid public key: ' . \openssl_error_string(), WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
// Let verificationData be the concatenation of (0x00 || rpIdHash || clientDataHash || credentialId || publicKeyU2F)
|
||||
$dataToVerify = "\x00";
|
||||
$dataToVerify .= $this->_authenticatorData->getRpIdHash();
|
||||
$dataToVerify .= $clientDataHash;
|
||||
$dataToVerify .= $this->_authenticatorData->getCredentialId();
|
||||
$dataToVerify .= $this->_authenticatorData->getPublicKeyU2F();
|
||||
|
||||
$coseAlgorithm = $this->_getCoseAlgorithm($this->_alg);
|
||||
|
||||
// check certificate
|
||||
return \openssl_verify($dataToVerify, $this->_signature, $publicKey, $coseAlgorithm->openssl) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* validates the certificate against root certificates
|
||||
* @param array $rootCas
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function validateRootCertificate($rootCas) {
|
||||
$chainC = $this->_createX5cChainFile();
|
||||
if ($chainC) {
|
||||
$rootCas[] = $chainC;
|
||||
}
|
||||
|
||||
$v = \openssl_x509_checkpurpose($this->getCertificatePem(), -1, $rootCas);
|
||||
if ($v === -1) {
|
||||
throw new WebAuthnException('error on validating root certificate: ' . \openssl_error_string(), WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
300
app-code/api/login/Binary/ByteBuffer.php
Normal file
300
app-code/api/login/Binary/ByteBuffer.php
Normal file
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\Binary;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
|
||||
/**
|
||||
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/ByteBuffer.php
|
||||
* Copyright © 2018 Thomas Bleeker - MIT licensed
|
||||
* Modified by Lukas Buchs
|
||||
* Thanks Thomas for your work!
|
||||
*/
|
||||
class ByteBuffer implements \JsonSerializable, \Serializable {
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
public static $useBase64UrlEncoding = false;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $_data;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $_length;
|
||||
|
||||
public function __construct($binaryData) {
|
||||
$this->_data = (string)$binaryData;
|
||||
$this->_length = \strlen($binaryData);
|
||||
}
|
||||
|
||||
|
||||
// -----------------------
|
||||
// PUBLIC STATIC
|
||||
// -----------------------
|
||||
|
||||
/**
|
||||
* create a ByteBuffer from a base64 url encoded string
|
||||
* @param string $base64url
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public static function fromBase64Url($base64url): ByteBuffer {
|
||||
$bin = self::_base64url_decode($base64url);
|
||||
if ($bin === false) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid base64 url string', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return new ByteBuffer($bin);
|
||||
}
|
||||
|
||||
/**
|
||||
* create a ByteBuffer from a base64 url encoded string
|
||||
* @param string $hex
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public static function fromHex($hex): ByteBuffer {
|
||||
$bin = \hex2bin($hex);
|
||||
if ($bin === false) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid hex string', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return new ByteBuffer($bin);
|
||||
}
|
||||
|
||||
/**
|
||||
* create a random ByteBuffer
|
||||
* @param string $length
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public static function randomBuffer($length): ByteBuffer {
|
||||
if (\function_exists('random_bytes')) { // >PHP 7.0
|
||||
return new ByteBuffer(\random_bytes($length));
|
||||
|
||||
} else if (\function_exists('openssl_random_pseudo_bytes')) {
|
||||
return new ByteBuffer(\openssl_random_pseudo_bytes($length));
|
||||
|
||||
} else {
|
||||
throw new WebAuthnException('ByteBuffer: cannot generate random bytes', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------
|
||||
// PUBLIC
|
||||
// -----------------------
|
||||
|
||||
public function getBytes($offset, $length): string {
|
||||
if ($offset < 0 || $length < 0 || ($offset + $length > $this->_length)) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset or length', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return \substr($this->_data, $offset, $length);
|
||||
}
|
||||
|
||||
public function getByteVal($offset): int {
|
||||
if ($offset < 0 || $offset >= $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return \ord(\substr($this->_data, $offset, 1));
|
||||
}
|
||||
|
||||
public function getJson($jsonFlags=0) {
|
||||
$data = \json_decode($this->getBinaryString(), null, 512, $jsonFlags);
|
||||
if (\json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new WebAuthnException(\json_last_error_msg(), WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function getLength(): int {
|
||||
return $this->_length;
|
||||
}
|
||||
|
||||
public function getUint16Val($offset) {
|
||||
if ($offset < 0 || ($offset + 2) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return unpack('n', $this->_data, $offset)[1];
|
||||
}
|
||||
|
||||
public function getUint32Val($offset) {
|
||||
if ($offset < 0 || ($offset + 4) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
$val = unpack('N', $this->_data, $offset)[1];
|
||||
|
||||
// Signed integer overflow causes signed negative numbers
|
||||
if ($val < 0) {
|
||||
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return $val;
|
||||
}
|
||||
|
||||
public function getUint64Val($offset) {
|
||||
if (PHP_INT_SIZE < 8) {
|
||||
throw new WebAuthnException('ByteBuffer: 64-bit values not supported by this system', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
if ($offset < 0 || ($offset + 8) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
$val = unpack('J', $this->_data, $offset)[1];
|
||||
|
||||
// Signed integer overflow causes signed negative numbers
|
||||
if ($val < 0) {
|
||||
throw new WebAuthnException('ByteBuffer: Value out of integer range.', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
|
||||
return $val;
|
||||
}
|
||||
|
||||
public function getHalfFloatVal($offset) {
|
||||
//FROM spec pseudo decode_half(unsigned char *halfp)
|
||||
$half = $this->getUint16Val($offset);
|
||||
|
||||
$exp = ($half >> 10) & 0x1f;
|
||||
$mant = $half & 0x3ff;
|
||||
|
||||
if ($exp === 0) {
|
||||
$val = $mant * (2 ** -24);
|
||||
} elseif ($exp !== 31) {
|
||||
$val = ($mant + 1024) * (2 ** ($exp - 25));
|
||||
} else {
|
||||
$val = ($mant === 0) ? INF : NAN;
|
||||
}
|
||||
|
||||
return ($half & 0x8000) ? -$val : $val;
|
||||
}
|
||||
|
||||
public function getFloatVal($offset) {
|
||||
if ($offset < 0 || ($offset + 4) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return unpack('G', $this->_data, $offset)[1];
|
||||
}
|
||||
|
||||
public function getDoubleVal($offset) {
|
||||
if ($offset < 0 || ($offset + 8) > $this->_length) {
|
||||
throw new WebAuthnException('ByteBuffer: Invalid offset', WebAuthnException::BYTEBUFFER);
|
||||
}
|
||||
return unpack('E', $this->_data, $offset)[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getBinaryString(): string {
|
||||
return $this->_data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|ByteBuffer $buffer
|
||||
* @return bool
|
||||
*/
|
||||
public function equals($buffer): bool {
|
||||
if (is_object($buffer) && $buffer instanceof ByteBuffer) {
|
||||
return $buffer->getBinaryString() === $this->getBinaryString();
|
||||
|
||||
} else if (is_string($buffer)) {
|
||||
return $buffer === $this->getBinaryString();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getHex(): string {
|
||||
return \bin2hex($this->_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isEmpty(): bool {
|
||||
return $this->_length === 0;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* jsonSerialize interface
|
||||
* return binary data in RFC 1342-Like serialized string
|
||||
* @return string
|
||||
*/
|
||||
public function jsonSerialize(): string {
|
||||
if (ByteBuffer::$useBase64UrlEncoding) {
|
||||
return self::_base64url_encode($this->_data);
|
||||
|
||||
} else {
|
||||
return '=?BINARY?B?' . \base64_encode($this->_data) . '?=';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializable-Interface
|
||||
* @return string
|
||||
*/
|
||||
public function serialize(): string {
|
||||
return \serialize($this->_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializable-Interface
|
||||
* @param string $serialized
|
||||
*/
|
||||
public function unserialize($serialized) {
|
||||
$this->_data = \unserialize($serialized);
|
||||
$this->_length = \strlen($this->_data);
|
||||
}
|
||||
|
||||
/**
|
||||
* (PHP 8 deprecates Serializable-Interface)
|
||||
* @return array
|
||||
*/
|
||||
public function __serialize(): array {
|
||||
return [
|
||||
'data' => \serialize($this->_data)
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* object to string
|
||||
* @return string
|
||||
*/
|
||||
public function __toString(): string {
|
||||
return $this->getHex();
|
||||
}
|
||||
|
||||
/**
|
||||
* (PHP 8 deprecates Serializable-Interface)
|
||||
* @param array $data
|
||||
* @return void
|
||||
*/
|
||||
public function __unserialize($data) {
|
||||
if ($data && isset($data['data'])) {
|
||||
$this->_data = \unserialize($data['data']);
|
||||
$this->_length = \strlen($this->_data);
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------
|
||||
// PROTECTED STATIC
|
||||
// -----------------------
|
||||
|
||||
/**
|
||||
* base64 url decoding
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
protected static function _base64url_decode($data): string {
|
||||
return \base64_decode(\strtr($data, '-_', '+/') . \str_repeat('=', 3 - (3 + \strlen($data)) % 4));
|
||||
}
|
||||
|
||||
/**
|
||||
* base64 url encoding
|
||||
* @param string $data
|
||||
* @return string
|
||||
*/
|
||||
protected static function _base64url_encode($data): string {
|
||||
return \rtrim(\strtr(\base64_encode($data), '+/', '-_'), '=');
|
||||
}
|
||||
}
|
||||
220
app-code/api/login/CBOR/CborDecoder.php
Normal file
220
app-code/api/login/CBOR/CborDecoder.php
Normal file
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace lbuchs\WebAuthn\CBOR;
|
||||
use lbuchs\WebAuthn\WebAuthnException;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
|
||||
/**
|
||||
* Modified version of https://github.com/madwizard-thomas/webauthn-server/blob/master/src/Format/CborDecoder.php
|
||||
* Copyright © 2018 Thomas Bleeker - MIT licensed
|
||||
* Modified by Lukas Buchs
|
||||
* Thanks Thomas for your work!
|
||||
*/
|
||||
class CborDecoder {
|
||||
const CBOR_MAJOR_UNSIGNED_INT = 0;
|
||||
const CBOR_MAJOR_TEXT_STRING = 3;
|
||||
const CBOR_MAJOR_FLOAT_SIMPLE = 7;
|
||||
const CBOR_MAJOR_NEGATIVE_INT = 1;
|
||||
const CBOR_MAJOR_ARRAY = 4;
|
||||
const CBOR_MAJOR_TAG = 6;
|
||||
const CBOR_MAJOR_MAP = 5;
|
||||
const CBOR_MAJOR_BYTE_STRING = 2;
|
||||
|
||||
/**
|
||||
* @param ByteBuffer|string $bufOrBin
|
||||
* @return mixed
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public static function decode($bufOrBin) {
|
||||
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
|
||||
|
||||
$offset = 0;
|
||||
$result = self::_parseItem($buf, $offset);
|
||||
if ($offset !== $buf->getLength()) {
|
||||
throw new WebAuthnException('Unused bytes after data item.', WebAuthnException::CBOR);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ByteBuffer|string $bufOrBin
|
||||
* @param int $startOffset
|
||||
* @param int|null $endOffset
|
||||
* @return mixed
|
||||
*/
|
||||
public static function decodeInPlace($bufOrBin, $startOffset, &$endOffset = null) {
|
||||
$buf = $bufOrBin instanceof ByteBuffer ? $bufOrBin : new ByteBuffer($bufOrBin);
|
||||
|
||||
$offset = $startOffset;
|
||||
$data = self::_parseItem($buf, $offset);
|
||||
$endOffset = $offset;
|
||||
return $data;
|
||||
}
|
||||
|
||||
// ---------------------
|
||||
// protected
|
||||
// ---------------------
|
||||
|
||||
/**
|
||||
* @param ByteBuffer $buf
|
||||
* @param int $offset
|
||||
* @return mixed
|
||||
*/
|
||||
protected static function _parseItem(ByteBuffer $buf, &$offset) {
|
||||
$first = $buf->getByteVal($offset++);
|
||||
$type = $first >> 5;
|
||||
$val = $first & 0b11111;
|
||||
|
||||
if ($type === self::CBOR_MAJOR_FLOAT_SIMPLE) {
|
||||
return self::_parseFloatSimple($val, $buf, $offset);
|
||||
}
|
||||
|
||||
$val = self::_parseExtraLength($val, $buf, $offset);
|
||||
|
||||
return self::_parseItemData($type, $val, $buf, $offset);
|
||||
}
|
||||
|
||||
protected static function _parseFloatSimple($val, ByteBuffer $buf, &$offset) {
|
||||
switch ($val) {
|
||||
case 24:
|
||||
$val = $buf->getByteVal($offset);
|
||||
$offset++;
|
||||
return self::_parseSimple($val);
|
||||
|
||||
case 25:
|
||||
$floatValue = $buf->getHalfFloatVal($offset);
|
||||
$offset += 2;
|
||||
return $floatValue;
|
||||
|
||||
case 26:
|
||||
$floatValue = $buf->getFloatVal($offset);
|
||||
$offset += 4;
|
||||
return $floatValue;
|
||||
|
||||
case 27:
|
||||
$floatValue = $buf->getDoubleVal($offset);
|
||||
$offset += 8;
|
||||
return $floatValue;
|
||||
|
||||
case 28:
|
||||
case 29:
|
||||
case 30:
|
||||
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
|
||||
|
||||
case 31:
|
||||
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
return self::_parseSimple($val);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $val
|
||||
* @return mixed
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
protected static function _parseSimple($val) {
|
||||
if ($val === 20) {
|
||||
return false;
|
||||
}
|
||||
if ($val === 21) {
|
||||
return true;
|
||||
}
|
||||
if ($val === 22) {
|
||||
return null;
|
||||
}
|
||||
throw new WebAuthnException(sprintf('Unsupported simple value %d.', $val), WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
protected static function _parseExtraLength($val, ByteBuffer $buf, &$offset) {
|
||||
switch ($val) {
|
||||
case 24:
|
||||
$val = $buf->getByteVal($offset);
|
||||
$offset++;
|
||||
break;
|
||||
|
||||
case 25:
|
||||
$val = $buf->getUint16Val($offset);
|
||||
$offset += 2;
|
||||
break;
|
||||
|
||||
case 26:
|
||||
$val = $buf->getUint32Val($offset);
|
||||
$offset += 4;
|
||||
break;
|
||||
|
||||
case 27:
|
||||
$val = $buf->getUint64Val($offset);
|
||||
$offset += 8;
|
||||
break;
|
||||
|
||||
case 28:
|
||||
case 29:
|
||||
case 30:
|
||||
throw new WebAuthnException('Reserved value used.', WebAuthnException::CBOR);
|
||||
|
||||
case 31:
|
||||
throw new WebAuthnException('Indefinite length is not supported.', WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
return $val;
|
||||
}
|
||||
|
||||
protected static function _parseItemData($type, $val, ByteBuffer $buf, &$offset) {
|
||||
switch ($type) {
|
||||
case self::CBOR_MAJOR_UNSIGNED_INT: // uint
|
||||
return $val;
|
||||
|
||||
case self::CBOR_MAJOR_NEGATIVE_INT:
|
||||
return -1 - $val;
|
||||
|
||||
case self::CBOR_MAJOR_BYTE_STRING:
|
||||
$data = $buf->getBytes($offset, $val);
|
||||
$offset += $val;
|
||||
return new ByteBuffer($data); // bytes
|
||||
|
||||
case self::CBOR_MAJOR_TEXT_STRING:
|
||||
$data = $buf->getBytes($offset, $val);
|
||||
$offset += $val;
|
||||
return $data; // UTF-8
|
||||
|
||||
case self::CBOR_MAJOR_ARRAY:
|
||||
return self::_parseArray($buf, $offset, $val);
|
||||
|
||||
case self::CBOR_MAJOR_MAP:
|
||||
return self::_parseMap($buf, $offset, $val);
|
||||
|
||||
case self::CBOR_MAJOR_TAG:
|
||||
return self::_parseItem($buf, $offset); // 1 embedded data item
|
||||
}
|
||||
|
||||
// This should never be reached
|
||||
throw new WebAuthnException(sprintf('Unknown major type %d.', $type), WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
protected static function _parseMap(ByteBuffer $buf, &$offset, $count) {
|
||||
$map = array();
|
||||
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$mapKey = self::_parseItem($buf, $offset);
|
||||
$mapVal = self::_parseItem($buf, $offset);
|
||||
|
||||
if (!\is_int($mapKey) && !\is_string($mapKey)) {
|
||||
throw new WebAuthnException('Can only use strings or integers as map keys', WebAuthnException::CBOR);
|
||||
}
|
||||
|
||||
$map[$mapKey] = $mapVal; // todo dup
|
||||
}
|
||||
return $map;
|
||||
}
|
||||
|
||||
protected static function _parseArray(ByteBuffer $buf, &$offset, $count) {
|
||||
$arr = array();
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$arr[] = self::_parseItem($buf, $offset);
|
||||
}
|
||||
|
||||
return $arr;
|
||||
}
|
||||
}
|
||||
677
app-code/api/login/WebAuthn.php
Normal file
677
app-code/api/login/WebAuthn.php
Normal file
@@ -0,0 +1,677 @@
|
||||
<?php
|
||||
|
||||
namespace lbuchs\WebAuthn;
|
||||
use lbuchs\WebAuthn\Binary\ByteBuffer;
|
||||
require_once 'WebAuthnException.php';
|
||||
require_once 'Binary/ByteBuffer.php';
|
||||
require_once 'Attestation/AttestationObject.php';
|
||||
require_once 'Attestation/AuthenticatorData.php';
|
||||
require_once 'Attestation/Format/FormatBase.php';
|
||||
require_once 'Attestation/Format/None.php';
|
||||
require_once 'Attestation/Format/AndroidKey.php';
|
||||
require_once 'Attestation/Format/AndroidSafetyNet.php';
|
||||
require_once 'Attestation/Format/Apple.php';
|
||||
require_once 'Attestation/Format/Packed.php';
|
||||
require_once 'Attestation/Format/Tpm.php';
|
||||
require_once 'Attestation/Format/U2f.php';
|
||||
require_once 'CBOR/CborDecoder.php';
|
||||
|
||||
/**
|
||||
* WebAuthn
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class WebAuthn {
|
||||
// relying party
|
||||
private $_rpName;
|
||||
private $_rpId;
|
||||
private $_rpIdHash;
|
||||
private $_challenge;
|
||||
private $_signatureCounter;
|
||||
private $_caFiles;
|
||||
private $_formats;
|
||||
|
||||
/**
|
||||
* Initialize a new WebAuthn server
|
||||
* @param string $rpName the relying party name
|
||||
* @param string $rpId the relying party ID = the domain name
|
||||
* @param bool $useBase64UrlEncoding true to use base64 url encoding for binary data in json objects. Default is a RFC 1342-Like serialized string.
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function __construct($rpName, $rpId, $allowedFormats=null, $useBase64UrlEncoding=false) {
|
||||
$this->_rpName = $rpName;
|
||||
$this->_rpId = $rpId;
|
||||
$this->_rpIdHash = \hash('sha256', $rpId, true);
|
||||
ByteBuffer::$useBase64UrlEncoding = !!$useBase64UrlEncoding;
|
||||
$supportedFormats = array('android-key', 'android-safetynet', 'apple', 'fido-u2f', 'none', 'packed', 'tpm');
|
||||
|
||||
if (!\function_exists('\openssl_open')) {
|
||||
throw new WebAuthnException('OpenSSL-Module not installed');
|
||||
}
|
||||
|
||||
if (!\in_array('SHA256', \array_map('\strtoupper', \openssl_get_md_methods()))) {
|
||||
throw new WebAuthnException('SHA256 not supported by this openssl installation.');
|
||||
}
|
||||
|
||||
// default: all format
|
||||
if (!is_array($allowedFormats)) {
|
||||
$allowedFormats = $supportedFormats;
|
||||
}
|
||||
$this->_formats = $allowedFormats;
|
||||
|
||||
// validate formats
|
||||
$invalidFormats = \array_diff($this->_formats, $supportedFormats);
|
||||
if (!$this->_formats || $invalidFormats) {
|
||||
throw new WebAuthnException('invalid formats on construct: ' . implode(', ', $invalidFormats));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* add a root certificate to verify new registrations
|
||||
* @param string $path file path of / directory with root certificates
|
||||
* @param array|null $certFileExtensions if adding a direction, all files with provided extension are added. default: pem, crt, cer, der
|
||||
*/
|
||||
public function addRootCertificates($path, $certFileExtensions=null) {
|
||||
if (!\is_array($this->_caFiles)) {
|
||||
$this->_caFiles = [];
|
||||
}
|
||||
if ($certFileExtensions === null) {
|
||||
$certFileExtensions = array('pem', 'crt', 'cer', 'der');
|
||||
}
|
||||
$path = \rtrim(\trim($path), '\\/');
|
||||
if (\is_dir($path)) {
|
||||
foreach (\scandir($path) as $ca) {
|
||||
if (\is_file($path . DIRECTORY_SEPARATOR . $ca) && \in_array(\strtolower(\pathinfo($ca, PATHINFO_EXTENSION)), $certFileExtensions)) {
|
||||
$this->addRootCertificates($path . DIRECTORY_SEPARATOR . $ca);
|
||||
}
|
||||
}
|
||||
} else if (\is_file($path) && !\in_array(\realpath($path), $this->_caFiles)) {
|
||||
$this->_caFiles[] = \realpath($path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the generated challenge to save for later validation
|
||||
* @return ByteBuffer
|
||||
*/
|
||||
public function getChallenge() {
|
||||
return $this->_challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates the object for a key registration
|
||||
* provide this data to navigator.credentials.create
|
||||
* @param string $userId
|
||||
* @param string $userName
|
||||
* @param string $userDisplayName
|
||||
* @param int $timeout timeout in seconds
|
||||
* @param bool|string $requireResidentKey 'required', if the key should be stored by the authentication device
|
||||
* Valid values:
|
||||
* true = required
|
||||
* false = preferred
|
||||
* string 'required' 'preferred' 'discouraged'
|
||||
* @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
|
||||
* if the response does not have the UV flag set.
|
||||
* Valid values:
|
||||
* true = required
|
||||
* false = preferred
|
||||
* string 'required' 'preferred' 'discouraged'
|
||||
* @param bool|null $crossPlatformAttachment true for cross-platform devices (eg. fido usb),
|
||||
* false for platform devices (eg. windows hello, android safetynet),
|
||||
* null for both
|
||||
* @param array $excludeCredentialIds a array of ids, which are already registered, to prevent re-registration
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function getCreateArgs($userId, $userName, $userDisplayName, $timeout=20, $requireResidentKey=false, $requireUserVerification=false, $crossPlatformAttachment=null, $excludeCredentialIds=[]) {
|
||||
|
||||
$args = new \stdClass();
|
||||
$args->publicKey = new \stdClass();
|
||||
|
||||
// relying party
|
||||
$args->publicKey->rp = new \stdClass();
|
||||
$args->publicKey->rp->name = $this->_rpName;
|
||||
$args->publicKey->rp->id = $this->_rpId;
|
||||
|
||||
$args->publicKey->authenticatorSelection = new \stdClass();
|
||||
$args->publicKey->authenticatorSelection->userVerification = 'preferred';
|
||||
|
||||
// validate User Verification Requirement
|
||||
if (\is_bool($requireUserVerification)) {
|
||||
$args->publicKey->authenticatorSelection->userVerification = $requireUserVerification ? 'required' : 'preferred';
|
||||
|
||||
} else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
|
||||
$args->publicKey->authenticatorSelection->userVerification = \strtolower($requireUserVerification);
|
||||
}
|
||||
|
||||
// validate Resident Key Requirement
|
||||
if (\is_bool($requireResidentKey) && $requireResidentKey) {
|
||||
$args->publicKey->authenticatorSelection->requireResidentKey = true;
|
||||
$args->publicKey->authenticatorSelection->residentKey = 'required';
|
||||
|
||||
} else if (\is_string($requireResidentKey) && \in_array(\strtolower($requireResidentKey), ['required', 'preferred', 'discouraged'])) {
|
||||
$requireResidentKey = \strtolower($requireResidentKey);
|
||||
$args->publicKey->authenticatorSelection->residentKey = $requireResidentKey;
|
||||
$args->publicKey->authenticatorSelection->requireResidentKey = $requireResidentKey === 'required';
|
||||
}
|
||||
|
||||
// filte authenticators attached with the specified authenticator attachment modality
|
||||
if (\is_bool($crossPlatformAttachment)) {
|
||||
$args->publicKey->authenticatorSelection->authenticatorAttachment = $crossPlatformAttachment ? 'cross-platform' : 'platform';
|
||||
}
|
||||
|
||||
// user
|
||||
$args->publicKey->user = new \stdClass();
|
||||
$args->publicKey->user->id = new ByteBuffer($userId); // binary
|
||||
$args->publicKey->user->name = $userName;
|
||||
$args->publicKey->user->displayName = $userDisplayName;
|
||||
|
||||
// supported algorithms
|
||||
$args->publicKey->pubKeyCredParams = [];
|
||||
|
||||
if (function_exists('sodium_crypto_sign_verify_detached') || \in_array('ed25519', \openssl_get_curve_names(), true)) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -8; // EdDSA
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
|
||||
if (\in_array('prime256v1', \openssl_get_curve_names(), true)) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -7; // ES256
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
|
||||
$tmp = new \stdClass();
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->alg = -257; // RS256
|
||||
$args->publicKey->pubKeyCredParams[] = $tmp;
|
||||
unset ($tmp);
|
||||
|
||||
// if there are root certificates added, we need direct attestation to validate
|
||||
// against the root certificate. If there are no root-certificates added,
|
||||
// anonymization ca are also accepted, because we can't validate the root anyway.
|
||||
$attestation = 'indirect';
|
||||
if (\is_array($this->_caFiles)) {
|
||||
$attestation = 'direct';
|
||||
}
|
||||
|
||||
$args->publicKey->attestation = \count($this->_formats) === 1 && \in_array('none', $this->_formats) ? 'none' : $attestation;
|
||||
$args->publicKey->extensions = new \stdClass();
|
||||
$args->publicKey->extensions->exts = true;
|
||||
$args->publicKey->timeout = $timeout * 1000; // microseconds
|
||||
$args->publicKey->challenge = $this->_createChallenge(); // binary
|
||||
|
||||
//prevent re-registration by specifying existing credentials
|
||||
$args->publicKey->excludeCredentials = [];
|
||||
|
||||
if (is_array($excludeCredentialIds)) {
|
||||
foreach ($excludeCredentialIds as $id) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id); // binary
|
||||
$tmp->type = 'public-key';
|
||||
$tmp->transports = array('usb', 'nfc', 'ble', 'hybrid', 'internal');
|
||||
$args->publicKey->excludeCredentials[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
}
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates the object for key validation
|
||||
* Provide this data to navigator.credentials.get
|
||||
* @param array $credentialIds binary
|
||||
* @param int $timeout timeout in seconds
|
||||
* @param bool $allowUsb allow removable USB
|
||||
* @param bool $allowNfc allow Near Field Communication (NFC)
|
||||
* @param bool $allowBle allow Bluetooth
|
||||
* @param bool $allowHybrid allow a combination of (often separate) data-transport and proximity mechanisms.
|
||||
* @param bool $allowInternal allow client device-specific transport. These authenticators are not removable from the client device.
|
||||
* @param bool|string $requireUserVerification indicates that you require user verification and will fail the operation
|
||||
* if the response does not have the UV flag set.
|
||||
* Valid values:
|
||||
* true = required
|
||||
* false = preferred
|
||||
* string 'required' 'preferred' 'discouraged'
|
||||
* @return \stdClass
|
||||
*/
|
||||
public function getGetArgs($credentialIds=[], $timeout=20, $allowUsb=true, $allowNfc=true, $allowBle=true, $allowHybrid=true, $allowInternal=true, $requireUserVerification=false) {
|
||||
|
||||
// validate User Verification Requirement
|
||||
if (\is_bool($requireUserVerification)) {
|
||||
$requireUserVerification = $requireUserVerification ? 'required' : 'preferred';
|
||||
} else if (\is_string($requireUserVerification) && \in_array(\strtolower($requireUserVerification), ['required', 'preferred', 'discouraged'])) {
|
||||
$requireUserVerification = \strtolower($requireUserVerification);
|
||||
} else {
|
||||
$requireUserVerification = 'preferred';
|
||||
}
|
||||
|
||||
$args = new \stdClass();
|
||||
$args->publicKey = new \stdClass();
|
||||
$args->publicKey->timeout = $timeout * 1000; // microseconds
|
||||
$args->publicKey->challenge = $this->_createChallenge(); // binary
|
||||
$args->publicKey->userVerification = $requireUserVerification;
|
||||
$args->publicKey->rpId = $this->_rpId;
|
||||
|
||||
if (\is_array($credentialIds) && \count($credentialIds) > 0) {
|
||||
$args->publicKey->allowCredentials = [];
|
||||
|
||||
foreach ($credentialIds as $id) {
|
||||
$tmp = new \stdClass();
|
||||
$tmp->id = $id instanceof ByteBuffer ? $id : new ByteBuffer($id); // binary
|
||||
$tmp->transports = [];
|
||||
|
||||
if ($allowUsb) {
|
||||
$tmp->transports[] = 'usb';
|
||||
}
|
||||
if ($allowNfc) {
|
||||
$tmp->transports[] = 'nfc';
|
||||
}
|
||||
if ($allowBle) {
|
||||
$tmp->transports[] = 'ble';
|
||||
}
|
||||
if ($allowHybrid) {
|
||||
$tmp->transports[] = 'hybrid';
|
||||
}
|
||||
if ($allowInternal) {
|
||||
$tmp->transports[] = 'internal';
|
||||
}
|
||||
|
||||
$tmp->type = 'public-key';
|
||||
$args->publicKey->allowCredentials[] = $tmp;
|
||||
unset ($tmp);
|
||||
}
|
||||
}
|
||||
|
||||
return $args;
|
||||
}
|
||||
|
||||
/**
|
||||
* returns the new signature counter value.
|
||||
* returns null if there is no counter
|
||||
* @return ?int
|
||||
*/
|
||||
public function getSignatureCounter() {
|
||||
return \is_int($this->_signatureCounter) ? $this->_signatureCounter : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* process a create request and returns data to save for future logins
|
||||
* @param string $clientDataJSON binary from browser
|
||||
* @param string $attestationObject binary from browser
|
||||
* @param string|ByteBuffer $challenge binary used challange
|
||||
* @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
|
||||
* @param bool $requireUserPresent false, if the device must NOT check user presence (e.g. by pressing a button)
|
||||
* @param bool $failIfRootMismatch false, if there should be no error thrown if root certificate doesn't match
|
||||
* @param bool $requireCtsProfileMatch false, if you don't want to check if the device is approved as a Google-certified Android device.
|
||||
* @return \stdClass
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function processCreate($clientDataJSON, $attestationObject, $challenge, $requireUserVerification=false, $requireUserPresent=true, $failIfRootMismatch=true, $requireCtsProfileMatch=true) {
|
||||
$clientDataHash = \hash('sha256', $clientDataJSON, true);
|
||||
$clientData = \json_decode($clientDataJSON);
|
||||
$challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
|
||||
|
||||
// security: https://www.w3.org/TR/webauthn/#registering-a-new-credential
|
||||
|
||||
// 2. Let C, the client data claimed as collected during the credential creation,
|
||||
// be the result of running an implementation-specific JSON parser on JSONtext.
|
||||
if (!\is_object($clientData)) {
|
||||
throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// 3. Verify that the value of C.type is webauthn.create.
|
||||
if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.create') {
|
||||
throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
|
||||
}
|
||||
|
||||
// 4. Verify that the value of C.challenge matches the challenge that was sent to the authenticator in the create() call.
|
||||
if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
|
||||
throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
|
||||
}
|
||||
|
||||
// 5. Verify that the value of C.origin matches the Relying Party's origin.
|
||||
if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
|
||||
throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// Attestation
|
||||
$attestationObject = new Attestation\AttestationObject($attestationObject, $this->_formats);
|
||||
|
||||
// 9. Verify that the RP ID hash in authData is indeed the SHA-256 hash of the RP ID expected by the RP.
|
||||
if (!$attestationObject->validateRpIdHash($this->_rpIdHash)) {
|
||||
throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
|
||||
}
|
||||
|
||||
// 14. Verify that attStmt is a correct attestation statement, conveying a valid attestation signature
|
||||
if (!$attestationObject->validateAttestation($clientDataHash)) {
|
||||
throw new WebAuthnException('invalid certificate signature', WebAuthnException::INVALID_SIGNATURE);
|
||||
}
|
||||
|
||||
// Android-SafetyNet: if required, check for Compatibility Testing Suite (CTS).
|
||||
if ($requireCtsProfileMatch && $attestationObject->getAttestationFormat() instanceof Attestation\Format\AndroidSafetyNet) {
|
||||
if (!$attestationObject->getAttestationFormat()->ctsProfileMatch()) {
|
||||
throw new WebAuthnException('invalid ctsProfileMatch: device is not approved as a Google-certified Android device.', WebAuthnException::ANDROID_NOT_TRUSTED);
|
||||
}
|
||||
}
|
||||
|
||||
// 15. If validation is successful, obtain a list of acceptable trust anchors
|
||||
$rootValid = is_array($this->_caFiles) ? $attestationObject->validateRootCertificate($this->_caFiles) : null;
|
||||
if ($failIfRootMismatch && is_array($this->_caFiles) && !$rootValid) {
|
||||
throw new WebAuthnException('invalid root certificate', WebAuthnException::CERTIFICATE_NOT_TRUSTED);
|
||||
}
|
||||
|
||||
// 10. Verify that the User Present bit of the flags in authData is set.
|
||||
$userPresent = $attestationObject->getAuthenticatorData()->getUserPresent();
|
||||
if ($requireUserPresent && !$userPresent) {
|
||||
throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
|
||||
}
|
||||
|
||||
// 11. If user verification is required for this registration, verify that the User Verified bit of the flags in authData is set.
|
||||
$userVerified = $attestationObject->getAuthenticatorData()->getUserVerified();
|
||||
if ($requireUserVerification && !$userVerified) {
|
||||
throw new WebAuthnException('user not verified during authentication', WebAuthnException::USER_VERIFICATED);
|
||||
}
|
||||
|
||||
$signCount = $attestationObject->getAuthenticatorData()->getSignCount();
|
||||
if ($signCount > 0) {
|
||||
$this->_signatureCounter = $signCount;
|
||||
}
|
||||
|
||||
// prepare data to store for future logins
|
||||
$data = new \stdClass();
|
||||
$data->rpId = $this->_rpId;
|
||||
$data->attestationFormat = $attestationObject->getAttestationFormatName();
|
||||
$data->credentialId = $attestationObject->getAuthenticatorData()->getCredentialId();
|
||||
$data->credentialPublicKey = $attestationObject->getAuthenticatorData()->getPublicKeyPem();
|
||||
$data->certificateChain = $attestationObject->getCertificateChain();
|
||||
$data->certificate = $attestationObject->getCertificatePem();
|
||||
$data->certificateIssuer = $attestationObject->getCertificateIssuer();
|
||||
$data->certificateSubject = $attestationObject->getCertificateSubject();
|
||||
$data->signatureCounter = $this->_signatureCounter;
|
||||
$data->AAGUID = $attestationObject->getAuthenticatorData()->getAAGUID();
|
||||
$data->rootValid = $rootValid;
|
||||
$data->userPresent = $userPresent;
|
||||
$data->userVerified = $userVerified;
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* process a get request
|
||||
* @param string $clientDataJSON binary from browser
|
||||
* @param string $authenticatorData binary from browser
|
||||
* @param string $signature binary from browser
|
||||
* @param string $credentialPublicKey string PEM-formated public key from used credentialId
|
||||
* @param string|ByteBuffer $challenge binary from used challange
|
||||
* @param int $prevSignatureCnt signature count value of the last login
|
||||
* @param bool $requireUserVerification true, if the device must verify user (e.g. by biometric data or pin)
|
||||
* @param bool $requireUserPresent true, if the device must check user presence (e.g. by pressing a button)
|
||||
* @return boolean true if get is successful
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function processGet($clientDataJSON, $authenticatorData, $signature, $credentialPublicKey, $challenge, $prevSignatureCnt=null, $requireUserVerification=false, $requireUserPresent=true) {
|
||||
$authenticatorObj = new Attestation\AuthenticatorData($authenticatorData);
|
||||
$clientDataHash = \hash('sha256', $clientDataJSON, true);
|
||||
$clientData = \json_decode($clientDataJSON);
|
||||
$challenge = $challenge instanceof ByteBuffer ? $challenge : new ByteBuffer($challenge);
|
||||
|
||||
// https://www.w3.org/TR/webauthn/#verifying-assertion
|
||||
|
||||
// 1. If the allowCredentials option was given when this authentication ceremony was initiated,
|
||||
// verify that credential.id identifies one of the public key credentials that were listed in allowCredentials.
|
||||
// -> TO BE VERIFIED BY IMPLEMENTATION
|
||||
|
||||
// 2. If credential.response.userHandle is present, verify that the user identified
|
||||
// by this value is the owner of the public key credential identified by credential.id.
|
||||
// -> TO BE VERIFIED BY IMPLEMENTATION
|
||||
|
||||
// 3. Using credential’s id attribute (or the corresponding rawId, if base64url encoding is
|
||||
// inappropriate for your use case), look up the corresponding credential public key.
|
||||
// -> TO BE LOOKED UP BY IMPLEMENTATION
|
||||
|
||||
// 5. Let JSONtext be the result of running UTF-8 decode on the value of cData.
|
||||
if (!\is_object($clientData)) {
|
||||
throw new WebAuthnException('invalid client data', WebAuthnException::INVALID_DATA);
|
||||
}
|
||||
|
||||
// 7. Verify that the value of C.type is the string webauthn.get.
|
||||
if (!\property_exists($clientData, 'type') || $clientData->type !== 'webauthn.get') {
|
||||
throw new WebAuthnException('invalid type', WebAuthnException::INVALID_TYPE);
|
||||
}
|
||||
|
||||
// 8. Verify that the value of C.challenge matches the challenge that was sent to the
|
||||
// authenticator in the PublicKeyCredentialRequestOptions passed to the get() call.
|
||||
if (!\property_exists($clientData, 'challenge') || ByteBuffer::fromBase64Url($clientData->challenge)->getBinaryString() !== $challenge->getBinaryString()) {
|
||||
throw new WebAuthnException('invalid challenge', WebAuthnException::INVALID_CHALLENGE);
|
||||
}
|
||||
|
||||
// 9. Verify that the value of C.origin matches the Relying Party's origin.
|
||||
if (!\property_exists($clientData, 'origin') || !$this->_checkOrigin($clientData->origin)) {
|
||||
throw new WebAuthnException('invalid origin', WebAuthnException::INVALID_ORIGIN);
|
||||
}
|
||||
|
||||
// 11. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID expected by the Relying Party.
|
||||
if ($authenticatorObj->getRpIdHash() !== $this->_rpIdHash) {
|
||||
throw new WebAuthnException('invalid rpId hash', WebAuthnException::INVALID_RELYING_PARTY);
|
||||
}
|
||||
|
||||
// 12. Verify that the User Present bit of the flags in authData is set
|
||||
if ($requireUserPresent && !$authenticatorObj->getUserPresent()) {
|
||||
throw new WebAuthnException('user not present during authentication', WebAuthnException::USER_PRESENT);
|
||||
}
|
||||
|
||||
// 13. If user verification is required for this assertion, verify that the User Verified bit of the flags in authData is set.
|
||||
if ($requireUserVerification && !$authenticatorObj->getUserVerified()) {
|
||||
throw new WebAuthnException('user not verificated during authentication', WebAuthnException::USER_VERIFICATED);
|
||||
}
|
||||
|
||||
// 14. Verify the values of the client extension outputs
|
||||
// (extensions not implemented)
|
||||
|
||||
// 16. Using the credential public key looked up in step 3, verify that sig is a valid signature
|
||||
// over the binary concatenation of authData and hash.
|
||||
$dataToVerify = '';
|
||||
$dataToVerify .= $authenticatorData;
|
||||
$dataToVerify .= $clientDataHash;
|
||||
|
||||
if (!$this->_verifySignature($dataToVerify, $signature, $credentialPublicKey)) {
|
||||
throw new WebAuthnException('invalid signature', WebAuthnException::INVALID_SIGNATURE);
|
||||
}
|
||||
|
||||
$signatureCounter = $authenticatorObj->getSignCount();
|
||||
if ($signatureCounter !== 0) {
|
||||
$this->_signatureCounter = $signatureCounter;
|
||||
}
|
||||
|
||||
// 17. If either of the signature counter value authData.signCount or
|
||||
// previous signature count is nonzero, and if authData.signCount
|
||||
// less than or equal to previous signature count, it's a signal
|
||||
// that the authenticator may be cloned
|
||||
if ($prevSignatureCnt !== null) {
|
||||
if ($signatureCounter !== 0 || $prevSignatureCnt !== 0) {
|
||||
if ($prevSignatureCnt >= $signatureCounter) {
|
||||
throw new WebAuthnException('signature counter not valid', WebAuthnException::SIGNATURE_COUNTER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads root certificates from FIDO Alliance Metadata Service (MDS) to a specific folder
|
||||
* https://fidoalliance.org/metadata/
|
||||
* @param string $certFolder Folder path to save the certificates in PEM format.
|
||||
* @param bool $deleteCerts delete certificates in the target folder before adding the new ones.
|
||||
* @return int number of cetificates
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
public function queryFidoMetaDataService($certFolder, $deleteCerts=true) {
|
||||
$url = 'https://mds.fidoalliance.org/';
|
||||
$raw = null;
|
||||
if (\function_exists('curl_init')) {
|
||||
$ch = \curl_init($url);
|
||||
\curl_setopt($ch, CURLOPT_HEADER, false);
|
||||
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
\curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
||||
\curl_setopt($ch, CURLOPT_USERAGENT, 'github.com/lbuchs/WebAuthn - A simple PHP WebAuthn server library');
|
||||
$raw = \curl_exec($ch);
|
||||
\curl_close($ch);
|
||||
} else {
|
||||
$raw = \file_get_contents($url);
|
||||
}
|
||||
|
||||
$certFolder = \rtrim(\realpath($certFolder), '\\/');
|
||||
if (!is_dir($certFolder)) {
|
||||
throw new WebAuthnException('Invalid folder path for query FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
if (!\is_string($raw)) {
|
||||
throw new WebAuthnException('Unable to query FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
$jwt = \explode('.', $raw);
|
||||
if (\count($jwt) !== 3) {
|
||||
throw new WebAuthnException('Invalid JWT from FIDO Alliance Metadata Service');
|
||||
}
|
||||
|
||||
if ($deleteCerts) {
|
||||
foreach (\scandir($certFolder) as $ca) {
|
||||
if (\substr($ca, -4) === '.pem') {
|
||||
if (\unlink($certFolder . DIRECTORY_SEPARATOR . $ca) === false) {
|
||||
throw new WebAuthnException('Cannot delete certs in folder for FIDO Alliance Metadata Service');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
list($header, $payload, $hash) = $jwt;
|
||||
$payload = Binary\ByteBuffer::fromBase64Url($payload)->getJson();
|
||||
|
||||
$count = 0;
|
||||
if (\is_object($payload) && \property_exists($payload, 'entries') && \is_array($payload->entries)) {
|
||||
foreach ($payload->entries as $entry) {
|
||||
if (\is_object($entry) && \property_exists($entry, 'metadataStatement') && \is_object($entry->metadataStatement)) {
|
||||
$description = $entry->metadataStatement->description ?? null;
|
||||
$attestationRootCertificates = $entry->metadataStatement->attestationRootCertificates ?? null;
|
||||
|
||||
if ($description && $attestationRootCertificates) {
|
||||
|
||||
// create filename
|
||||
$certFilename = \preg_replace('/[^a-z0-9]/i', '_', $description);
|
||||
$certFilename = \trim(\preg_replace('/\_{2,}/i', '_', $certFilename),'_') . '.pem';
|
||||
$certFilename = \strtolower($certFilename);
|
||||
|
||||
// add certificate
|
||||
$certContent = $description . "\n";
|
||||
$certContent .= \str_repeat('-', \mb_strlen($description)) . "\n";
|
||||
|
||||
foreach ($attestationRootCertificates as $attestationRootCertificate) {
|
||||
$attestationRootCertificate = \str_replace(["\n", "\r", ' '], '', \trim($attestationRootCertificate));
|
||||
$count++;
|
||||
$certContent .= "\n-----BEGIN CERTIFICATE-----\n";
|
||||
$certContent .= \chunk_split($attestationRootCertificate, 64, "\n");
|
||||
$certContent .= "-----END CERTIFICATE-----\n";
|
||||
}
|
||||
|
||||
if (\file_put_contents($certFolder . DIRECTORY_SEPARATOR . $certFilename, $certContent) === false) {
|
||||
throw new WebAuthnException('unable to save certificate from FIDO Alliance Metadata Service');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
// -----------------------------------------------
|
||||
// PRIVATE
|
||||
// -----------------------------------------------
|
||||
|
||||
/**
|
||||
* checks if the origin matchs the RP ID
|
||||
* @param string $origin
|
||||
* @return boolean
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _checkOrigin($origin) {
|
||||
// https://www.w3.org/TR/webauthn/#rp-id
|
||||
|
||||
// The origin's scheme must be https
|
||||
if ($this->_rpId !== 'localhost' && \parse_url($origin, PHP_URL_SCHEME) !== 'https') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// extract host from origin
|
||||
$host = \parse_url($origin, PHP_URL_HOST);
|
||||
$host = \trim($host, '.');
|
||||
|
||||
// The RP ID must be equal to the origin's effective domain, or a registrable
|
||||
// domain suffix of the origin's effective domain.
|
||||
return \preg_match('/' . \preg_quote($this->_rpId) . '$/i', $host) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* generates a new challange
|
||||
* @param int $length
|
||||
* @return string
|
||||
* @throws WebAuthnException
|
||||
*/
|
||||
private function _createChallenge($length = 32) {
|
||||
if (!$this->_challenge) {
|
||||
$this->_challenge = ByteBuffer::randomBuffer($length);
|
||||
}
|
||||
return $this->_challenge;
|
||||
}
|
||||
|
||||
/**
|
||||
* check if the signature is valid.
|
||||
* @param string $dataToVerify
|
||||
* @param string $signature
|
||||
* @param string $credentialPublicKey PEM format
|
||||
* @return bool
|
||||
*/
|
||||
private function _verifySignature($dataToVerify, $signature, $credentialPublicKey) {
|
||||
|
||||
// Use Sodium to verify EdDSA 25519 as its not yet supported by openssl
|
||||
if (\function_exists('sodium_crypto_sign_verify_detached') && !\in_array('ed25519', \openssl_get_curve_names(), true)) {
|
||||
$pkParts = [];
|
||||
if (\preg_match('/BEGIN PUBLIC KEY\-+(?:\s|\n|\r)+([^\-]+)(?:\s|\n|\r)*\-+END PUBLIC KEY/i', $credentialPublicKey, $pkParts)) {
|
||||
$rawPk = \base64_decode($pkParts[1]);
|
||||
|
||||
// 30 = der sequence
|
||||
// 2a = length 42 byte
|
||||
// 30 = der sequence
|
||||
// 05 = lenght 5 byte
|
||||
// 06 = der OID
|
||||
// 03 = OID length 3 byte
|
||||
// 2b 65 70 = OID 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
|
||||
// 03 = der bit string
|
||||
// 21 = length 33 byte
|
||||
// 00 = null padding
|
||||
// [...] = 32 byte x-curve
|
||||
$okpPrefix = "\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00";
|
||||
|
||||
if ($rawPk && \strlen($rawPk) === 44 && \substr($rawPk,0, \strlen($okpPrefix)) === $okpPrefix) {
|
||||
$publicKeyXCurve = \substr($rawPk, \strlen($okpPrefix));
|
||||
|
||||
return \sodium_crypto_sign_verify_detached($signature, $dataToVerify, $publicKeyXCurve);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// verify with openSSL
|
||||
$publicKey = \openssl_pkey_get_public($credentialPublicKey);
|
||||
if ($publicKey === false) {
|
||||
throw new WebAuthnException('public key invalid', WebAuthnException::INVALID_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
return \openssl_verify($dataToVerify, $signature, $publicKey, OPENSSL_ALGO_SHA256) === 1;
|
||||
}
|
||||
}
|
||||
28
app-code/api/login/WebAuthnException.php
Normal file
28
app-code/api/login/WebAuthnException.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
namespace lbuchs\WebAuthn;
|
||||
|
||||
/**
|
||||
* @author Lukas Buchs
|
||||
* @license https://github.com/lbuchs/WebAuthn/blob/master/LICENSE MIT
|
||||
*/
|
||||
class WebAuthnException extends \Exception {
|
||||
const INVALID_DATA = 1;
|
||||
const INVALID_TYPE = 2;
|
||||
const INVALID_CHALLENGE = 3;
|
||||
const INVALID_ORIGIN = 4;
|
||||
const INVALID_RELYING_PARTY = 5;
|
||||
const INVALID_SIGNATURE = 6;
|
||||
const INVALID_PUBLIC_KEY = 7;
|
||||
const CERTIFICATE_NOT_TRUSTED = 8;
|
||||
const USER_PRESENT = 9;
|
||||
const USER_VERIFICATED = 10;
|
||||
const SIGNATURE_COUNTER = 11;
|
||||
const CRYPTO_STRONG = 13;
|
||||
const BYTEBUFFER = 14;
|
||||
const CBOR = 15;
|
||||
const ANDROID_NOT_TRUSTED = 16;
|
||||
|
||||
public function __construct($message = "", $code = 0, $previous = null) {
|
||||
parent::__construct($message, $code, $previous);
|
||||
}
|
||||
}
|
||||
36
app-code/api/login/check_mfa.php
Normal file
36
app-code/api/login/check_mfa.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
session_start();
|
||||
header('Content-Type: application/json');
|
||||
$send_to=$_SESSION["end_url"];
|
||||
|
||||
include "../../config/config.php";
|
||||
include "../utils/generate_pin.php";
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
|
||||
|
||||
$username=$_SESSION["username"];
|
||||
$sql="SELECT 2fa FROM users WHERE username = ?";
|
||||
$stmt = mysqli_prepare($conn, $sql);
|
||||
mysqli_stmt_bind_param($stmt, 's', $username);
|
||||
mysqli_stmt_execute($stmt);
|
||||
mysqli_stmt_store_result($stmt);
|
||||
$twofa_secret="";
|
||||
mysqli_stmt_bind_result($stmt, $twofa_secret);
|
||||
mysqli_stmt_fetch($stmt);
|
||||
mysqli_stmt_close($stmt);
|
||||
$twofa_pin=$_POST["twofa_pin"];
|
||||
|
||||
if(generateTOTP($twofa_secret)===$twofa_pin){
|
||||
$_SESSION["mfa_authenticated"]=1;
|
||||
$data = [
|
||||
'status' => 'success'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}else{
|
||||
$data = [
|
||||
'status' => 'failure'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}
|
||||
|
||||
|
||||
?>
|
||||
194
app-code/api/login/check_passkey.php
Normal file
194
app-code/api/login/check_passkey.php
Normal file
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
header('Content-Type: application/json');
|
||||
require_once 'WebAuthn.php';
|
||||
include "../../config/config.php";
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD,$DB_DATABASE);
|
||||
if ($conn->connect_error) {
|
||||
$success=0;
|
||||
die("Connection failed: " . $conn->connect_error);
|
||||
}
|
||||
|
||||
try {
|
||||
session_start();
|
||||
|
||||
// read get argument and post body
|
||||
$fn = filter_input(INPUT_GET, 'fn');
|
||||
$requireResidentKey = !!filter_input(INPUT_GET, 'requireResidentKey');
|
||||
$userVerification = filter_input(INPUT_GET, 'userVerification', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
|
||||
$userId = filter_input(INPUT_GET, 'userId', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
$userName = filter_input(INPUT_GET, 'userName', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
$userDisplayName = filter_input(INPUT_GET, 'userDisplayName', FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
|
||||
$userId = preg_replace('/[^0-9a-f]/i', '', $userId);
|
||||
$userName = preg_replace('/[^0-9a-z]/i', '', $userName);
|
||||
$userDisplayName = preg_replace('/[^0-9a-z öüäéèàÖÜÄÉÈÀÂÊÎÔÛâêîôû]/i', '', $userDisplayName);
|
||||
|
||||
$post = trim(file_get_contents('php://input'));
|
||||
if ($post) {
|
||||
$post = json_decode($post, null, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
if ($fn !== 'getStoredDataHtml') {
|
||||
|
||||
// Formats
|
||||
$formats = [];
|
||||
//if (filter_input(INPUT_GET, 'fmt_android-key')) {
|
||||
$formats[] = 'android-key';
|
||||
//}
|
||||
///if (filter_input(INPUT_GET, 'fmt_android-safetynet')) {
|
||||
$formats[] = 'android-safetynet';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_apple')) {
|
||||
$formats[] = 'apple';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_fido-u2f')) {
|
||||
$formats[] = 'fido-u2f';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_none')) {
|
||||
$formats[] = 'none';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_packed')) {
|
||||
$formats[] = 'packed';
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'fmt_tpm')) {
|
||||
$formats[] = 'tpm';
|
||||
//}
|
||||
|
||||
$rpId=$_SERVER['SERVER_NAME'];
|
||||
|
||||
$typeUsb = true;
|
||||
$typeNfc = true;
|
||||
$typeBle = true;
|
||||
$typeInt = true;
|
||||
$typeHyb = true;
|
||||
|
||||
// cross-platform: true, if type internal is not allowed
|
||||
// false, if only internal is allowed
|
||||
// null, if internal and cross-platform is allowed
|
||||
$crossPlatformAttachment = null;
|
||||
if (($typeUsb || $typeNfc || $typeBle || $typeHyb) && !$typeInt) {
|
||||
$crossPlatformAttachment = true;
|
||||
|
||||
} else if (!$typeUsb && !$typeNfc && !$typeBle && !$typeHyb && $typeInt) {
|
||||
$crossPlatformAttachment = false;
|
||||
}
|
||||
|
||||
|
||||
// new Instance of the server library.
|
||||
// make sure that $rpId is the domain name.
|
||||
$WebAuthn = new lbuchs\WebAuthn\WebAuthn('WebAuthn Library', $rpId, $formats);
|
||||
|
||||
// add root certificates to validate new registrations
|
||||
//if (filter_input(INPUT_GET, 'solo')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/solo.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'apple')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/apple.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'yubico')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/yubico.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'hypersecu')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/hypersecu.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'google')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/globalSign.pem');
|
||||
$WebAuthn->addRootCertificates('rootCertificates/googleHardware.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'microsoft')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/microsoftTpmCollection.pem');
|
||||
//}
|
||||
//if (filter_input(INPUT_GET, 'mds')) {
|
||||
$WebAuthn->addRootCertificates('rootCertificates/mds');
|
||||
//}
|
||||
|
||||
}
|
||||
|
||||
// Handle different functions
|
||||
if ($fn === 'getCreateArgs') {
|
||||
// Get create arguments
|
||||
$createArgs = $WebAuthn->getCreateArgs(\hex2bin($userId), $userName, $userDisplayName, 60*4, $requireResidentKey, $userVerification);
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($createArgs));
|
||||
|
||||
// Save challenge to session or somewhere else if needed
|
||||
} else if ($fn === 'getGetArgs') {
|
||||
$ids = [];
|
||||
|
||||
//get registrations form user table
|
||||
//put credential id into session where userid = $userId
|
||||
|
||||
$stmt = $conn->prepare("SELECT credential_id FROM users WHERE username = ?");
|
||||
$stmt->bind_param("s", $userName);
|
||||
$stmt->execute();
|
||||
$registration = $stmt->get_result();
|
||||
$row = $registration->fetch_assoc();
|
||||
|
||||
|
||||
if ($registration->num_rows <= 0) {
|
||||
throw new Exception('User does not exist');
|
||||
}
|
||||
|
||||
$_SESSION["registrations"]["credentialId"]=$row["credential_id"];
|
||||
|
||||
$ids[]=$row["credential_id"];
|
||||
$_SESSION["registrations"]["userId"]=$userId;
|
||||
|
||||
$getArgs = $WebAuthn->getGetArgs($ids, 60*4, $typeUsb, $typeNfc, $typeBle, $typeHyb, $typeInt, $userVerification);
|
||||
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($getArgs));
|
||||
|
||||
// save challange to session. you have to deliver it to processGet later.
|
||||
$_SESSION['challenge'] = $WebAuthn->getChallenge();
|
||||
|
||||
}else if ($fn === 'processGet') {
|
||||
// Process get
|
||||
// Retrieve registration data from the database based on credential ID
|
||||
$id = base64_decode($post->id);
|
||||
$stmt = $conn->prepare("SELECT * FROM users WHERE credential_id = ?");
|
||||
$stmt->bind_param("s", $_SESSION["registrations"]["credentialId"]);
|
||||
$stmt->execute();
|
||||
$registration = $stmt->get_result();
|
||||
$row = $registration->fetch_assoc();
|
||||
|
||||
if (!$registration) {
|
||||
throw new Exception('Public Key for credential ID not found!');
|
||||
}
|
||||
|
||||
$clientDataJSON = base64_decode($post->clientDataJSON);
|
||||
$authenticatorData = base64_decode($post->authenticatorData);
|
||||
$signature = base64_decode($post->signature);
|
||||
$userHandle = base64_decode($post->userHandle);
|
||||
$challenge = $_SESSION['challenge'] ?? '';
|
||||
$credentialPublicKey = $row['public_key'];
|
||||
|
||||
// Process the get request
|
||||
$WebAuthn->processGet($clientDataJSON, $authenticatorData, $signature, $credentialPublicKey, $challenge, null, $userVerification === 'required');
|
||||
|
||||
// Authentication success
|
||||
//set sessionso user is authenticated
|
||||
$_SESSION["mfa_authenticated"]=1;
|
||||
$_SESSION["pw_authenticated"]=1;
|
||||
$_SESSION["passkey_authenticated"]=1;
|
||||
$return = new stdClass();
|
||||
$return->success = true;
|
||||
|
||||
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($return));
|
||||
}
|
||||
|
||||
} catch (Throwable $ex) {
|
||||
$return = new stdClass();
|
||||
$return->success = false;
|
||||
$return->msg = $ex->getMessage();
|
||||
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($return));
|
||||
}
|
||||
|
||||
|
||||
|
||||
?>
|
||||
@@ -2,19 +2,80 @@
|
||||
session_start();
|
||||
header('Content-Type: application/json');
|
||||
$send_to=$_SESSION["end_url"];
|
||||
//if allready authenticated
|
||||
if(($_SESSION["auth_passkey"]==="not_reauired" or $_SESSION["auth_passkey"]==="authenticated") and ($_SESSION["auth_password"]==="not_reauired" or $_SESSION["auth_password"]==="authenticated") and ($_SESSION["auth_2fa"]==="not_reauired" or $_SESSION["auth_2fa"]==="authenticated")){
|
||||
//user is fully authenticated, send him to the desired page
|
||||
$data = [
|
||||
'login' => true,
|
||||
'message' => 'fully_logged_in',
|
||||
'redirect' => $send_to
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}else{
|
||||
|
||||
include "../../config/config.php";
|
||||
$conn = new mysqli($DB_SERVERNAME, $DB_USERNAME, $DB_PASSWORD, $DB_DATABASE);
|
||||
|
||||
if($_SESSION["needs_auth"]===false && $_SESSION["pw_required"]==1 && $_SESSION["pw_authenticated"]==0){
|
||||
//check for pw
|
||||
$data=[
|
||||
'message' => 'auth_pw',
|
||||
'redirect' => '/login/pw.php'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}
|
||||
else if($_SESSION["needs_auth"]===false && $_SESSION["mfa_required"]==1 && $_SESSION["mfa_authenticated"]==0){
|
||||
$data=[
|
||||
'message' => 'auth_mfa',
|
||||
'redirect' => '/login/mfa.php'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
|
||||
//check for mfa
|
||||
}
|
||||
else if($_SESSION["needs_auth"]===false && $_SESSION["passkey_required"]==1 && $_SESSION["passkey_authenticated"]==0){
|
||||
//check for passkey
|
||||
$data=[
|
||||
'message' => 'auth_passkey',
|
||||
'redirect' => '/login/passkey.php'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}else if ($_SESSION["needs_auth"]===false && $_SESSION["mfa_authenticated"]==1 && $_SESSION["pw_authenticated"]==1 && $_SESSION["passkey_authenticated"]){
|
||||
//fully authenticated
|
||||
$_SESSION["logged_in"]=true;
|
||||
$data=[
|
||||
'message' => 'done',
|
||||
'redirect' => $send_to
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}
|
||||
else{
|
||||
//we have to send the user around :)
|
||||
//load his auth methods. then send the first one. if he auths there he will be send back here and we can send him to the next auth method
|
||||
$username=$_SESSION["username"];
|
||||
$_SESSION["needs_auth"]=false;
|
||||
$_SESSION["logged_in"]=false;
|
||||
$sql="SELECT auth_method_required_pw, auth_method_required_2fa, auth_method_required_passkey FROM users WHERE username = ?";
|
||||
$stmt = mysqli_prepare($conn, $sql);
|
||||
mysqli_stmt_bind_param($stmt, 's', $username);
|
||||
mysqli_stmt_execute($stmt);
|
||||
mysqli_stmt_store_result($stmt);
|
||||
$pw=0;
|
||||
$mfa=0;
|
||||
$passkey=0;
|
||||
if(mysqli_stmt_num_rows($stmt) == 1){
|
||||
mysqli_stmt_bind_result($stmt, $pw,$mfa,$passkey);
|
||||
mysqli_stmt_fetch($stmt);
|
||||
$_SESSION["pw_required"] = $pw;
|
||||
$_SESSION["pw_authenticated"] = ($pw == 0) ? 1 : 0; // If $pw is 0, set pw_authenticated to 1
|
||||
$_SESSION["mfa_required"] = $mfa;
|
||||
$_SESSION["mfa_authenticated"] = ($mfa == 0) ? 1 : 0;
|
||||
$_SESSION["passkey_required"] = $passkey;
|
||||
$_SESSION["passkey_authenticated"] = ($passkey == 0) ? 1 : 0;
|
||||
$data=[
|
||||
'message' => 'prepared_start_auth',
|
||||
'redirect' => '/login/'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}else{
|
||||
$data = [
|
||||
'message' => 'this user does not exist',
|
||||
'redirect' => '/?user_not_found'
|
||||
];
|
||||
echo(json_encode($data));
|
||||
}
|
||||
mysqli_stmt_close($stmt);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
session_start();
|
||||
$_SESSION["needs_auth"]=true;
|
||||
$_SESSION["username"]=preg_replace("/[^a-z0-9_]/","",$_POST["username"]);
|
||||
?>
|
||||
|
||||
37
app-code/api/utils/create_key.php
Normal file
37
app-code/api/utils/create_key.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
function generateBase32Secret($length = 16) {
|
||||
// Generate a random binary string (length in bytes)
|
||||
$randomBytes = random_bytes($length); // Length in bytes (16 bytes = 128 bits)
|
||||
|
||||
// Encode the binary string to Base32
|
||||
$base32Secret = base32_encode($randomBytes);
|
||||
|
||||
return $base32Secret;
|
||||
}
|
||||
|
||||
// Function to encode to Base32
|
||||
function base32_encode($data) {
|
||||
$base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; // Base32 alphabet
|
||||
$encoded = '';
|
||||
$buffer = 0;
|
||||
$bitsLeft = 0;
|
||||
|
||||
foreach (str_split($data) as $char) {
|
||||
$buffer = ($buffer << 8) | ord($char);
|
||||
$bitsLeft += 8;
|
||||
|
||||
while ($bitsLeft >= 5) {
|
||||
$bitsLeft -= 5;
|
||||
$encoded .= $base32Chars[($buffer >> $bitsLeft) & 31];
|
||||
$buffer &= (1 << $bitsLeft) - 1;
|
||||
}
|
||||
}
|
||||
|
||||
if ($bitsLeft > 0) {
|
||||
$encoded .= $base32Chars[($buffer << (5 - $bitsLeft)) & 31];
|
||||
}
|
||||
|
||||
return $encoded;
|
||||
}
|
||||
|
||||
?>
|
||||
53
app-code/api/utils/generate_pin.php
Normal file
53
app-code/api/utils/generate_pin.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
function base32_decode($base32) {
|
||||
$base32Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
$base32 = strtoupper($base32);
|
||||
$buffer = 0;
|
||||
$bitsLeft = 0;
|
||||
$decoded = '';
|
||||
|
||||
foreach (str_split($base32) as $char) {
|
||||
$value = strpos($base32Chars, $char);
|
||||
if ($value === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$buffer = ($buffer << 5) | $value;
|
||||
$bitsLeft += 5;
|
||||
|
||||
if ($bitsLeft >= 8) {
|
||||
$bitsLeft -= 8;
|
||||
$decoded .= chr(($buffer >> $bitsLeft) & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
function generateTOTP($secret) {
|
||||
// Convert the secret from Base32 to binary
|
||||
$secretBinary = base32_decode($secret);
|
||||
|
||||
// Get the current time in seconds
|
||||
$time = floor(time() / 30); // 30-second time step
|
||||
|
||||
// Convert the time to a 8-byte string
|
||||
$timeBytes = pack('N*', 0) . pack('N*', $time); // Pack time as an 8-byte string
|
||||
|
||||
// Hash the time with the secret key using HMAC-SHA1
|
||||
$hash = hash_hmac('sha1', $timeBytes, $secretBinary, true);
|
||||
|
||||
// Extract a 4-byte dynamic offset from the hash
|
||||
$offset = ord($hash[19]) & 0x0F;
|
||||
|
||||
// Calculate the 6-digit code by truncating the hash
|
||||
$code = unpack('N', substr($hash, $offset, 4))[1] & 0x7FFFFFFF; // Ensure non-negative
|
||||
|
||||
// Modulo 10^6 to get the final 6-digit code
|
||||
$otp = $code % 1000000;
|
||||
|
||||
// Pad with leading zeros if necessary
|
||||
return str_pad($otp, 6, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -20,11 +20,16 @@
|
||||
<div class="card shadow">
|
||||
<div class="card-body">
|
||||
<h4 class="card-title text-center mb-4">Jakach Login</h4>
|
||||
<?php
|
||||
if(isset($_GET["user_not_found"])){
|
||||
echo("<div class='alert alert-danger'>Account not found!</div>");
|
||||
}
|
||||
?>
|
||||
<!-- Form -->
|
||||
<form id="usernameForm">
|
||||
<!-- Username Input -->
|
||||
<div class="mb-3">
|
||||
<input type="text" id="username" name="username" class="form-control" placeholder="Benutzername" required>
|
||||
<input type="text" autofocus id="username" name="username" class="form-control" placeholder="Benutzername" required>
|
||||
</div>
|
||||
<!-- Submit Button -->
|
||||
<div class="d-grid gap-2">
|
||||
@@ -40,6 +45,23 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="errorModalLabel">Error</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
Account not found!
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Select the form
|
||||
const usernameForm = document.getElementById('usernameForm');
|
||||
@@ -60,14 +82,15 @@
|
||||
|
||||
try {
|
||||
// Send POST request to the API
|
||||
const response = await fetch('/api/login/set_username.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ username }), // Send username as JSON
|
||||
});
|
||||
|
||||
const response = await fetch('/api/login/set_username.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded', // Form-like data
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
username: username, // Send username as form data
|
||||
}),
|
||||
});
|
||||
// Check if the request was successful
|
||||
if (response.ok) {
|
||||
// Redirect to /login/ upon success
|
||||
@@ -83,7 +106,19 @@
|
||||
alert('An error occurred. Please try again later.');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</script>
|
||||
<?php
|
||||
// Check if the GET parameter "user_not_found" is set
|
||||
if (isset($_GET["user_not_found"])) {
|
||||
echo "
|
||||
<script>
|
||||
// Use JavaScript to trigger the modal to open
|
||||
var errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
|
||||
errorModal.show();
|
||||
</script>
|
||||
";
|
||||
}
|
||||
?>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(255) NOT NULL UNIQUE,
|
||||
public_key TEXT DEFAULT '',
|
||||
credential_id TEXT DEFAULT '',
|
||||
credential_id VARBINARY(64),
|
||||
counter INT DEFAULT 0,
|
||||
2fa VARCHAR(255),
|
||||
email VARCHAR(255),
|
||||
|
||||
6
app-code/login/logout.php
Normal file
6
app-code/login/logout.php
Normal file
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
session_start();
|
||||
session_unset();
|
||||
session_destroy();
|
||||
header("LOCATION:/");
|
||||
?>
|
||||
115
app-code/login/mfa.php
Normal file
115
app-code/login/mfa.php
Normal file
@@ -0,0 +1,115 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-bs-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Jakach Login</title>
|
||||
<?php
|
||||
include "../assets/components.php";
|
||||
session_start();
|
||||
?>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-md-6 col-lg-4">
|
||||
<!-- Card for the form -->
|
||||
<div class="card shadow">
|
||||
<div class="card-body">
|
||||
<h4 class="card-title text-center mb-4">Jakach Login</h4>
|
||||
<!-- Form -->
|
||||
<form id="twofaForm">
|
||||
<!-- password Input -->
|
||||
<div class="mb-3">
|
||||
<input autofocus type="text" id="twofa" name="twofa" class="form-control" placeholder="2FA pin" required>
|
||||
</div>
|
||||
<!-- Submit Button -->
|
||||
<div class="d-grid gap-2">
|
||||
<!-- Login Button -->
|
||||
<button type="submit" class="btn btn-primary btn-lg">Check</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="errorModalLabel">Error</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
Wrong 2fa pin!
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Select the form
|
||||
const passwordForm = document.getElementById('twofaForm');
|
||||
|
||||
// Add submit event listener
|
||||
passwordForm.addEventListener('submit', async (event) => {
|
||||
event.preventDefault(); // Prevent the default form submission behavior
|
||||
|
||||
// Get the username input value
|
||||
const passwordInput = document.getElementById('twofa');
|
||||
const password = passwordInput.value;
|
||||
|
||||
// Check if username is empty (just in case)
|
||||
if (!password) {
|
||||
alert('Please enter a 2fa pin.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
// Send POST request to the API
|
||||
const response = await fetch('/api/login/check_mfa.php', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded', // Form-like data
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
twofa_pin: password, // Send password as form data
|
||||
}),
|
||||
});
|
||||
|
||||
// Check if the request was successful
|
||||
if (response.ok) {
|
||||
// Await response.json() to parse the JSON
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'success') {
|
||||
// Redirect to /login/
|
||||
window.location.href = '/login/';
|
||||
} else {
|
||||
// Show the error modal on failure
|
||||
var errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
|
||||
errorModal.show();
|
||||
// Optionally, display the error message
|
||||
console.error("Error: ", data.message || "Unknown error");
|
||||
}
|
||||
} else {
|
||||
// Handle HTTP errors (non-2xx status codes)
|
||||
const errorData = await response.json();
|
||||
alert(`Error: ${errorData.message || 'Failed to check 2fa pin.'}`);
|
||||
}
|
||||
} catch (error) {
|
||||
// Handle network or unexpected errors
|
||||
console.error('Error:', error);
|
||||
alert('An error occurred. Please try again later.');
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
261
app-code/login/passkey.php
Normal file
261
app-code/login/passkey.php
Normal file
@@ -0,0 +1,261 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-bs-theme="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Jakach Login</title>
|
||||
<?php
|
||||
include "../assets/components.php";
|
||||
session_start();
|
||||
?>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container mt-5">
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-md-6 col-lg-4">
|
||||
<!-- Card for the form -->
|
||||
<div class="card shadow">
|
||||
<div class="card-body">
|
||||
<h4 class="card-title text-center mb-4">Jakach Login</h4>
|
||||
<!-- Form -->
|
||||
<form id="twofaForm">
|
||||
<!-- Submit Button -->
|
||||
<div class="d-grid gap-2">
|
||||
<!-- Login Button -->
|
||||
<button style="align:right" type="button" class="btn btn-primary btn-block" onclick="checkRegistration()">Login with a passkey</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="errorModalLabel">Error</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
Wrong 2fa pin!
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script>
|
||||
//js that handelsour passkey login
|
||||
|
||||
async function checkRegistration() {
|
||||
try {
|
||||
|
||||
if (!window.fetch || !navigator.credentials || !navigator.credentials.create) {
|
||||
throw new Error('Browser not supported.');
|
||||
}
|
||||
|
||||
// get check args
|
||||
let rep = await window.fetch('/api/login/check_passkey.php?fn=getGetArgs' + getGetParams(), {method:'GET',cache:'no-cache'});
|
||||
const getArgs = await rep.json();
|
||||
|
||||
// error handling
|
||||
if (getArgs.success === false) {
|
||||
throw new Error(getArgs.msg);
|
||||
}
|
||||
|
||||
// replace binary base64 data with ArrayBuffer. a other way to do this
|
||||
// is the reviver function of JSON.parse()
|
||||
recursiveBase64StrToArrayBuffer(getArgs);
|
||||
|
||||
// check credentials with hardware
|
||||
const cred = await navigator.credentials.get(getArgs);
|
||||
|
||||
// create object for transmission to server
|
||||
const authenticatorAttestationResponse = {
|
||||
id: cred.rawId ? arrayBufferToBase64(cred.rawId) : null,
|
||||
clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
|
||||
authenticatorData: cred.response.authenticatorData ? arrayBufferToBase64(cred.response.authenticatorData) : null,
|
||||
signature: cred.response.signature ? arrayBufferToBase64(cred.response.signature) : null,
|
||||
userHandle: cred.response.userHandle ? arrayBufferToBase64(cred.response.userHandle) : null
|
||||
};
|
||||
|
||||
// send to server
|
||||
rep = await window.fetch('/api/login/check_passkey.php?fn=processGet' + getGetParams(), {
|
||||
method:'POST',
|
||||
body: JSON.stringify(authenticatorAttestationResponse),
|
||||
cache:'no-cache'
|
||||
});
|
||||
const authenticatorAttestationServerResponse = await rep.json();
|
||||
|
||||
// check server response
|
||||
if (authenticatorAttestationServerResponse.success) {
|
||||
reloadServerPreview();
|
||||
//window.alert(authenticatorAttestationServerResponse.msg || 'login success');
|
||||
//auth success, send to index
|
||||
|
||||
window.location.href = "/login/";
|
||||
|
||||
} else {
|
||||
throw new Error(authenticatorAttestationServerResponse.msg);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
reloadServerPreview();
|
||||
if(err.message=="User does not exist"){
|
||||
//we will display a warning here later on
|
||||
//alert("User does not exist!!! check line 71 of login.html to set warning");
|
||||
var alert_message=document.getElementById("no_passkey");
|
||||
alert_message.style.display="block";
|
||||
}else{
|
||||
window.alert(err.message || 'unknown error occured');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function queryFidoMetaDataService() {
|
||||
window.fetch('/api/login/check_passkey.php?fn=queryFidoMetaDataService' + getGetParams(), {method:'GET',cache:'no-cache'}).then(function(response) {
|
||||
return response.json();
|
||||
|
||||
}).then(function(json) {
|
||||
if (json.success) {
|
||||
window.alert(json.msg);
|
||||
} else {
|
||||
throw new Error(json.msg);
|
||||
}
|
||||
}).catch(function(err) {
|
||||
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);
|
||||
}
|
||||
|
||||
function ascii_to_hex(str) {
|
||||
let hex = '';
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
let ascii = str.charCodeAt(i).toString(16);
|
||||
hex += ('00' + ascii).slice(-2); // Ensure each hex value is 2 characters long
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
/**
|
||||
* Get URL parameter
|
||||
* @returns {String}
|
||||
*/
|
||||
function getGetParams() {
|
||||
let url = '';
|
||||
|
||||
url += '&apple=1';
|
||||
url += '&yubico=1';
|
||||
url += '&solo=1'
|
||||
url += '&hypersecu=1';
|
||||
url += '&google=1';
|
||||
url += 'µsoft=1';
|
||||
url += '&mds=1';
|
||||
|
||||
url += '&requireResidentKey=0';
|
||||
|
||||
url += '&type_usb=1';
|
||||
url += '&type_nfc=1';
|
||||
url += '&type_ble=1';
|
||||
url += '&type_int=1';
|
||||
url += '&type_hybrid=1';
|
||||
|
||||
url += '&fmt_android-key=1';
|
||||
url += '&fmt_android-safetynet=1';
|
||||
url += '&fmt_apple=1';
|
||||
url += '&fmt_fido-u2f=1';
|
||||
url += '&fmt_none=1';
|
||||
url += '&fmt_packed=1';
|
||||
url += '&fmt_tpm=1';
|
||||
|
||||
url += '&rpId=auth.jakach.com';
|
||||
|
||||
url += '&userId=' + encodeURIComponent(ascii_to_hex('<?php echo($_SESSION["username"]);?>'));
|
||||
url += '&userName=' + encodeURIComponent('<?php echo($_SESSION["username"]);?>');
|
||||
url += '&userDisplayName=' + encodeURIComponent('<?php echo($_SESSION["username"]);?>');
|
||||
|
||||
url += '&userVerification=discouraged';
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
function reloadServerPreview() {
|
||||
}
|
||||
|
||||
function setAttestation(attestation) {
|
||||
let inputEls = document.getElementsByTagName('input');
|
||||
for (const inputEl of inputEls) {
|
||||
if (inputEl.id && inputEl.id.match(/^(fmt|cert)\_/)) {
|
||||
inputEl.disabled = !attestation;
|
||||
}
|
||||
if (inputEl.id && inputEl.id.match(/^fmt\_/)) {
|
||||
inputEl.checked = attestation ? inputEl.id !== 'fmt_none' : inputEl.id === 'fmt_none';
|
||||
}
|
||||
if (inputEl.id && inputEl.id.match(/^cert\_/)) {
|
||||
inputEl.checked = attestation ? inputEl.id === 'cert_mds' : false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* force https on load
|
||||
* @returns {undefined}
|
||||
*/
|
||||
window.onload = function() {
|
||||
if (location.protocol !== 'https:' && location.host !== 'localhost') {
|
||||
location.href = location.href.replace('http', 'https');
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -27,6 +27,11 @@
|
||||
<div class="d-grid gap-2">
|
||||
<!-- Login Button -->
|
||||
<button type="submit" class="btn btn-primary btn-lg">Check</button>
|
||||
<?php
|
||||
if($_SESSION["passkey_required"]==1){
|
||||
echo('<a class="btn btn-primary btn-lg" href="/login/passkey.php">Use passkey instead</a>');
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -66,7 +71,7 @@
|
||||
|
||||
// Check if username is empty (just in case)
|
||||
if (!password) {
|
||||
alert('Please enter a username.');
|
||||
alert('Please enter a password.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -20,8 +20,12 @@ COPY ./app-code /var/www/html
|
||||
# Install Composer
|
||||
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
|
||||
|
||||
RUN mkdir -p /var/www/vendor
|
||||
RUN chown -R www-data:www-data /var/www/vendor
|
||||
# Install WebAuthn library using Composer
|
||||
RUN composer require web-auth/webauthn-lib
|
||||
RUN composer require web-auth/webauthn-lib --working-dir=/var/www/vendor
|
||||
RUN composer require web-auth/webauthn-framework --working-dir=/var/www/vendor
|
||||
|
||||
|
||||
# Create necessary directories with appropriate permissions
|
||||
RUN mkdir -p /var/www/html/install/ \
|
||||
|
||||
Reference in New Issue
Block a user