Files
itflow/functions/passkey.php

470 lines
23 KiB
PHP

<?php
/*
* ITFlow - signing in with a passkey (database 4.2.2, user_passkeys).
*
* Agents add passkeys in Your account > Security, client portal contacts in the portal's Your
* account - each taking their password, as adding a way in should. A passkey then signs them in
* on its own, from Sign in with a passkey (or the email box's autofill) on the sign-in page, and
* counts as two-step sign-in: it is a device they have, unlocked with their PIN, fingerprint or
* face (user verification is required, every time).
*
* The sign-in itself (login_passkey.php): the browser signs a challenge kept in the session, the
* signature is checked against the passkey's public key here (report-uri/passkeys-php, libs/webauthn),
* and login.php then signs them in through its usual path, as it does after a two-step code.
*
* The vault: an agent's copy of the vault key is sealed by their password, which a passkey sign-in
* doesn't have. A passkey that supports the PRF extension gives the same secret every time it is
* used here, and a copy of the vault key sealed by that is kept with it (passkey_vault, AES-256-GCM
* under HKDF-SHA256 of the secret) - so signing in with it opens the vault too. One that doesn't
* leaves the vault locked; the agent types their password once to open it (vaultUnlock()).
*
* Passkeys are made for this install's address (config_base_url) - one made for another address
* doesn't work here, and moving ITFlow to a new address means adding them again.
*/
require_once __DIR__ . '/../libs/webauthn/src/WebAuthn.php';
const PASSKEY_CHALLENGE_SECONDS = 300;
const PASSKEY_VAULT_FORMAT = 'pk1:';
const PASSKEY_PER_USER = 20;
const PASSKEY_NAME_MAX = 60;
/*
* Whether the database has passkeys yet (4.2.2), and whether they can be used to sign in - Admin >
* Settings > Security. Read here rather than with every page's settings, so pages still open before
* the update that adds them.
*/
function passkeySettings() {
global $mysqli;
static $settings = null;
if ($settings === null) {
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM settings WHERE company_id = 1")) ?: [];
$settings = ['ready' => array_key_exists('config_login_passkeys', $row), 'on' => intval($row['config_login_passkeys'] ?? 0) === 1];
}
return $settings;
}
function passkeysReady() {
return passkeySettings()['ready'];
}
function passkeysOn() {
return passkeySettings()['on'];
}
function passkeyB64url($binary) {
return rtrim(strtr(base64_encode((string) $binary), '+/', '-_'), '=');
}
/** Bytes from base64url - false when it isn't. */
function passkeyFromB64url($text) {
$text = (string) $text;
if ($text === '' || !preg_match('/^[A-Za-z0-9_-]+$/', $text)) {
return false;
}
return base64_decode(strtr($text, '-_', '+/') . str_repeat('=', (4 - strlen($text) % 4) % 4), true);
}
/**
* Who the passkeys are for - this install's address: the name the RP ID is (its host), the origins
* a browser may sign from (https, or http on localhost, the only place a browser allows it), and
* the address to name when someone is somewhere else.
*/
function passkeyRp() {
global $config_base_url, $config_app_name;
$base = preg_replace('#^https?://#i', '', trim((string) $config_base_url));
$parts = parse_url('https://' . $base);
$host = strtolower((string) ($parts['host'] ?? ''));
$port = isset($parts['port']) ? ':' . intval($parts['port']) : '';
$origins = ["https://$host$port"];
if ($host === 'localhost') {
$origins[] = "http://$host$port";
}
$name = trim((string) ($config_app_name ?? '')) !== '' ? (string) $config_app_name : 'ITFlow';
return ['id' => $host, 'origins' => $origins, 'name' => $name, 'address' => "https://$host$port"];
}
function passkeyWebAuthn() {
$rp = passkeyRp();
return new \ReportUri\Passkeys\WebAuthn($rp['name'], $rp['id'], true);
}
/** The salt the PRF extension is asked to sign - the same for every passkey here; the secret it gives is each passkey's own. */
function passkeyPrfSalt() {
return hash('sha256', 'ITFlow passkey vault key', true);
}
/** A new challenge for $purpose (sign_in, create), kept in the session - replacing any before it. */
function passkeyChallenge($purpose, $user_id = 0) {
$challenge = random_bytes(32);
$_SESSION['passkey_challenge'] = ['value' => passkeyB64url($challenge), 'purpose' => $purpose, 'user_id' => intval($user_id), 'created' => time()];
return passkeyB64url($challenge);
}
/** The session's challenge for $purpose, used up - false when there is none, or it ran out. */
function passkeyChallengeTake($purpose, $user_id = 0) {
$kept = $_SESSION['passkey_challenge'] ?? null;
unset($_SESSION['passkey_challenge']);
if (!is_array($kept) || ($kept['purpose'] ?? '') !== $purpose || intval($kept['user_id'] ?? 0) !== intval($user_id)
|| time() - intval($kept['created'] ?? 0) > PASSKEY_CHALLENGE_SECONDS) {
return false;
}
return passkeyFromB64url($kept['value'] ?? '');
}
/** What the sign-in page asks the browser for - any passkey made for this address (the browser offers the person theirs). */
function passkeySignInOptions() {
$rp = passkeyRp();
return [
'challenge' => passkeyChallenge('sign_in'),
'rpId' => $rp['id'],
'timeout' => 120000,
'userVerification' => 'required',
'allowCredentials' => [],
'extensions' => ['prf' => ['eval' => ['first' => passkeyB64url(passkeyPrfSalt())]]],
'address' => $rp['address'],
];
}
/** The random id a user's passkeys are made for - made the first time it is needed. */
function passkeyUserHandle($user_id) {
global $mysqli;
$user_id = intval($user_id);
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_passkey_handle FROM users WHERE user_id = $user_id"));
$handle = (string) ($row[0] ?? '');
if ($handle === '') {
$handle = passkeyB64url(random_bytes(32));
mysqli_query($mysqli, "UPDATE users SET user_passkey_handle = '" . escapeSql($handle) . "' WHERE user_id = $user_id AND (user_passkey_handle IS NULL OR user_passkey_handle = '')");
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_passkey_handle FROM users WHERE user_id = $user_id"));
$handle = (string) ($row[0] ?? $handle);
}
return $handle;
}
/** What adding a passkey asks the browser for - one made for this user, and not one of theirs already here. */
function passkeyCreateOptions($user_id, $email, $name) {
$rp = passkeyRp();
$exclude = [];
foreach (passkeyList($user_id) as $passkey) {
$item = ['type' => 'public-key', 'id' => $passkey['passkey_credential_id']];
if ($passkey['passkey_transports'] !== '') {
$item['transports'] = explode(',', $passkey['passkey_transports']);
}
$exclude[] = $item;
}
return [
'challenge' => passkeyChallenge('create', $user_id),
'rp' => ['id' => $rp['id'], 'name' => $rp['name']],
'user' => ['id' => passkeyUserHandle($user_id), 'name' => (string) $email, 'displayName' => (string) $name],
'pubKeyCredParams' => [['type' => 'public-key', 'alg' => -7], ['type' => 'public-key', 'alg' => -257]],
'timeout' => 120000,
'attestation' => 'none',
'authenticatorSelection' => ['residentKey' => 'required', 'requireResidentKey' => true, 'userVerification' => 'required'],
'excludeCredentials' => $exclude,
'extensions' => ['credProps' => true, 'prf' => ['eval' => ['first' => passkeyB64url(passkeyPrfSalt())]]],
'address' => $rp['address'],
];
}
/** Whether the browser signed from this install's own address - exactly, not just a name ending in it. */
function passkeyOriginOk($client_data_json) {
$client_data = json_decode((string) $client_data_json, true);
return is_array($client_data) && in_array((string) ($client_data['origin'] ?? ''), passkeyRp()['origins'], true);
}
/** A user's passkeys, newest first. */
function passkeyList($user_id) {
global $mysqli;
$rows = [];
$sql = mysqli_query($mysqli, "SELECT passkey_id, passkey_name, passkey_credential_id, passkey_transports, passkey_synced, passkey_vault <> '' AS passkey_opens_vault,
passkey_created_at, passkey_used_at FROM user_passkeys WHERE passkey_user_id = " . intval($user_id) . " ORDER BY passkey_created_at DESC, passkey_id DESC");
while ($sql && $row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
return $rows;
}
function passkeyCount($user_id) {
global $mysqli;
$sql = mysqli_query($mysqli, "SELECT COUNT(*) FROM user_passkeys WHERE passkey_user_id = " . intval($user_id));
return $sql ? intval(mysqli_fetch_row($sql)[0]) : 0;
}
/** Take away one of a user's passkeys - its name when it was theirs, false when it wasn't. */
function passkeyDelete($user_id, $passkey_id) {
global $mysqli;
$user_id = intval($user_id);
$passkey_id = intval($passkey_id);
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT passkey_name FROM user_passkeys WHERE passkey_id = $passkey_id AND passkey_user_id = $user_id"));
if (!$row) {
return false;
}
mysqli_query($mysqli, "DELETE FROM user_passkeys WHERE passkey_id = $passkey_id AND passkey_user_id = $user_id");
return (string) $row[0];
}
/** Take away all of a user's passkeys - when two-step sign-in is reset, they are archived, or their account goes. How many. */
function passkeysForget($user_id) {
global $mysqli;
$user_id = intval($user_id);
$count = passkeyCount($user_id);
if ($count) {
mysqli_query($mysqli, "DELETE FROM user_passkeys WHERE passkey_user_id = $user_id");
}
return $count;
}
/** A name for a new passkey when none is given - the device it is being added on. */
function passkeyDefaultName($user_agent) {
$name = trim(strip_tags(userDeviceHtml((string) $user_agent)));
return $name === '' || $name === 'Unknown device' ? 'Passkey' : mb_substr($name, 0, PASSKEY_NAME_MAX);
}
/** The vault key, sealed by a passkey's PRF secret - bound to that passkey (its credential hash). */
function passkeySealVault($master, $prf, $credential_hash) {
$key = hash_hkdf('sha256', (string) $prf, 32, 'ITFlow vault key', '');
$nonce = random_bytes(12);
$tag = '';
$ciphertext = openssl_encrypt((string) $master, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, PASSKEY_VAULT_FORMAT . $credential_hash);
return PASSKEY_VAULT_FORMAT . base64_encode($nonce . $tag . $ciphertext);
}
/** The vault key from a passkey's sealed copy and its PRF secret - false when it doesn't open. */
function passkeyOpenVault($sealed, $prf, $credential_hash) {
$sealed = (string) $sealed;
if (strpos($sealed, PASSKEY_VAULT_FORMAT) !== 0 || strlen((string) $prf) < 16) {
return false;
}
$raw = base64_decode(substr($sealed, strlen(PASSKEY_VAULT_FORMAT)), true);
if ($raw === false || strlen($raw) < 29) {
return false;
}
$key = hash_hkdf('sha256', (string) $prf, 32, 'ITFlow vault key', '');
$master = openssl_decrypt(substr($raw, 28), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($raw, 0, 12), substr($raw, 12, 16), PASSKEY_VAULT_FORMAT . $credential_hash);
return is_string($master) && $master !== '' ? $master : false;
}
/**
* Add a passkey for a user, from what the browser made ($post: client_data, attestation, transports,
* prf - all base64url but transports) - checked against the challenge given them, this address,
* and that it verified the person. $master is the vault key, for an agent, to seal with the
* passkey's PRF secret when it gave one. [passkey id or false, message].
*/
function passkeyRegister($user_id, $name, array $post, $master = null) {
global $mysqli;
$user_id = intval($user_id);
$challenge = passkeyChallengeTake('create', $user_id);
if ($challenge === false) {
return [false, 'That took too long - add the passkey again.'];
}
if (passkeyCount($user_id) >= PASSKEY_PER_USER) {
return [false, 'You have ' . PASSKEY_PER_USER . ' passkeys already - remove one you no longer use first.'];
}
$client_data = passkeyFromB64url($post['client_data'] ?? '');
$attestation = passkeyFromB64url($post['attestation'] ?? '');
if ($client_data === false || $attestation === false) {
return [false, 'The browser did not send a passkey - add it again.'];
}
if (!passkeyOriginOk($client_data)) {
return [false, 'Passkeys are added at ' . passkeyRp()['address'] . ' - open ITFlow there and add it again.'];
}
try {
$made = passkeyWebAuthn()->processCreate($client_data, $attestation, $challenge, true, true);
} catch (\Throwable $e) {
return [false, 'That passkey could not be checked (' . $e->getMessage() . ') - add it again.'];
}
$credential_id = (string) $made->credentialId;
$hash = hash('sha256', $credential_id);
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM user_passkeys WHERE passkey_credential_hash = '$hash'"))) {
return [false, 'That passkey is already added.'];
}
$transports = [];
foreach (explode(',', (string) ($post['transports'] ?? '')) as $transport) {
$transport = trim($transport);
if (preg_match('/^[a-z-]{2,20}$/', $transport) && !in_array($transport, $transports, true)) {
$transports[] = $transport;
}
}
$vault = '';
$prf = passkeyFromB64url($post['prf'] ?? '');
if (is_string($master) && $master !== '' && $prf !== false && strlen($prf) >= 32) {
$vault = passkeySealVault($master, $prf, $hash);
if (passkeyOpenVault($vault, $prf, $hash) !== $master) {
$vault = '';
}
}
$aaguid = '';
if (is_string($made->AAGUID ?? null) && strlen($made->AAGUID) === 16 && trim($made->AAGUID, "\0") !== '') {
$aaguid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($made->AAGUID), 4));
}
$name = mb_substr(trim((string) $name), 0, PASSKEY_NAME_MAX);
mysqli_query($mysqli, "INSERT INTO user_passkeys SET passkey_user_id = $user_id, passkey_name = '" . escapeSql($name !== '' ? $name : 'Passkey') . "',
passkey_credential_id = '" . escapeSql(passkeyB64url($credential_id)) . "', passkey_credential_hash = '$hash',
passkey_public_key = '" . escapeSql((string) $made->credentialPublicKey) . "', passkey_sign_count = " . max(0, intval($made->signatureCounter ?? 0)) . ",
passkey_aaguid = '$aaguid', passkey_transports = '" . escapeSql(implode(',', $transports)) . "',
passkey_synced = " . (!empty($made->isBackupEligible) ? 1 : 0) . ", passkey_vault = '" . escapeSql($vault) . "'");
return [intval(mysqli_insert_id($mysqli)), $vault !== '' ? 'opens' : 'added'];
}
/**
* Check a passkey sign-in ($post: id, client_data, authenticator_data, signature, user_handle - base64url)
* against the challenge given this session, the passkey's public key, this address, and that the
* person was verified. [the passkey and its user, or false; why not, for the log; the user it was, if known].
*/
function passkeyVerifySignIn(array $post) {
global $mysqli;
$challenge = passkeyChallengeTake('sign_in');
if ($challenge === false) {
return [false, 'the sign-in took too long', 0];
}
$id = passkeyFromB64url($post['id'] ?? '');
$client_data = passkeyFromB64url($post['client_data'] ?? '');
$authenticator_data = passkeyFromB64url($post['authenticator_data'] ?? '');
$signature = passkeyFromB64url($post['signature'] ?? '');
if ($id === false || $client_data === false || $authenticator_data === false || $signature === false) {
return [false, 'the browser sent no passkey', 0];
}
$hash = hash('sha256', $id);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_passkeys.*, users.user_id, users.user_email, users.user_name, users.user_type, users.user_passkey_handle
FROM user_passkeys JOIN users ON users.user_id = user_passkeys.passkey_user_id WHERE passkey_credential_hash = '$hash'"));
if (!$row) {
return [false, 'the passkey is not one added here - it may have been removed', 0];
}
$user_id = intval($row['user_id']);
$handle = passkeyFromB64url($post['user_handle'] ?? '');
if ($handle !== false && !hash_equals(passkeyB64url($handle), (string) $row['user_passkey_handle'])) {
return [false, 'the passkey is not this account\'s', $user_id];
}
if (!passkeyOriginOk($client_data)) {
return [false, 'the browser was not at ' . passkeyRp()['address'], $user_id];
}
try {
passkeyWebAuthn()->processGet($client_data, $authenticator_data, $signature, $row['passkey_public_key'], $challenge, intval($row['passkey_sign_count']), true, true);
} catch (\Throwable $e) {
return [false, 'the passkey did not check out (' . $e->getMessage() . ')', $user_id];
}
// The signature count, when the passkey keeps one (synced ones don't - always 0)
$count = strlen($authenticator_data) >= 37 ? unpack('N', substr($authenticator_data, 33, 4))[1] : 0;
mysqli_query($mysqli, "UPDATE user_passkeys SET passkey_used_at = NOW()" . ($count > 0 ? ", passkey_sign_count = " . intval($count) : '') . "
WHERE passkey_id = " . intval($row['passkey_id']));
return [$row, '', $user_id];
}
/** The passkeys card's details for one - when added and last used, and what it does. Raw in, HTML out. */
function passkeyMetaHtml(array $passkey, $vault = true) {
$bits = ['Added ' . escapeHtml(date('M j, Y', strtotime($passkey['passkey_created_at'])))];
$bits[] = $passkey['passkey_used_at'] ? 'used <span title="' . formatDateTime($passkey['passkey_used_at']) . '">' . escapeHtml(timeAgo($passkey['passkey_used_at'])) . '</span>' : 'not used yet';
if (intval($passkey['passkey_synced'])) {
$bits[] = 'synced between your devices';
}
if ($vault) {
$bits[] = intval($passkey['passkey_opens_vault']) ? 'opens your credentials' : 'credentials take your password';
}
return implode(' · ', $bits);
}
/* ------------------------------------------------------------ The vault, after a passkey sign-in that didn't open it */
/**
* Is this agent's vault locked - they have a copy of the vault key, but this session's vault
* doesn't open (a passkey sign-in that couldn't open it)? Unlocked with their password (vaultUnlock()).
*/
function vaultLocked() {
global $mysqli, $session_user_id;
static $locked = null;
if ($locked !== null) {
return $locked;
}
$user_id = intval($session_user_id ?? 0);
if (!$user_id || vaultSessionOpens()) {
return $locked = false;
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_specific_encryption_ciphertext FROM users WHERE user_id = $user_id AND user_type = 1"));
return $locked = trim((string) ($row[0] ?? '')) !== '';
}
/*
* Their password, for adding a passkey or unlocking the vault - five wrong ones in ten minutes and
* it waits (each logged, as Login / Password Failed). [ok, message, the user's row].
*/
function passkeyPasswordCheck($user_id, #[\SensitiveParameter] $password, $for) {
global $mysqli;
$user_id = intval($user_id);
$failed = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(log_id) FROM logs WHERE log_user_id = $user_id AND log_type IN ('Login', 'Client Login')
AND log_action = 'Password Failed' AND log_created_at > (NOW() - INTERVAL 10 MINUTE)"));
if (intval($failed[0] ?? 0) >= 5) {
return [false, 'Too many wrong passwords - wait 10 minutes and try again.', null];
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_id, user_name, user_email, user_type, user_password, user_specific_encryption_ciphertext FROM users WHERE user_id = $user_id"));
if (!$row || (string) $password === '' || !password_verify((string) $password, (string) $row['user_password'])) {
$client_id = 0;
if ($row && intval($row['user_type']) === 2) {
$client_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_client_id FROM contacts WHERE contact_user_id = $user_id"))[0] ?? 0);
}
logAudit($row && intval($row['user_type']) === 2 ? 'Client Login' : 'Login', 'Password Failed', escapeSql(($row['user_name'] ?? 'Someone') . " typed a wrong password to $for"), $client_id, $user_id);
return [false, 'That is not your password.', null];
}
return [true, '', $row];
}
/** This session's vault key - false when the vault isn't open. */
function vaultSessionMaster() {
$ciphertext = $_SESSION['user_encryption_session_ciphertext'] ?? '';
$iv = base64_decode($_SESSION['user_encryption_session_iv'] ?? '');
$key = base64_decode($_COOKIE['user_encryption_session_key'] ?? '');
if ($ciphertext === '' || strlen($iv) !== 16 || $key === '') {
return false;
}
$master = openssl_decrypt($ciphertext, 'aes-128-cbc', $key, 0, $iv);
return is_string($master) && strlen($master) === 16 ? $master : false;
}
/** Open a locked vault with the agent's password. [ok, message]. */
function vaultUnlock($user_id, #[\SensitiveParameter] $password) {
[$ok, $message, $row] = passkeyPasswordCheck($user_id, $password, 'unlock their credentials');
if (!$ok) {
return [false, $message];
}
if (intval($row['user_type']) !== 1 || !vaultSignIn(intval($user_id), $row['user_specific_encryption_ciphertext'], $password)) {
return [false, 'Your copy of the vault key did not open - ask an administrator to set your password again.'];
}
logAudit('Login', 'Unlock', escapeSql($row['user_name']) . ' unlocked their credentials with their password', 0, intval($user_id));
return [true, ''];
}
/*
* Why the vault is locked, as it is said to the agent - how they signed in without the password
* that opens it (login.php): a passkey that can't, an identity provider, or their mail password.
*/
function vaultLockedReason() {
$via = trim((string) ($_SESSION['signed_in_via'] ?? ''));
return [
'provider' => 'you signed in with ' . ($via !== '' ? $via : 'an identity provider') . ', which can\'t open them',
'imap' => 'you signed in with your mail password, which can\'t open them',
][$_SESSION['signed_in_with'] ?? ''] ?? 'you signed in with a passkey that can\'t open them';
}
/** The note in a credential window while the vault is locked - with the button that unlocks it (js/credentials.js). */
function vaultLockedAlertHtml() {
return '<div class="alert alert-warning small d-flex align-items-center gap-2"><i class="fas fa-lock"></i>'
. '<span class="flex-grow-1">Your credentials are locked - ' . escapeHtml(vaultLockedReason()) . '.</span>'
. '<button type="button" class="btn btn-sm btn-warning text-nowrap" data-vault-unlock><i class="fas fa-unlock me-1"></i>Unlock</button></div>';
}
/** How many passkeys each user has - [user id => count], for lists. Empty before the database has them. */
function passkeyCounts() {
global $mysqli;
if (!passkeysReady()) {
return [];
}
$counts = [];
$sql = mysqli_query($mysqli, "SELECT passkey_user_id, COUNT(*) FROM user_passkeys GROUP BY passkey_user_id");
while ($row = mysqli_fetch_row($sql)) {
$counts[intval($row[0])] = intval($row[1]);
}
return $counts;
}