diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a540d15a..56cc53257 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,29 @@
This file documents all notable changes made to ITFlow.
+## [26.12.3]
+
+### Upgrading to 26.12.3
+
+Update from Maintenance > Update as usual - this release has one database change (4.2.2), which adds a table for passkeys and a setting to turn them on or off. Nothing else is required: passkeys are on, and no one has one until they add it. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again.
+
+### New Features & Updates
+
+- Passkeys: agents and client portal contacts can sign in with a passkey - their fingerprint, face or PIN, with the passkey kept on their computer, their phone, a security key or their password manager - instead of their email and password. They add one, with their password, from Your account > Security (agents) or Your account in the client portal. Then they click Sign in with a passkey on the sign-in page, or pick it as the browser offers it in the email box.
+- Passkeys count as two-step sign-in: signing in with one doesn't ask for an authenticator code, and it meets a role's or the client portal's requirement for two-step sign-in. An agent who signs in with their password still needs their code as before.
+- Passkeys and credentials: a passkey that supports it (most current ones do) also opens an agent's credentials when they sign in with it. One that doesn't still signs them in, but usernames, passwords and 2FA codes are locked - the first one they open asks for their password, once, until they sign out. Each passkey in Your account > Security says which kind it is.
+- Admin > Settings > Security has a Passkeys switch, on. Off, passkeys already added are kept but don't sign anyone in until it's on again.
+- Resetting an agent's MFA (Admin > Users) or turning off a contact's two-step sign-in also removes their passkeys, for a lost or replaced device, and so do archiving an agent and resetting every agent's password. Agents and contacts are emailed when a passkey is added to or removed from their account, failed passkey sign-ins count towards the same lockout as passwords, and both show in the sign-in log.
+
+### Developer Updates
+
+- Database 4.2.2: user_passkeys (each passkey's credential id and the SHA-256 of it to find it by, its public key, signature count, AAGUID, transports, whether it is synced, and for an agent a copy of the vault key sealed by the passkey's PRF output - AES-256-GCM under HKDF-SHA256, bound to the credential), users.user_passkey_handle (the random WebAuthn user handle) and settings.config_login_passkeys.
+- WebAuthn is checked by lbuchs/WebAuthn 2.2.0 (MIT) in libs/webauthn, with user verification required and attestation none; the origin is also matched exactly against config_base_url, as the library only checks the end of the host name. functions/passkey.php holds the challenges (session, five minutes, single use), registration, the sign-in check and the vault copy.
+- Signing in: login_passkey.php answers the options and checks the browser's answer (JSON), then login.php's passkey_login step signs them in through its usual success path - the same as after a two-step code, session regeneration and new-device email included. js/passkey.js draws the button, offers passkeys in the email box (conditional mediation, never retried in a loop) and runs the add forms.
+- A locked vault: vaultLocked() and vaultUnlock(), with get_credential_via_id and get_totp_token_via_id in agent/ajax.php answering {locked}, and js/credentials.js opening the Unlock window (includes/footer.php). New calls: passkey_create_options and vault_unlock in agent/ajax.php; add_your_passkey and delete_your_passkey for agents; passkey_create_options, portal_passkey_add and portal_passkey_remove in client/post.php. The password checks for adding a passkey and unlocking are limited to five wrong ones in ten minutes per account (Password Failed).
+- $_SESSION['signed_in_with'] ('passkey' or 'password') lets includes/load_user_session.php and client/includes/check_login.php leave MFA enforcement out for a passkey sign-in.
+- generateUserSessionKey() reads config.php by its own path, so it works from agent/ as well as the root folder.
+
## [26.12.2]
### Upgrading to 26.12.2
diff --git a/admin/database_updates/4.2.2.php b/admin/database_updates/4.2.2.php
new file mode 100644
index 000000000..ebc2d4894
--- /dev/null
+++ b/admin/database_updates/4.2.2.php
@@ -0,0 +1,49 @@
+ 0;
$form_has_avatar = trim((string) ($form['user_avatar'] ?? '')) !== '';
$form_access = $form_user_id ? userClientAccess([$form_user_id])[$form_user_id] : ['allow' => [], 'deny' => []];
$form_invites = $is_new && userInvitesReady();
@@ -170,7 +173,7 @@ $value = function ($key) use ($form) {
-
For a lost or replaced phone - their authenticator app is forgotten, and so are their remembered browsers.
+
For a lost or replaced phone - their authenticator app is forgotten, and so are their remembered browsers= $form_passkeys ? ' and their ' . ($form_passkeys === 1 ? 'passkey' : "$form_passkeys passkeys") : '' ?>.
diff --git a/admin/post/portal_users.php b/admin/post/portal_users.php
index 68add8368..fd178d87b 100644
--- a/admin/post/portal_users.php
+++ b/admin/post/portal_users.php
@@ -99,6 +99,10 @@ if (isset($_GET['portal_user_reset_mfa'])) {
$row = portalUserForRequest($_GET['portal_user_reset_mfa']);
portalMfaReset($row['user_id']);
+ // Their passkeys count as two-step sign-in, and go too (functions/passkey.php)
+ if (passkeysReady()) {
+ passkeysForget($row['user_id']);
+ }
logAudit("Contact", "Edit", "$session_name turned off two-step sign-in for " . escapeSql($row['contact_name']) . " in the client portal", $row['client_id'], $row['contact_id']);
portalMailAccountChange($row['user_email'], $row['contact_name'], 'mfa_off_by_us');
@@ -198,6 +202,9 @@ if (isset($_POST['bulk_portal_reset_mfa'])) {
continue;
}
portalMfaReset($user_id);
+ if (passkeysReady()) {
+ passkeysForget($user_id);
+ }
logAudit("Contact", "Edit", "$session_name turned off two-step sign-in for " . escapeSql($row['contact_name']) . " in the client portal", $row['client_id'], $row['contact_id']);
portalMailAccountChange($row['user_email'], $row['contact_name'], 'mfa_off_by_us');
$count++;
diff --git a/admin/post/settings_security.php b/admin/post/settings_security.php
index c4d3596fe..591f9001e 100644
--- a/admin/post/settings_security.php
+++ b/admin/post/settings_security.php
@@ -3,8 +3,9 @@
/*
* Admin > Settings > Security (admin/settings_security.php):
* edit_security_settings saves the sign-in page's message and login key, how
- * long a browser is remembered, when admins hear of failed sign-ins, whether
- * the API takes a key in the address, and shared links. A login key required with none set - which would leave
+ * long a browser is remembered, whether passkeys sign people in, when admins
+ * hear of failed sign-ins, whether the API takes a key in the address, and
+ * shared links. A login key required with none set - which would leave
* agents no way in but the database - is refused, as is a key that couldn't
* be typed into an address, or a time out of range. Nothing is saved then.
* A choice not offered settles to the usual one.
@@ -16,8 +17,10 @@ if (isset($_POST['edit_security_settings'])) {
validateCSRFToken();
- $before = settingsCurrent(['config_login_message', 'config_login_key_required', 'config_login_key_secret', 'config_login_remember_me_expire',
- 'config_login_alert_failures', 'config_api_key_in_address', 'config_share_max_hours', 'config_share_require_protection']);
+ $before = settingsCurrent(array_merge(['config_login_message', 'config_login_key_required', 'config_login_key_secret', 'config_login_remember_me_expire',
+ 'config_login_alert_failures', 'config_api_key_in_address', 'config_share_max_hours', 'config_share_require_protection'],
+ // Passkeys, once the database has them (functions/passkey.php)
+ passkeysReady() ? ['config_login_passkeys'] : []));
// What was sent, and what is saved for anything that wasn't - a switch not sent is off
$in = $_POST + array_map(function ($value) { return (string) $value; }, $before);
@@ -32,6 +35,9 @@ if (isset($_POST['edit_security_settings'])) {
'config_share_max_hours' => intval($in['config_share_max_hours']),
'config_share_require_protection' => empty($_POST['config_share_require_protection']) ? 0 : 1,
];
+ if (array_key_exists('config_login_passkeys', $before)) {
+ $after['config_login_passkeys'] = empty($_POST['config_login_passkeys']) ? 0 : 1;
+ }
$errors = [];
if ($after['config_login_key_secret'] !== '' && !preg_match('/^\w{3,99}$/', $after['config_login_key_secret'])) {
diff --git a/admin/post/users.php b/admin/post/users.php
index 5ec11d460..e8fcced19 100644
--- a/admin/post/users.php
+++ b/admin/post/users.php
@@ -285,10 +285,14 @@ if (isset($_POST['edit_user'])) {
$changes[] = 'password changed';
userNotifyChange($name, $email, 'an administrator set a new password');
}
- if (!empty($_POST['reset_mfa']) && trim((string) $row['user_token']) !== '') {
+ if (!empty($_POST['reset_mfa']) && (trim((string) $row['user_token']) !== '' || (passkeysReady() && passkeyCount($user_id)))) {
userResetMfa($user_id);
+ $passkeys_removed = passkeysReady() ? passkeysForget($user_id) : 0;
+ if ($passkeys_removed) {
+ $changes[] = 'passkeys removed';
+ }
$changes[] = 'MFA reset';
- userNotifyChange($name, $email, 'an administrator turned off multi-factor authentication' . ($force_mfa ? ' - you will set it up again at your next sign in' : ''));
+ userNotifyChange($name, $email, 'an administrator turned off multi-factor authentication' . ($passkeys_removed ? ' and removed your passkeys' : '') . ($force_mfa ? ' - you will set it up again at your next sign in' : ''));
}
if (strcasecmp($email, $row['user_email']) !== 0) {
$changes[] = 'email changed';
@@ -388,9 +392,11 @@ if (isset($_GET['reset_user_mfa'])) {
$user_id = intval($row['user_id']);
userResetMfa($user_id);
- userNotifyChange($row['user_name'], $row['user_email'], 'an administrator turned off multi-factor authentication' . (intval($row['user_config_force_mfa']) ? ' - you will set it up again at your next sign in' : ''));
+ // Their passkeys count as MFA, and go too (functions/passkey.php)
+ $passkeys_removed = passkeysReady() ? passkeysForget($user_id) : 0;
+ userNotifyChange($row['user_name'], $row['user_email'], 'an administrator turned off multi-factor authentication' . ($passkeys_removed ? ' and removed your passkeys' : '') . (intval($row['user_config_force_mfa']) ? ' - you will set it up again at your next sign in' : ''));
- logAudit("User", "Edit", "$session_name reset MFA for user " . escapeSql($row['user_name']), 0, $user_id);
+ logAudit("User", "Edit", "$session_name reset MFA for user " . escapeSql($row['user_name']) . ($passkeys_removed ? " and removed their passkeys" : ''), 0, $user_id);
flashAlert("MFA reset for " . $row['user_name'] . "" . (intval($row['user_config_force_mfa']) ? ' - they set it up again at their next sign in' : ' - they sign in with their password alone until they turn it on'));
@@ -418,6 +424,9 @@ if (isset($_POST['archive_user'])) {
$scrambled = escapeSql(password_hash(randomString(), PASSWORD_DEFAULT));
mysqli_query($mysqli, "UPDATE users SET user_name = '$archived_name', user_password = '$scrambled', user_status = 0, user_specific_encryption_ciphertext = '', user_archived_at = NOW() WHERE user_id = $user_id");
mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_user_id = $user_id");
+ if (passkeysReady()) {
+ passkeysForget($user_id);
+ }
logAudit("User", "Archive", "$session_name archived user " . escapeSql($row['user_name']), 0, $user_id);
@@ -653,12 +662,15 @@ if (isset($_POST['ir_reset_user_password'])) {
while ($row = mysqli_fetch_assoc($sql_users)) {
$new_password = generateReadablePassword(4);
userSetPassword($row['user_id'], $new_password);
- // A remembered browser would skip their MFA code - in an incident, it must not
+ // A remembered browser would skip their MFA code, and a passkey their password - in an incident, neither must
mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_user_id = " . intval($row['user_id']));
+ if (passkeysReady()) {
+ passkeysForget($row['user_id']);
+ }
$reset[] = $row + ['password' => $new_password];
}
- logAudit("User", "Edit", "$session_name reset the passwords of " . count($reset) . " agent(s) and forgot their remembered browsers (incident response)");
+ logAudit("User", "Edit", "$session_name reset the passwords of " . count($reset) . " agent(s) and forgot their remembered browsers and passkeys (incident response)");
// Shown once, not kept - a plain page to read out or copy, and nothing else on it
header('Cache-Control: no-store');
diff --git a/admin/settings_security.php b/admin/settings_security.php
index c33828a65..f3d8db543 100644
--- a/admin/settings_security.php
+++ b/admin/settings_security.php
@@ -3,8 +3,8 @@
/*
* Admin > Settings > Security - the sign-in page (its message, and a login
* key agents need in its address), how long two-step sign-in remembers a
- * device, when admins hear of failed sign-ins, whether the API takes a key in
- * the address, and shared links. Saved by
+ * device, whether passkeys sign people in, when admins hear of failed sign-ins,
+ * whether the API takes a key in the address, and shared links. Saved by
* edit_security_settings (admin/post/settings_security.php).
*/
@@ -13,6 +13,10 @@ require_once "includes/inc_all_admin.php";
// Read here rather than with every page's settings, so a page still opens before the update that adds it
$config_login_alert_failures = signInAlertLimit();
$config_api_key_in_address = apiKeyInAddressAccepted() ? 1 : 0;
+// Passkeys, once the database has them (functions/passkey.php)
+$passkeys_ready = passkeysReady();
+$config_login_passkeys = passkeysOn() ? 1 : 0;
+$passkey_address = passkeyRp()['address'];
$login_url = rtrim('https://' . preg_replace('#^https?://#', '', (string) $config_base_url), '/') . '/login.php?key=';
$login_key_shown = (string) settingsValue('config_login_key_secret', $config_login_key_secret);
@@ -44,6 +48,12 @@ echo settingsPageStart('security');
'suffix' => 'days', 'help' => 'Each agent can see and forget their remembered browsers in their own Security settings.']) ?>
= settingsSectionEnd() ?>
+
+ = settingsSectionStart('passkeys', 'Passkeys', 'A passkey signs an agent or a client contact in with their fingerprint, face or PIN instead of their password, and counts as two-step sign-in. Each adds their own from their account, with their password. Passkeys are made for ' . escapeHtml($passkey_address) . ' - moving ITFlow to another address means adding them again.') ?>
+ = settingsSwitch('config_login_passkeys', $config_login_passkeys, ['help' => 'Off, passkeys already added are kept, but don\'t sign anyone in until it is on again.']) ?>
+ = settingsSectionEnd() ?>
+
+
= settingsSectionStart('failed', 'Failed sign-ins', 'Counted over ' . SIGN_IN_WINDOW_MINUTES . ' minutes, from one address or against one account. An address is turned away after ' . SIGN_IN_LOCKOUT . ', whatever is set here.') ?>
= settingsSelect('config_login_alert_failures', intval($config_login_alert_failures), signInAlertOptions(), ['icon' => 'fa-bell',
'help' => 'Each admin gets a notification and an email.']) ?>
diff --git a/admin/users.php b/admin/users.php
index ae750b9a2..990d25d2a 100644
--- a/admin/users.php
+++ b/admin/users.php
@@ -32,6 +32,8 @@ if (($_GET['canned_date'] ?? '') === 'custom' && empty($_GET['dtf'])) {
}
$roles = userRoles();
+// Who has passkeys - resetting two-step sign-in takes them away too (functions/passkey.php)
+$passkey_counts = passkeyCounts();
$role_filter = isset($roles[intval($_GET['role'] ?? 0)]) ? intval($_GET['role']) : 0;
// The search is for the side being looked at - agents and their invites, or portal users - and leaves the other side's counts alone
@@ -435,6 +437,7 @@ $csrf = $_SESSION['csrf_token'];
$is_on = $off_why === '';
$is_local = $row['user_auth_method'] === 'local';
$has_mfa = trim((string) $row['user_token']) !== '';
+ $has_passkeys = !empty($passkey_counts[$user_id]);
$can_turn_on = !$is_on && empty($row['client_archived_at']) && empty($row['contact_archived_at']);
$name = escapeHtml($row['contact_name']);
$contact_url = "/agent/contact.php?client_id=$client_id&contact_id=$contact_id";
@@ -515,9 +518,9 @@ $csrf = $_SESSION['csrf_token'];
-
+
Turn Off Two-step Sign-in
@@ -694,6 +697,7 @@ $csrf = $_SESSION['csrf_token'];
$is_active = intval($row['user_status']) === 1 && !$is_archived;
$is_admin = intval($row['role_is_admin']) === 1;
$has_mfa = trim((string) $row['user_token']) !== '';
+ $has_passkeys = !empty($passkey_counts[$user_id]);
$display_name = $is_archived ? trim(str_replace(' (archived)', '', $row['user_name'])) : $row['user_name'];
$name = escapeHtml($display_name);
$quick_url = "modals/user/user.php?id=$user_id";
@@ -788,9 +792,9 @@ $csrf = $_SESSION['csrf_token'];
Edit
-
+
Reset MFA
diff --git a/agent/ajax.php b/agent/ajax.php
index 5028d117e..6df62de23 100644
--- a/agent/ajax.php
+++ b/agent/ajax.php
@@ -27,6 +27,38 @@ if (isset($_POST['invoice_bulk_set'])) {
exit;
}
+/*
+ * Adding a passkey in Your account > Security (js/passkey.js, functions/passkey.php): their password
+ * checked first, so a typo doesn't leave a passkey on their device that doesn't work here - then
+ * what to ask the browser for. The passkey itself comes back with the form, to add_your_passkey.
+ */
+if (isset($_POST['passkey_create_options'])) {
+ validateCSRFToken();
+ header('Content-Type: application/json');
+ if (!passkeysOn()) {
+ http_response_code(403);
+ exit(json_encode(['error' => 'Passkeys are turned off.']));
+ }
+ [$password_ok, $password_message, $me] = passkeyPasswordCheck($session_user_id, (string) ($_POST['current_password'] ?? ''), 'add a passkey');
+ if (!$password_ok) {
+ exit(json_encode(['error' => $password_message]));
+ }
+ echo json_encode(passkeyCreateOptions($session_user_id, $me['user_email'], $me['user_name']));
+ exit;
+}
+
+/*
+ * Unlocking the credentials with your password - after a passkey sign-in that couldn't open the
+ * vault (vaultUnlock()). The vault session's cookie comes back with the answer.
+ */
+if (isset($_POST['vault_unlock'])) {
+ validateCSRFToken();
+ header('Content-Type: application/json');
+ [$unlocked, $unlock_message] = vaultUnlock($session_user_id, (string) ($_POST['password'] ?? ''));
+ echo json_encode($unlocked ? ['unlocked' => true] : ['error' => $unlock_message]);
+ exit;
+}
+
/*
* The host in a New / Edit Certificate form, checked when asked: connect,
* take the certificate it serves and say what it is - OK, for another name,
@@ -1930,6 +1962,11 @@ if (isset($_GET['get_totp_token_via_id'])) {
enforceUserPermission('module_credential');
+ // Signed in with a passkey that couldn't open the vault - their password unlocks it (js/credentials.js)
+ if (vaultLocked()) {
+ exit(json_encode(['locked' => true]));
+ }
+
$credential_id = intval($_GET['credential_id']);
$sql = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT credential_name, credential_otp_secret, credential_client_id FROM credentials WHERE credential_id = $credential_id"));
@@ -3002,6 +3039,11 @@ if (isset($_GET['get_credential_via_id'])) {
enforceUserPermission('module_credential');
+ // Signed in with a passkey that couldn't open the vault - their password unlocks it (js/credentials.js)
+ if (vaultLocked()) {
+ exit(json_encode(['locked' => true]));
+ }
+
$credential_id = intval($_GET['credential_id']);
$sql = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT credential_name, credential_username, credential_password, credential_client_id FROM credentials WHERE credential_id = $credential_id"));
diff --git a/agent/contact.php b/agent/contact.php
index 9a181354f..5dcbda72d 100644
--- a/agent/contact.php
+++ b/agent/contact.php
@@ -68,6 +68,8 @@ $contact_mobile_copy = escapeHtml(formatPhoneNumber($row['contact_mobile'], $row
$contact_dial = $row['contact_phone'] ? 'phone' : ($row['contact_mobile'] ? 'mobile' : '');
$contact_portal = contactPortalAccess($row['contact_user_id'], $row['user_auth_method']);
$contact_portal_mfa = $contact_portal === 'Password' && trim((string) $row['user_token']) !== '';
+// Their passkeys count as two-step sign-in (functions/passkey.php)
+$contact_portal_passkeys = $contact_portal === 'Password' && passkeysReady() ? passkeyCount($row['contact_user_id']) : 0;
$contact_portal_last = $contact_portal ? portalContactLastSignIn($row['contact_user_id']) : null;
// How they joined, when it was by an invite or signing up (functions/portal_invite.php)
$contact_portal_joined = $contact_portal ? portalContactJoined($contact_id) : null;
@@ -412,20 +414,20 @@ if (!$can_support) {
Portal
- = $contact_portal ? "Can log in · $contact_portal" . ($contact_portal_mfa ? ' and a code' : '') . "" : 'No access' ?>
+ = $contact_portal ? "Can log in · $contact_portal" . ($contact_portal_mfa ? ' and a code' : '') . ($contact_portal_passkeys ? ', or a passkey' : '') . "" : 'No access' ?>
= $contact_portal_last ? 'Last signed in ' . timeAgo($contact_portal_last) . '' : 'Has not signed in yet' ?>
+ None yet. A passkey signs you in with your fingerprint, face or PIN instead of your password - kept on this device, your phone, a security key or your password manager. It counts as multi-factor authentication, and where it can, it opens your credentials too.
+
+
+
+
+
+
@@ -165,6 +207,11 @@ $remember_days = max(1, intval($config_login_remember_me_expire));
require_once "modals/user_mfa_modal.php";
} ?>
+
+
+
+
+Locked';
+ }
if ($username === '') {
return '' . $empty . '';
}
diff --git a/functions/email_preview.php b/functions/email_preview.php
index a45c8da27..87cbb7ac2 100644
--- a/functions/email_preview.php
+++ b/functions/email_preview.php
@@ -350,6 +350,14 @@ function emailPreviewCatalog() {
'run' => function ($s) {
portalMailAccountChange($s['alex_email'], $s['alex_name'], 'mfa_off_by_us');
}],
+ 'portal_passkey_added' => ['group' => 'Client portal', 'label' => 'Passkey added', 'to' => 'The contact', 'when' => 'They add a passkey in Your account',
+ 'run' => function ($s) {
+ portalMailAccountChange($s['alex_email'], $s['alex_name'], 'passkey_added');
+ }],
+ 'portal_passkey_removed' => ['group' => 'Client portal', 'label' => 'Passkey removed', 'to' => 'The contact', 'when' => 'They remove a passkey in Your account',
+ 'run' => function ($s) {
+ portalMailAccountChange($s['alex_email'], $s['alex_name'], 'passkey_removed');
+ }],
// ---- Shared links
'share_link' => ['group' => 'Shared links', 'label' => 'Secure link', 'to' => 'Whoever it is for', 'when' => 'An agent shares something and asks to email the link',
diff --git a/functions/passkey.php b/functions/passkey.php
new file mode 100644
index 000000000..c83b5c057
--- /dev/null
+++ b/functions/passkey.php
@@ -0,0 +1,457 @@
+ 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 (lbuchs/WebAuthn, 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 \lbuchs\WebAuthn\WebAuthn($rp['name'], $rp['id'], null, 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, false, false);
+ } 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 ' . escapeHtml(timeAgo($passkey['passkey_used_at'])) . '' : '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, ''];
+}
+
+/** The note in a credential window while the vault is locked - with the button that unlocks it (js/credentials.js). */
+function vaultLockedAlertHtml() {
+ return '
'
+ . 'Your credentials are locked - you signed in with a passkey that can\'t open them.'
+ . '
';
+}
+
+/** 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;
+}
diff --git a/functions/portal.php b/functions/portal.php
index af169bf11..53d4c71d6 100644
--- a/functions/portal.php
+++ b/functions/portal.php
@@ -285,7 +285,8 @@ function portalAccountEmail($email, $name, $subject, $intro, $button = null) {
/*
* Tell a contact their portal account changed - $change: password (changed
* in Your account), password_link (set from an emailed link), mfa_on, mfa_off
- * (by them), mfa_off_by_us (an agent turned it off). False when it can't go.
+ * (by them), mfa_off_by_us (an agent turned it off, and took any passkeys),
+ * passkey_added, passkey_removed (by them). False when it can't go.
*/
function portalMailAccountChange($email, $name, $change) {
$company = (string) (billingCompany()['company_name'] ?? '');
@@ -294,7 +295,9 @@ function portalMailAccountChange($email, $name, $change) {
'password_link' => ["Your $company client portal password was changed", ["The password for your $company client portal account ($email) was just set from an emailed link.", 'If that was you, there is nothing more to do.']],
'mfa_on' => ['Two-step sign-in is on for your client portal account', ["Signing in to the $company client portal now asks for a code from your authenticator app, as well as your password.", 'Lost your phone? Ask us and we will reset it.']],
'mfa_off' => ['Two-step sign-in is off for your client portal account', ["Signing in to the $company client portal now asks for your password alone.", 'You can turn two-step sign-in back on from Your account.']],
- 'mfa_off_by_us' => ['Two-step sign-in was turned off for your client portal account', ['We turned off two-step sign-in for your client portal account, so it asks only for your password now.', 'You can turn it back on from Your account in the portal.']],
+ 'mfa_off_by_us' => ['Two-step sign-in was turned off for your client portal account', ['We turned off two-step sign-in for your client portal account, and took away any passkeys, so it asks only for your password now.', 'You can turn it back on, and add passkeys again, from Your account in the portal.']],
+ 'passkey_added' => ['A passkey was added to your client portal account', ["A passkey was just added to your $company client portal account, from Your account - it signs you in without your password.", 'If that was you, there is nothing more to do. If it wasn\'t, change your password and remove the passkey from Your account.']],
+ 'passkey_removed' => ['A passkey was removed from your client portal account', ["A passkey was just removed from your $company client portal account, from Your account - it no longer signs you in.", 'If that was you, there is nothing more to do.']],
];
if (!isset($changes[$change])) {
return false;
diff --git a/functions/security.php b/functions/security.php
index bf4dccab6..fc812cb8b 100644
--- a/functions/security.php
+++ b/functions/security.php
@@ -213,8 +213,11 @@ function generateUserSessionKey($site_encryption_master_key) {
$_SESSION['user_encryption_session_ciphertext'] = $user_encryption_session_ciphertext;
$_SESSION['user_encryption_session_iv'] = base64_encode($user_encryption_session_iv);
- // Give the user "their" key as a cookie
- include 'config.php';
+ // Give the user "their" key as a cookie - by config.php's own path, as this also runs from agent/ (vaultUnlock())
+ global $config_https_only;
+ if (!isset($config_https_only)) {
+ include __DIR__ . '/../config.php';
+ }
if ($config_https_only) {
setcookie("user_encryption_session_key", base64_encode($user_encryption_session_key), ['path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
diff --git a/functions/settings.php b/functions/settings.php
index 548dfc60d..26855eacf 100644
--- a/functions/settings.php
+++ b/functions/settings.php
@@ -62,7 +62,7 @@ function settingsPages() {
'notification' => ['group' => 'email', 'title' => 'Notifications', 'icon' => 'fa-bell', 'url' => 'settings_notification.php',
'about' => 'Which alerts ITFlow raises, what it tells your agents about their tickets, and which emails and texts clients get.'],
'security' => ['group' => 'access', 'title' => 'Security', 'icon' => 'fa-shield-alt', 'url' => 'settings_security.php',
- 'about' => 'The sign-in page, two-step sign-in, failed sign-ins, API keys and shared links.'],
+ 'about' => 'The sign-in page, two-step sign-in, passkeys, failed sign-ins, API keys and shared links.'],
'client_portal' => ['group' => 'access', 'title' => 'Client Portal', 'icon' => 'fa-user-shield', 'url' => 'settings_client_portal.php', 'module' => 'portal',
'about' => 'How your clients\' contacts sign in to the portal, and the announcements they see there.'],
'identity' => ['group' => 'access', 'title' => 'Single Sign-on', 'icon' => 'fa-fingerprint', 'url' => 'identity_providers.php', 'module' => 'portal',
@@ -411,6 +411,7 @@ function settingsFields() {
'config_login_key_required' => ['page' => 'security', 'section' => 'The sign-in page', 'label' => 'Require a login key', 'words' => 'login key secret url hide sign in'] + $on_off,
'config_login_key_secret' => ['page' => 'security', 'section' => 'The sign-in page', 'label' => 'Login key', 'quiet' => true, 'words' => 'login key secret url address'],
'config_login_remember_me_expire' => ['page' => 'security', 'section' => 'Two-step sign-in', 'label' => 'Remember a browser for', 'words' => '2fa mfa remember me days trusted device'],
+ 'config_login_passkeys' => ['page' => 'security', 'section' => 'Passkeys', 'label' => 'Sign in with passkeys', 'words' => 'passkey passkeys webauthn fido2 fingerprint face pin passwordless security key yubikey'] + $on_off,
'config_login_alert_failures' => ['page' => 'security', 'section' => 'Failed sign-ins', 'label' => 'Tell admins', 'kind' => 'select', 'options' => 'sign_in_alerts', 'words' => 'failed login brute force lockout alert'],
'config_api_key_in_address' => ['page' => 'security', 'section' => 'API keys', 'label' => 'Take API keys in the address', 'words' => 'api key address url query string api_key header x-api-key access log'] + $on_off,
'config_share_max_hours' => ['page' => 'security', 'section' => 'Shared links', 'label' => 'Longest a shared link can last', 'kind' => 'select', 'options' => 'share_max', 'words' => 'share link expiry guest'],
diff --git a/includes/footer.php b/includes/footer.php
index 86638d1c0..47104e4d1 100644
--- a/includes/footer.php
+++ b/includes/footer.php
@@ -94,6 +94,40 @@ try {
+
+
+
+
+
+
Unlock Your Credentials
+
+
+
+
+
You signed in with a passkey that can't open the credential vault, so usernames, passwords and 2FA codes are locked. Type your password to unlock them until you sign out.
";
+ } else {
+ $email = escapeSql($sess['email'] ?? '');
+ $email_raw = (string) ($sess['email'] ?? '');
+ $role_choice = ($sess['type'] ?? 'agent') === 'client' ? 'client' : 'agent';
+ $passkey_name = escapeSql(mb_substr((string) ($sess['passkey_name'] ?? 'Passkey'), 0, PASSKEY_NAME_MAX));
+ }
+ }
+
// -----------------------------------
// STEP 1: INITIAL CREDENTIALS
// -----------------------------------
@@ -246,9 +274,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_
$allowed_client_id = isset($sess['client_user_id']) ? intval($sess['client_user_id']) : null;
}
- if ($is_mfa_step) {
- $sess = $_SESSION['pending_mfa_login'] ?? null;
- // Only the account whose password was checked - the other kind is left out altogether (-1 matches no one)
+ if ($is_mfa_step || $is_passkey_step) {
+ $sess = $_SESSION[$is_passkey_step ? 'pending_passkey_login' : 'pending_mfa_login'] ?? null;
+ // Only the account whose password (or passkey) was checked - the other kind is left out altogether (-1 matches no one)
if (($sess['type'] ?? 'agent') === 'client') {
$allowed_client_id = intval($sess['client_user_id'] ?? 0);
$allowed_agent_id = -1;
@@ -442,6 +470,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_
$extended_log = 'with MFA';
}
+ // A passkey is two-step sign-in in itself - the device, unlocked with their PIN, fingerprint or face
+ if ($is_passkey_step) {
+ $mfa_is_complete = true;
+ $extended_log = "with a passkey ($passkey_name)";
+ }
+
if ($mfa_is_complete) {
// Remember me token creation
@@ -495,24 +529,29 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_
$_SESSION['logged'] = true;
// A later password change ends this session (userSessionStamp())
$_SESSION['user_session_stamp'] = userSessionStamp($selectedRow['user_password'] ?? '');
+ // A passkey sign-in is two-step already - MFA enforcement leaves it be (includes/load_user_session.php)
+ $_SESSION['signed_in_with'] = $is_passkey_step ? 'passkey' : 'password';
- if ($force_mfa == 1 && $token == NULL) {
+ $mfa_to_set_up = $force_mfa == 1 && $token == NULL && !$is_passkey_step;
+ if ($mfa_to_set_up) {
$config_start_page = "user/mfa_enforcement.php";
}
// The vault session WITHOUT PASSWORD IN SESSION - opened at step 1, while the password was here (vaultSignIn()).
// After the role choice or two-step code it is already there; signing straight in, it is opened now.
- if (!$is_mfa_step && !$is_role_step) {
+ // With a passkey it was opened by login_passkey.php, when the passkey could - or is unlocked later (vaultUnlock()).
+ if (!$is_mfa_step && !$is_role_step && !$is_passkey_step) {
vaultSignIn($user_id, $user_encryption_ciphertext, $password);
}
// NOW safe to clear pending sessions AFTER we used them
unset($_SESSION['pending_mfa_login']);
unset($_SESSION['pending_dual_login']);
+ unset($_SESSION['pending_passkey_login']);
// A new install's first admin is walked through what is left to set up, once (functions/getting_started.php) -
// after MFA enforcement, and not instead of a page they were on their way to
- if (!($force_mfa == 1 && $token == NULL) && !isset($_GET['last_visited']) && gettingStartedFirstVisit($user_id)) {
+ if (!$mfa_to_set_up && !isset($_GET['last_visited']) && gettingStartedFirstVisit($user_id)) {
redirect('admin/getting_started.php');
}
@@ -616,8 +655,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_
// a remembered browser, or a code from their app. Wrong codes are
// counted per account, as an agent's are.
$client_mfa_secret = trim((string) ($selectedRow['user_token'] ?? ''));
- $client_mfa_done = $client_mfa_secret === '';
- $client_mfa_how = '';
+ // A passkey is two-step sign-in in itself
+ $client_mfa_done = $client_mfa_secret === '' || $is_passkey_step;
+ $client_mfa_how = $is_passkey_step ? " with a passkey ($passkey_name)" : '';
$client_mfa_locked = false;
$client_code = preg_replace('/\s+/', '', (string) ($_POST['current_code'] ?? ''));
if (!preg_match('/^[0-9]{6}$/', $client_code)) {
@@ -693,6 +733,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_
$_SESSION['user_type'] = 2;
$_SESSION['contact_id'] = $contact_id;
$_SESSION['login_method'] = "local";
+ $_SESSION['signed_in_with'] = $is_passkey_step ? 'passkey' : 'password';
// A later password change ends this session (userSessionStamp())
$_SESSION['user_session_stamp'] = userSessionStamp($selectedRow['user_password'] ?? '');
@@ -708,6 +749,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_
// and the vault a dual-role user's password opened, as they went on as the client
unset($_SESSION['pending_dual_login']);
unset($_SESSION['pending_mfa_login']);
+ unset($_SESSION['pending_passkey_login']);
unset($_SESSION['portal_view_as']);
unset($_SESSION['user_encryption_session_ciphertext'], $_SESSION['user_encryption_session_iv']);
@@ -824,6 +866,7 @@ $show_login_form = (!$show_role_choice && !$show_mfa_form);
placeholder=""
name="email"
value="= htmlspecialchars($email ?? '', ENT_QUOTES) ?>"
+ = $config_login_passkeys === 1 ? 'autocomplete="username webauthn"' : 'autocomplete="username"' ?>
required autofocus
>