mirror of
https://github.com/itflow-org/itflow
synced 2026-12-04 01:59:00 +00:00
Passkeys and the credential vault: a passkey that gives its PRF secret at sign-in but has no copy of the vault key that opens with it (added where the browser didn't give the secret then, like Windows Hello before Chrome 147) has the secret kept for the session (passkeySealKeep(), encrypted with its key in the passkey_seal_key cookie) and a copy sealed to it once the vault opens (passkeySealKept()), so it opens the vault by itself from the next sign-in; the Unlock window offers Unlock with a Passkey when the agent has a passkey that opens the vault (vaultUnlockPasskey(), passkeyVerify() with an unlock challenge, vault_unlock_passkey_options and vault_unlock_passkey in agent/ajax.php); 26.12.5 changelog
This commit is contained in:
@@ -15,18 +15,21 @@ Update from Maintenance > Update as usual. This release has one database change,
|
||||
|
||||
- Cron leaves alone the jobs that have nothing to do on your ITFlow - what they work with is switched off or isn't set up: AI Triage, Text Messages, RMM Sync and RMM Alerts, the Ticket Email Parser with email to ticket off or no mailbox, the Mail Queue with no mail server, Payment Provider Fees without Stripe, the Update Check on an install that isn't a git checkout, and Manager Check-in and Managed Instances when there's nothing connected. Before, each one started every minute only to stop itself. Maintenance > Cron shows them as **Not in use**, with why under each; they start by themselves once that changes, and **Run Now** still runs them. Cron Watch doesn't email about them falling behind.
|
||||
- An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them.
|
||||
- Unlock your credentials with a passkey. When a passkey sign-in leaves them locked although your passkey opens them - signing in by scanning a QR code with your phone, or some password managers' autofill - the Unlock window offers **Unlock with a Passkey** before your password, with any passkey of yours that opens them. It's there while passkeys are on in Admin > Settings > Security.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- A cron job that an old cron line also ran - the line for the Ticket Email Parser or the Mail Queue left in `/etc/cron.d/itflow` by the install script before 26.08 - no longer looks stopped. The old line's run took the job's lock, so `cron.php` passed it by: its last run on Maintenance > Cron stayed days old and Cron Watch emailed that it had fallen behind, while its work got done - and turning it off didn't stop it. Now the old line's run steps aside while `cron.php` is running, Maintenance > Cron lists the lines to take out, with the file and line, and so do Debug and Cron Watch's email. A line ITFlow can't see - in a user's own crontab - is still found from its runs, and said with where to look.
|
||||
- A cron job whose lock file was made by a run as root no longer stops cron. The web server's user can't open such a file, and every job after it in the list stopped, every minute, without a word - Cron Watch with them - until the server restarted. Now that job fails, saying which file to delete, and the rest run. Cron started as root now becomes the user that owns ITFlow's files first, so it doesn't leave such files - or uploads, backups and git files the web server can't use - behind.
|
||||
- AI Triage no longer runs every minute when AI triage is off in Settings > Tickets or there's no AI model to ask - before, it ran anyway and showed **Completed** every minute with nothing done.
|
||||
- A passkey that didn't open your credentials when it was added now opens them after you type your password once. Some browsers don't let a passkey open them when it's made, though they do at every sign-in after - Windows Hello in Chrome before version 147, for one, and some password managers - and every sign-in with such a passkey asked for the password again, for as long as you had it. Now the first sign-in with it says in the Unlock window that your passkey will open them from then on; type your password, and from the next sign-in it opens them by itself, and Your account > Security says **opens your credentials** under it. A passkey that never gives what opens them still takes your password each time.
|
||||
|
||||
### Developer Updates
|
||||
|
||||
- `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added.
|
||||
- Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule.
|
||||
- Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule.
|
||||
- Passkeys sealed to the vault after they were added (`functions/passkey.php`, no database change): `login_passkey.php` keeps a passkey's PRF result for the session when it has no `passkey_vault` that opens with it - `passkeySealKeep()`, AES-256-GCM in `$_SESSION['passkey_seal']` with its key in the httponly `passkey_seal_key` cookie, set as `user_encryption_session_key` is - and once the vault opens, `vaultUnlock()` or the new `vaultUnlockPasskey()` seals the vault key to it (`passkeySealKept()`, checked to open before `passkey_vault` is written; the kept secret is dropped either way, and logout clears the cookie). `vaultUnlockPasskey()` checks an assertion for the new `unlock` challenge purpose against the signed-in agent's own passkeys - `passkeyVerify($post, $purpose, $user_id)`, which `passkeyVerifySignIn()` now wraps - and opens the vault with its PRF result; a passkey whose copy doesn't open with it keeps that result for the password to seal. `passkeyUnlockOptions()`, `passkeyVaultCount()` and `passkeySealPending()` feed the Unlock window (`includes/footer.php`, `[data-vault-unlock-passkey]`), and `agent/ajax.php` adds `vault_unlock_passkey_options` and `vault_unlock_passkey` (POST, CSRF). `js/passkey.js` handles the button, runs once per page (`window.itflowPasskeys`) and fires `itflow:vault-unlocked` on `#vaultUnlockModal`, which `js/credentials.js` now listens for. A passkey that doesn't unlock is logged as Login / Unlock Failed. `vaultLockedReason()` for a passkey sign-in now reads "your passkey sign-in didn't open them".
|
||||
|
||||
## [26.12.4]
|
||||
|
||||
|
||||
@@ -59,6 +59,24 @@ if (isset($_POST['vault_unlock'])) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/*
|
||||
* Or with a passkey of theirs that opens the vault (vaultUnlockPasskey(), js/passkey.js):
|
||||
* vault_unlock_passkey_options is what to ask the browser for, vault_unlock_passkey checks its answer.
|
||||
*/
|
||||
if (isset($_POST['vault_unlock_passkey_options']) || isset($_POST['vault_unlock_passkey'])) {
|
||||
validateCSRFToken();
|
||||
header('Content-Type: application/json');
|
||||
if (!passkeyVaultCount($session_user_id)) {
|
||||
exit(json_encode(['error' => 'None of your passkeys opens your credentials here - type your password.']));
|
||||
}
|
||||
if (isset($_POST['vault_unlock_passkey_options'])) {
|
||||
exit(json_encode(passkeyUnlockOptions($session_user_id)));
|
||||
}
|
||||
[$unlocked, $unlock_message] = vaultUnlockPasskey($session_user_id, $_POST);
|
||||
echo json_encode($unlocked ? ['unlocked' => true] : ['error' => $unlock_message]);
|
||||
exit;
|
||||
}
|
||||
|
||||
/*
|
||||
* Markdown for a document's editors (js/document_markdown.js, functions/markdown.php): Markdown as
|
||||
* the HTML it shows as - its Preview, switching it to the rich text editor, and Markdown pasted
|
||||
|
||||
@@ -314,7 +314,7 @@ if (isset($_POST['add_your_passkey'])) {
|
||||
|
||||
flashAlert("Passkey <strong>" . escapeHtml($name) . "</strong> added - " . ($how === 'opens'
|
||||
? 'it signs you in and opens your credentials'
|
||||
: 'it signs you in, and you type your password once each time to open your credentials'));
|
||||
: 'it signs you in. The first time you sign in with it, unlock your credentials with your password - from then on it opens them too, if the passkey can'));
|
||||
|
||||
redirect("user_security.php");
|
||||
|
||||
|
||||
@@ -268,7 +268,7 @@ function credentialFormSet($post, $client_id, &$error = '') {
|
||||
$password = encryptCredentialEntry(trim((string) ($post['password'] ?? '')));
|
||||
$otp = credentialOtpEncrypt($otp);
|
||||
if ($username === false || $password === false || $otp === false) {
|
||||
$error = vaultLocked() ? 'Your credentials are locked - ' . vaultLockedReason() . '. Unlock them with your password (the lock beside a username), then save again.'
|
||||
$error = vaultLocked() ? 'Your credentials are locked - ' . vaultLockedReason() . '. Unlock them (the lock beside a username), then save again.'
|
||||
: 'Your vault session has expired, so the login could not be encrypted - sign out and back in, then try again.';
|
||||
return null;
|
||||
}
|
||||
@@ -314,8 +314,8 @@ function credentialUsername($row) {
|
||||
function credentialUsernameHtml($username, $empty = '-') {
|
||||
$username = escapeHtml($username);
|
||||
if ($username === '' && vaultLocked()) {
|
||||
// Signed in with a passkey that couldn't open the vault - their password unlocks it (js/credentials.js)
|
||||
return '<a href="#" class="text-body-secondary text-decoration-none" data-vault-unlock data-vault-locked title="Unlock with your password"><i class="fas fa-lock me-1"></i>Locked</a>';
|
||||
// Signed in with a passkey that didn't open the vault - their password, or a passkey that opens it, unlocks it (js/credentials.js)
|
||||
return '<a href="#" class="text-body-secondary text-decoration-none" data-vault-unlock data-vault-locked title="Unlock your credentials"><i class="fas fa-lock me-1"></i>Locked</a>';
|
||||
}
|
||||
if ($username === '') {
|
||||
return '<span class="text-body-secondary">' . $empty . '</span>';
|
||||
|
||||
@@ -19,6 +19,14 @@
|
||||
* 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()).
|
||||
*
|
||||
* That copy is made when the passkey is added, if the browser gives the secret then - and some
|
||||
* don't, though the same passkey gives it at every sign-in after (Windows Hello before Chrome 147,
|
||||
* some password managers). So a passkey sign-in that gives the secret, with no copy that opens with
|
||||
* it, keeps the secret for the session (passkeySealKeep()) until the vault is opened - by their
|
||||
* password, or another passkey - and a copy is sealed to it then (passkeySealKept()). A sign-in
|
||||
* that didn't bring the secret (a phone's QR code, some autofill) can be followed by Unlock with a
|
||||
* passkey, which asks for one of theirs that opens the vault (vaultUnlockPasskey()).
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
@@ -29,6 +37,7 @@ const PASSKEY_CHALLENGE_SECONDS = 300;
|
||||
const PASSKEY_VAULT_FORMAT = 'pk1:';
|
||||
const PASSKEY_PER_USER = 20;
|
||||
const PASSKEY_NAME_MAX = 60;
|
||||
const PASSKEY_SEAL_COOKIE = 'passkey_seal_key';
|
||||
|
||||
/*
|
||||
* Whether the database has passkeys yet (4.2.2), and whether they can be used to sign in - Admin >
|
||||
@@ -95,7 +104,7 @@ 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. */
|
||||
/** A new challenge for $purpose (sign_in, create, unlock), 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()];
|
||||
@@ -315,23 +324,35 @@ function passkeyRegister($user_id, $name, array $post, $master = null) {
|
||||
* 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) {
|
||||
return passkeyVerify($post, 'sign_in');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a passkey's answer to the challenge given this session for $purpose - sign_in (any passkey
|
||||
* added here) or unlock (one of $user_id's). As passkeyVerifySignIn().
|
||||
*/
|
||||
function passkeyVerify(array $post, $purpose, $user_id = 0) {
|
||||
global $mysqli;
|
||||
$challenge = passkeyChallengeTake('sign_in');
|
||||
$user_id = intval($user_id);
|
||||
$challenge = passkeyChallengeTake($purpose, $user_id);
|
||||
if ($challenge === false) {
|
||||
return [false, 'the sign-in took too long', 0];
|
||||
return [false, 'the sign-in took too long', $user_id];
|
||||
}
|
||||
$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];
|
||||
return [false, 'the browser sent no passkey', $user_id];
|
||||
}
|
||||
$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];
|
||||
return [false, 'the passkey is not one added here - it may have been removed', $user_id];
|
||||
}
|
||||
if ($user_id && intval($row['user_id']) !== $user_id) {
|
||||
return [false, 'the passkey is someone else\'s', $user_id];
|
||||
}
|
||||
$user_id = intval($row['user_id']);
|
||||
$handle = passkeyFromB64url($post['user_handle'] ?? '');
|
||||
@@ -370,7 +391,8 @@ function passkeyMetaHtml(array $passkey, $vault = true) {
|
||||
|
||||
/**
|
||||
* 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()).
|
||||
* doesn't open (a passkey sign-in that couldn't open it)? Unlocked with their password (vaultUnlock()),
|
||||
* or a passkey of theirs that opens it (vaultUnlockPasskey()).
|
||||
*/
|
||||
function vaultLocked() {
|
||||
global $mysqli, $session_user_id;
|
||||
@@ -422,7 +444,7 @@ function vaultSessionMaster() {
|
||||
return is_string($master) && strlen($master) === 16 ? $master : false;
|
||||
}
|
||||
|
||||
/** Open a locked vault with the agent's password. [ok, message]. */
|
||||
/** Open a locked vault with the agent's password - sealing it to a passkey kept for that (passkeySealKept()). [ok, message]. */
|
||||
function vaultUnlock($user_id, #[\SensitiveParameter] $password) {
|
||||
[$ok, $message, $row] = passkeyPasswordCheck($user_id, $password, 'unlock their credentials');
|
||||
if (!$ok) {
|
||||
@@ -431,20 +453,170 @@ function vaultUnlock($user_id, #[\SensitiveParameter] $password) {
|
||||
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));
|
||||
// The vault key vaultSignIn() just opened - remembered from there, not worked out again
|
||||
$sealed = passkeySealKept($user_id, decryptUserSpecificKey($row['user_specific_encryption_ciphertext'], $password));
|
||||
logAudit('Login', 'Unlock', escapeSql($row['user_name']) . ' unlocked their credentials with their password'
|
||||
. ($sealed !== '' ? ' - their passkey (' . escapeSql($sealed) . ') opens them from now on' : ''), 0, intval($user_id));
|
||||
return [true, ''];
|
||||
}
|
||||
|
||||
/*
|
||||
* Open a locked vault with a passkey (Unlock, js/passkey.js) - one of theirs with a copy of the vault
|
||||
* key, and the PRF secret it gives. One whose copy doesn't open with the secret it gave keeps that
|
||||
* secret, for their password to seal a copy that does (passkeySealKept()). [ok, message].
|
||||
*/
|
||||
function vaultUnlockPasskey($user_id, array $post) {
|
||||
global $mysqli;
|
||||
$user_id = intval($user_id);
|
||||
[$passkey, $why] = passkeyVerify($post, 'unlock', $user_id);
|
||||
if (!$passkey) {
|
||||
$name = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_id = $user_id"))[0] ?? 'Someone');
|
||||
logAudit('Login', 'Unlock Failed', escapeSql("$name couldn't unlock their credentials with a passkey - $why"), 0, $user_id);
|
||||
return [false, str_starts_with($why, 'the sign-in took too long') ? 'That took too long - try again.'
|
||||
: 'That passkey didn\'t unlock them - try again, or type your password.'];
|
||||
}
|
||||
$prf = passkeyFromB64url($post['prf'] ?? '');
|
||||
if ($prf === false || strlen($prf) < 32) {
|
||||
return [false, 'Your passkey didn\'t give what opens your credentials in this browser - type your password instead.'];
|
||||
}
|
||||
$master = $passkey['passkey_vault'] !== '' ? passkeyOpenVault($passkey['passkey_vault'], $prf, $passkey['passkey_credential_hash']) : false;
|
||||
if ($master === false) {
|
||||
passkeySealKeep($passkey, $prf);
|
||||
return [false, 'That passkey didn\'t open them - type your password, and it will from your next sign-in.'];
|
||||
}
|
||||
generateUserSessionKey($master);
|
||||
$sealed = passkeySealKept($user_id, $master);
|
||||
logAudit('Login', 'Unlock', escapeSql($passkey['user_name']) . ' unlocked their credentials with a passkey (' . escapeSql($passkey['passkey_name']) . ')'
|
||||
. ($sealed !== '' ? ' - their passkey (' . escapeSql($sealed) . ') opens them from now on' : ''), 0, $user_id);
|
||||
return [true, ''];
|
||||
}
|
||||
|
||||
/** What Unlock asks the browser for - one of $user_id's passkeys that opens the vault, and its PRF secret. Null when none of theirs does. */
|
||||
function passkeyUnlockOptions($user_id) {
|
||||
global $mysqli;
|
||||
$allow = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT passkey_credential_id, passkey_transports FROM user_passkeys WHERE passkey_user_id = " . intval($user_id) . " AND passkey_vault <> ''");
|
||||
while ($sql && $row = mysqli_fetch_assoc($sql)) {
|
||||
$item = ['type' => 'public-key', 'id' => $row['passkey_credential_id']];
|
||||
if ($row['passkey_transports'] !== '') {
|
||||
$item['transports'] = explode(',', $row['passkey_transports']);
|
||||
}
|
||||
$allow[] = $item;
|
||||
}
|
||||
if (!$allow) {
|
||||
return null;
|
||||
}
|
||||
$rp = passkeyRp();
|
||||
return [
|
||||
'challenge' => passkeyChallenge('unlock', $user_id),
|
||||
'rpId' => $rp['id'],
|
||||
'timeout' => 120000,
|
||||
'userVerification' => 'required',
|
||||
'allowCredentials' => $allow,
|
||||
'extensions' => ['prf' => ['eval' => ['first' => passkeyB64url(passkeyPrfSalt())]]],
|
||||
'address' => $rp['address'],
|
||||
];
|
||||
}
|
||||
|
||||
/** How many of $user_id's passkeys open the vault - for Unlock to offer them. 0 while passkeys are off or not in the database yet. */
|
||||
function passkeyVaultCount($user_id) {
|
||||
global $mysqli;
|
||||
if (!passkeysReady() || !passkeysOn()) {
|
||||
return 0;
|
||||
}
|
||||
$sql = mysqli_query($mysqli, "SELECT COUNT(*) FROM user_passkeys WHERE passkey_user_id = " . intval($user_id) . " AND passkey_vault <> ''");
|
||||
return $sql ? intval(mysqli_fetch_row($sql)[0]) : 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* A passkey's PRF secret, kept for this session until the vault opens (passkeySealKept()) - from a
|
||||
* sign-in (login_passkey.php) or Unlock that gave it, where the passkey has no copy of the vault key
|
||||
* that opens with it. Encrypted, with its key in a cookie, as the vault session is (generateUserSessionKey()),
|
||||
* so neither the session store nor the browser has it alone.
|
||||
*/
|
||||
function passkeySealKeep(array $passkey, #[\SensitiveParameter] $prf) {
|
||||
$key = random_bytes(32);
|
||||
$nonce = random_bytes(12);
|
||||
$tag = '';
|
||||
$ciphertext = openssl_encrypt((string) $prf, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, 'ITFlow passkey seal');
|
||||
$_SESSION['passkey_seal'] = [
|
||||
'user_id' => intval($passkey['passkey_user_id']),
|
||||
'passkey_id' => intval($passkey['passkey_id']),
|
||||
'hash' => (string) $passkey['passkey_credential_hash'],
|
||||
'name' => (string) $passkey['passkey_name'],
|
||||
'secret' => base64_encode($nonce . $tag . $ciphertext),
|
||||
];
|
||||
passkeySealCookie(base64_encode($key));
|
||||
}
|
||||
|
||||
/** The name of the passkey whose secret is kept for $user_id, waiting for the vault to open - '' when there is none. */
|
||||
function passkeySealPending($user_id) {
|
||||
$kept = $_SESSION['passkey_seal'] ?? null;
|
||||
return is_array($kept) && intval($kept['user_id'] ?? 0) === intval($user_id) && !empty($_COOKIE[PASSKEY_SEAL_COOKIE]) ? (string) $kept['name'] : '';
|
||||
}
|
||||
|
||||
/*
|
||||
* The vault just opened with $master, the vault key: seal a copy of it to the passkey kept for that
|
||||
* (passkeySealKeep()), so the passkey opens the vault itself from then on - checked to open before
|
||||
* it is written. The kept secret is dropped either way. The passkey's name, or '' when nothing was sealed.
|
||||
*/
|
||||
function passkeySealKept($user_id, #[\SensitiveParameter] $master) {
|
||||
global $mysqli;
|
||||
$kept = $_SESSION['passkey_seal'] ?? null;
|
||||
$key = base64_decode((string) ($_COOKIE[PASSKEY_SEAL_COOKIE] ?? ''), true);
|
||||
unset($_SESSION['passkey_seal']);
|
||||
if (isset($_COOKIE[PASSKEY_SEAL_COOKIE])) {
|
||||
passkeySealCookie('');
|
||||
}
|
||||
if (!is_array($kept) || intval($kept['user_id'] ?? 0) !== intval($user_id) || !is_string($master) || strlen($master) < 16 || !is_string($key) || strlen($key) !== 32) {
|
||||
return '';
|
||||
}
|
||||
$raw = base64_decode((string) ($kept['secret'] ?? ''), true);
|
||||
$prf = is_string($raw) && strlen($raw) > 28
|
||||
? openssl_decrypt(substr($raw, 28), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($raw, 0, 12), substr($raw, 12, 16), 'ITFlow passkey seal') : false;
|
||||
if (!is_string($prf) || strlen($prf) < 32) {
|
||||
return '';
|
||||
}
|
||||
$hash = (string) $kept['hash'];
|
||||
$sealed = passkeySealVault($master, $prf, $hash);
|
||||
if (passkeyOpenVault($sealed, $prf, $hash) !== $master) {
|
||||
return '';
|
||||
}
|
||||
mysqli_query($mysqli, "UPDATE user_passkeys SET passkey_vault = '" . escapeSql($sealed) . "'
|
||||
WHERE passkey_id = " . intval($kept['passkey_id']) . " AND passkey_user_id = " . intval($user_id) . " AND passkey_credential_hash = '" . escapeSql($hash) . "'");
|
||||
return mysqli_affected_rows($mysqli) > 0 ? (string) $kept['name'] : '';
|
||||
}
|
||||
|
||||
/** The cookie with the key to a kept secret (passkeySealKeep()) - set as the vault session's is (generateUserSessionKey()), or cleared with ''. */
|
||||
function passkeySealCookie($value) {
|
||||
global $config_https_only;
|
||||
if (!isset($config_https_only)) {
|
||||
include __DIR__ . '/../config.php';
|
||||
}
|
||||
$options = ['path' => '/', 'httponly' => true, 'expires' => $value === '' ? time() - 3600 : 0];
|
||||
if ($config_https_only) {
|
||||
$options += ['secure' => true, 'samesite' => 'None'];
|
||||
} else {
|
||||
$options['samesite'] = 'Lax';
|
||||
}
|
||||
if (!headers_sent()) {
|
||||
setcookie(PASSKEY_SEAL_COOKIE, (string) $value, $options);
|
||||
}
|
||||
if ($value === '') {
|
||||
unset($_COOKIE[PASSKEY_SEAL_COOKIE]);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 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.
|
||||
* that opens it (login.php): a passkey sign-in that didn'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';
|
||||
][$_SESSION['signed_in_with'] ?? ''] ?? 'your passkey sign-in didn\'t open them';
|
||||
}
|
||||
|
||||
/** The note in a credential window while the vault is locked - with the button that unlocks it (js/credentials.js). */
|
||||
|
||||
@@ -96,12 +96,21 @@ try {
|
||||
<script src="<?= staticFileUrl('/js/app.js') ?>"></script>
|
||||
<script src="<?= staticFileUrl('/js/picture_field.js') ?>"></script>
|
||||
<?php
|
||||
// Signed in without the password that opens the credential vault - a passkey that can't, an identity provider or a mail password; their password unlocks it (vaultUnlock(), js/credentials.js)
|
||||
// Signed in without the password that opens the credential vault - a passkey sign-in that didn't, an identity provider or a mail password; their password
|
||||
// unlocks it (vaultUnlock(), js/credentials.js), and so does a passkey of theirs that opens it (vaultUnlockPasskey(), js/passkey.js)
|
||||
try {
|
||||
$itflow_vault_locked = function_exists('vaultLocked') && vaultLocked();
|
||||
} catch (Throwable $e) {
|
||||
$itflow_vault_locked = false;
|
||||
}
|
||||
// And a passkey whose secret is kept from this sign-in, sealed to once the vault opens (passkeySealKept())
|
||||
try {
|
||||
$itflow_vault_passkeys = $itflow_vault_locked ? passkeyVaultCount($session_user_id) : 0;
|
||||
$itflow_vault_seal = $itflow_vault_locked ? passkeySealPending($session_user_id) : '';
|
||||
} catch (Throwable $e) {
|
||||
$itflow_vault_passkeys = 0;
|
||||
$itflow_vault_seal = '';
|
||||
}
|
||||
if ($itflow_vault_locked) { ?>
|
||||
<div class="modal" id="vaultUnlockModal" tabindex="-1" data-csrf="<?= $_SESSION['csrf_token'] ?>">
|
||||
<div class="modal-dialog">
|
||||
@@ -112,8 +121,17 @@ if ($itflow_vault_locked) { ?>
|
||||
</div>
|
||||
<form data-vault-unlock-form autocomplete="off">
|
||||
<div class="modal-body">
|
||||
<p><?= escapeHtml(ucfirst(vaultLockedReason())) ?>, so your usernames, passwords and 2FA codes are locked. Type your ITFlow password to unlock them until you sign out.</p>
|
||||
<p><?= escapeHtml(ucfirst(vaultLockedReason())) ?>, so your usernames, passwords and 2FA codes are locked. <?= $itflow_vault_passkeys ? 'Unlock them with a passkey or your ITFlow password' : 'Type your ITFlow password to unlock them' ?> until you sign out.</p>
|
||||
<?php if ($itflow_vault_seal !== '') { ?>
|
||||
<p class="small text-body-secondary"><i class="fas fa-fingerprint me-1"></i>Once you do, your passkey <strong><?= escapeHtml($itflow_vault_seal) ?></strong> opens them by itself from your next sign-in.</p>
|
||||
<?php } ?>
|
||||
<div data-vault-unlock-message></div>
|
||||
<?php if ($itflow_vault_passkeys) { ?>
|
||||
<div data-vault-unlock-passkey-box hidden>
|
||||
<button type="button" class="btn btn-outline-primary w-100" data-vault-unlock-passkey><i class="fas fa-fingerprint me-2"></i>Unlock with a Passkey</button>
|
||||
<div class="text-center small text-body-secondary my-3">or type your password</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<label class="form-label">Your password <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-lock"></i></span>
|
||||
@@ -128,6 +146,9 @@ if ($itflow_vault_locked) { ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php if ($itflow_vault_passkeys) { ?>
|
||||
<script src="<?= staticFileUrl('/js/passkey.js') ?>"></script>
|
||||
<?php } ?>
|
||||
<?php } ?>
|
||||
<script src="<?= staticFileUrl('/js/credentials.js') ?>"></script>
|
||||
<script src="<?= staticFileUrl('/js/tag_picker.js') ?>"></script>
|
||||
|
||||
@@ -11,8 +11,10 @@
|
||||
* is one of the credential's earlier passwords, fetched the same way.
|
||||
*
|
||||
* After a passkey sign-in that couldn't open the vault, both answer {locked}:
|
||||
* the Unlock window (includes/footer.php) asks for their password, then what
|
||||
* was asked for is tried again. [data-vault-unlock] opens it too.
|
||||
* the Unlock window (includes/footer.php) asks for their password - or a
|
||||
* passkey that opens it (js/passkey.js, which says so with the
|
||||
* itflow:vault-unlocked event) - then what was asked for is tried again.
|
||||
* [data-vault-unlock] opens it too.
|
||||
*/
|
||||
|
||||
(function () {
|
||||
@@ -30,7 +32,9 @@
|
||||
modal.itflowThen = then;
|
||||
bootstrap.Modal.getOrCreateInstance(modal).show();
|
||||
setTimeout(function () {
|
||||
var input = modal.querySelector('[name=password]');
|
||||
// A passkey that opens it first, where there is one (js/passkey.js shows its button)
|
||||
var passkey = modal.querySelector('[data-vault-unlock-passkey-box]:not([hidden]) [data-vault-unlock-passkey]');
|
||||
var input = passkey || modal.querySelector('[name=password]');
|
||||
if (input) {
|
||||
input.focus();
|
||||
}
|
||||
@@ -39,6 +43,17 @@
|
||||
|
||||
var unlockModal = document.getElementById('vaultUnlockModal');
|
||||
if (unlockModal) {
|
||||
// Unlocked - with the password here, or a passkey (js/passkey.js): try again what was asked for, or show the page afresh
|
||||
var unlocked = function () {
|
||||
bootstrap.Modal.getOrCreateInstance(unlockModal).hide();
|
||||
if (document.querySelector('[data-vault-locked]') || typeof unlockModal.itflowThen !== 'function') {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
unlockModal.itflowThen();
|
||||
};
|
||||
unlockModal.addEventListener('itflow:vault-unlocked', unlocked);
|
||||
|
||||
unlockModal.querySelector('[data-vault-unlock-form]').addEventListener('submit', function (e) {
|
||||
e.preventDefault();
|
||||
var form = this;
|
||||
@@ -65,12 +80,7 @@
|
||||
return;
|
||||
}
|
||||
input.value = '';
|
||||
bootstrap.Modal.getOrCreateInstance(unlockModal).hide();
|
||||
if (document.querySelector('[data-vault-locked]') || typeof unlockModal.itflowThen !== 'function') {
|
||||
window.location.reload();
|
||||
return;
|
||||
}
|
||||
unlockModal.itflowThen();
|
||||
unlocked();
|
||||
}).catch(function () {
|
||||
submit.disabled = false;
|
||||
});
|
||||
|
||||
@@ -11,10 +11,20 @@
|
||||
* passkey can open their credentials) gets what to ask the browser for, makes the passkey, and
|
||||
* sends it with the form - its name and their password - as an ordinary post. A passkey that does
|
||||
* PRF but didn't give its secret on being made is asked once more for it, to seal the vault key.
|
||||
*
|
||||
* Unlock: the Unlock window (includes/footer.php) of an agent whose credentials are locked, with a
|
||||
* passkey that opens them, shows [data-vault-unlock-passkey] - it asks for one of those and its secret
|
||||
* (agent/ajax.php, vaultUnlockPasskey()), and says itflow:vault-unlocked to js/credentials.js once open.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// Loaded once - the Security page has it, and so does the Unlock window
|
||||
if (window.itflowPasskeys) {
|
||||
return;
|
||||
}
|
||||
window.itflowPasskeys = true;
|
||||
|
||||
function toBytes(text) {
|
||||
text = String(text || '').replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (text.length % 4) {
|
||||
@@ -296,4 +306,63 @@
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------- Unlock the credentials */
|
||||
|
||||
var unlockModal = document.getElementById('vaultUnlockModal');
|
||||
var unlockButton = unlockModal && unlockModal.querySelector('[data-vault-unlock-passkey]');
|
||||
if (unlockButton && supported()) {
|
||||
var unlockMessage = unlockModal.querySelector('[data-vault-unlock-message]');
|
||||
unlockModal.querySelector('[data-vault-unlock-passkey-box]').hidden = false;
|
||||
|
||||
unlockButton.addEventListener('click', function () {
|
||||
var address = '';
|
||||
showMessage(unlockMessage, '');
|
||||
unlockButton.disabled = true;
|
||||
post('/agent/ajax.php', { vault_unlock_passkey_options: 1, csrf_token: unlockModal.dataset.csrf }).then(function (options) {
|
||||
if (options.error) {
|
||||
throw { message: options.error };
|
||||
}
|
||||
address = options.address;
|
||||
return navigator.credentials.get({
|
||||
publicKey: {
|
||||
challenge: toBytes(options.challenge),
|
||||
rpId: options.rpId,
|
||||
timeout: options.timeout,
|
||||
userVerification: options.userVerification,
|
||||
allowCredentials: options.allowCredentials.map(function (item) {
|
||||
return { type: item.type, id: toBytes(item.id), transports: item.transports };
|
||||
}),
|
||||
extensions: prfExtension(options)
|
||||
}
|
||||
});
|
||||
}).then(function (credential) {
|
||||
var response = credential.response;
|
||||
return post('/agent/ajax.php', {
|
||||
vault_unlock_passkey: 1,
|
||||
csrf_token: unlockModal.dataset.csrf,
|
||||
id: toText(credential.rawId),
|
||||
client_data: toText(response.clientDataJSON),
|
||||
authenticator_data: toText(response.authenticatorData),
|
||||
signature: toText(response.signature),
|
||||
user_handle: toText(response.userHandle),
|
||||
prf: prfOf(credential)
|
||||
});
|
||||
}).then(function (result) {
|
||||
unlockButton.disabled = false;
|
||||
if (!result.unlocked) {
|
||||
throw { message: result.error || 'That passkey didn\'t unlock them - type your password instead.' };
|
||||
}
|
||||
unlockModal.dispatchEvent(new CustomEvent('itflow:vault-unlocked'));
|
||||
}).catch(function (error) {
|
||||
unlockButton.disabled = false;
|
||||
var text = error && error.name ? whyNot(error, address) : ((error && error.message) || 'That passkey didn\'t unlock them - type your password instead.');
|
||||
showMessage(unlockMessage, text, 'warning');
|
||||
var password = unlockModal.querySelector('[name=password]');
|
||||
if (password && text) {
|
||||
password.focus();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* The sign-in page's passkey (functions/passkey.php) - JSON, POST only:
|
||||
* action=options - what to ask the browser for, with a challenge kept in the session
|
||||
* action=verify - the browser's answer, checked. For an agent, the vault is opened with the
|
||||
* passkey's PRF secret where it can be. Then {token}: the page posts it to
|
||||
* passkey's PRF secret where it can be - or the secret kept, to seal a copy of
|
||||
* the vault key to the passkey once the vault opens (passkeySealKeep()). Then {token}: the page posts it to
|
||||
* login.php (passkey_login), which signs them in its usual way, as it does
|
||||
* after a two-step code - a passkey counts as two-step sign-in.
|
||||
* Failures count towards the same lockout as passwords.
|
||||
@@ -127,8 +128,8 @@ $token = bin2hex(random_bytes(32));
|
||||
if (intval($user['user_type']) === 1) {
|
||||
|
||||
// The vault: opened with the passkey's PRF secret when it has a copy and the browser gave one -
|
||||
// otherwise it stays locked until they type their password (vaultUnlock())
|
||||
unset($_SESSION['user_encryption_session_ciphertext'], $_SESSION['user_encryption_session_iv']);
|
||||
// otherwise it stays locked until they type their password (vaultUnlock()) or use a passkey that opens it
|
||||
unset($_SESSION['user_encryption_session_ciphertext'], $_SESSION['user_encryption_session_iv'], $_SESSION['passkey_seal']);
|
||||
$agent_vault = false;
|
||||
$prf = passkeyFromB64url($_POST['prf'] ?? '');
|
||||
if ($passkey['passkey_vault'] !== '' && $prf !== false) {
|
||||
@@ -138,6 +139,12 @@ if (intval($user['user_type']) === 1) {
|
||||
$agent_vault = true;
|
||||
}
|
||||
}
|
||||
// It gave its secret but has no copy that opens with it - added where the browser didn't give the
|
||||
// secret then. Kept until the vault opens this session, which seals a copy to it (passkeySealKept()),
|
||||
// so from the next sign-in it opens the vault itself
|
||||
if (!$agent_vault && $prf !== false && strlen($prf) >= 32 && trim((string) $user['user_specific_encryption_ciphertext']) !== '') {
|
||||
passkeySealKeep($passkey, $prf);
|
||||
}
|
||||
|
||||
$_SESSION['pending_passkey_login'] = [
|
||||
'type' => 'agent',
|
||||
|
||||
@@ -20,6 +20,10 @@ if (isset($_GET['logout'])) {
|
||||
setcookie("user_extension_key", '', time() - 3600, "/");
|
||||
unset($_COOKIE['user_extension_key']);
|
||||
|
||||
// A passkey's secret kept to seal the vault to (passkeySealKeep())
|
||||
setcookie("passkey_seal_key", '', time() - 3600, "/");
|
||||
unset($_COOKIE['passkey_seal_key']);
|
||||
|
||||
session_unset();
|
||||
session_destroy();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user