From eed334aaa425d45dca00ee445e4e8c14755131e4 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Fri, 27 Nov 2026 14:17:06 -0500 Subject: [PATCH] Credential vault: each agent's and API key's copy of the master key is sealed with AES-256-GCM under a 600,000 round PBKDF2-SHA256 key with its full 256 bits instead of a 64 bit key, old copies still read and moved to the new format at the next sign-in or API call, Admin > Backup lists the copies still in the old format with a button to retire them; sign-in no longer keeps the plain master key in the session between the password and two-step steps, which also fixes the vault being closed after a mistyped two-step code; 26.12.2 changelog entries --- CHANGELOG.md | 7 +- admin/backup.php | 28 +++++++ admin/post/api_keys.php | 4 + admin/post/backup.php | 32 ++++++++ functions/security.php | 160 ++++++++++++++++++++++++++++++++-------- functions/user.php | 4 +- login.php | 67 +++++------------ 7 files changed, 222 insertions(+), 80 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 28826d632..3093393aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,14 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's four database changes (4.1.8 to 4.2.1) in the same pass. They add a table for the problems of instances you manage and two settings for which of them open tickets, and a table for each instance's history with columns for its usage, and make room for a credential's 2FA key to be kept encrypted. Nothing else is required - the 2FA keys already saved are encrypted the first time an agent opens ITFlow after the update. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's four database changes (4.1.8 to 4.2.1) in the same pass. They add a table for the problems of instances you manage and two settings for which of them open tickets, and a table for each instance's history with columns for its usage, and make room for a credential's 2FA key to be kept encrypted. Nothing else is required - the 2FA keys already saved are encrypted the first time an agent opens ITFlow after the update, and each agent's copy of the credential vault's key is sealed more strongly the next time they sign in (see Security). If you manage other ITFlow installs, the manager and its instances can be updated in either order. An instance sends its check-ins encoded only once both are on this version, so a web application firewall in front of the manager may need its exclusion for check-ins until then. An instance shows its agents and error categories once it is updated. Each instance's history starts with its first check-in after the manager is updated - there is none from before - and its usage once the instance is updated too. ### Security +- Credential vault: each agent's and API key's copy of the vault's key was sealed under a key worked out from their password that was only 64 bits long, so someone with a copy of the database could find it without going through the password's 100,000 rounds. Copies are now sealed with AES-256 under the full 256 bits of a 600,000-round key. Each moves to it by itself - an agent's the next time they sign in, an API key's on its next call that reads credentials - and Admin > Backup lists those still sealed the old way, with a button to retire them. Signing in, and an API call that reads or writes credentials, takes about half a second longer. +- Signing in: between the password and the two-step code, or the choice between the agent and client portal, the vault's key was kept unencrypted in the server's session - and left there when the sign-in wasn't finished. It's now kept encrypted, the way a signed-in session keeps it. - Credentials: a login's 2FA secret key was stored as it was typed, while its username and password were encrypted, so anyone with a copy of the database could make its 2FA codes. It's now encrypted with the same vault key. The keys already saved are encrypted the first time an agent opens ITFlow after the update. Everything that uses the key works as before - the code on the credential, the Edit window, shared links, exports and the API, which gives it decrypted as it gives the password. A shared link made before 2.9.0 stops showing its 2FA code once the key is encrypted, as a guest has no vault to open it with. ### New Features & Updates @@ -26,6 +28,7 @@ If you manage other ITFlow installs, the manager and its instances can be update ### Bug Fixes +- Signing in: after a mistyped two-step code, the right one signed the agent in with the credential vault closed - every username and password showed blank until they signed out and back in. - Managed Instances: a manager behind a web application firewall - ModSecurity with the OWASP Core Rule Set, say - could answer an instance's check-ins with 403, as the cron command and error text in its report looked like an attack, and the instance's Managed By page said "The manager answered 403". Check-ins are now sent encoded, so nothing needs excluding. An instance sends them that way once its manager says it reads them, and a manager still reads a plain check-in, so either side can be updated first. - Racks: on a rack's drawing, clicking an asset opens its page, and the pen for editing it there - to move it or take it out of the rack - only showed while you pointed at it, at the far right. It was easy to miss, and on a touch screen it never showed. The pen is now always on each asset, in a holder's slot too when the slot is wide enough, and an asset's own page has Edit or remove under Rack, in Where & who. - Interfaces: adding several ports at once dropped the space at the end of the name before the number, so Port 01, Port 02 were made as Port01, Port02 - though the window showed them with the space. They are now made as the window shows them. @@ -48,6 +51,8 @@ If you manage other ITFlow installs, the manager and its instances can be update - Database 4.2.0: `managed_instance_stats` gets a column for each of `MANAGED_USAGE_FIGURES`, `_api_keys` (JSON) and `_agents_30d`, all NULL for a day nothing was reported. Re-runnable. `managedStatsRecord()` writes each of the instance's days onto the row of the same date, when it is there and within three days, and `_agents_30d` onto today's; `managedUsageReady()` guards it. `managedInstanceHistory()` adds each day's figures, `usage` (their totals, or null), `api_keys` and `agents_30d`, and the weekly view adds the figures up - `agent_signins` taking the week's highest day. - `admin/managed_instances.php` reads each instance's last 30 days in one query, and sorts by tickets opened in them as `usage_tickets` - a sort key keeps to letters and underscores, as `filter_header.php` strips anything else. The Health column wraps, so the table fits. - Payment reminders: `cron/nightly_tasks.php` gathers each client's late invoices and reminds them once, when `billingReminderOnDay()` is true for the oldest one's days late - `billingOverdueEmail()` from `billingStatement()` with two or more late, and the invoice's own reminder with one. Each invoice in it gets a `Reminder emailed` history line, so the once-a-day check still holds. `billingReminderNext()` returns `with_others` and counts late days from `billingReminderClientOldestDue()`. `smsClientOverdueNotify()` sends the combined text, and `billingStatementLines()` builds the invoice rows for statements and the combined reminder. +- Vault key copies: `setupFirstUserSpecificKey()` writes `VAULT_WRAP_FORMAT` (`v2:`) and then base64 of a 16 byte salt, 12 byte nonce, 16 byte GCM tag and the ciphertext - AES-256-GCM under `hash_pbkdf2('sha256', ..., VAULT_WRAP_ITERATIONS (600000), 32, true)`, the prefix as AAD. `decryptUserSpecificKey()` reads both formats and keeps what it opened for the rest of the request, so an API call derives the key once. `encryptUserSpecificKey()` returns false when the session's vault doesn't open - `userSetPassword()` then writes no copy, and a new API key is refused. `vaultSignIn($user_id, $ciphertext, $password)` opens the copy, rewrites an old-format one (checked to open, and only over the value read) and starts the vault session; `apiDecryptPasswordOpens()` rewrites an API key's the same way. `vaultWrapIsLegacy()` and `vaultCopies()` (Admin > Backup) tell them apart, and `retire_old_vault_copies` (admin/post/backup.php) blanks the old ones, only for an admin whose own copy is current. +- Sign-in steps: `login.php` opens the vault at the password step with `vaultSignIn()`, so the vault session is in place before the role choice or two-step code. `pending_dual_login` and `pending_mfa_login` carry `agent_vault` (whether it opened) instead of `agent_master_key`, a retried code keeps it, and going on as the client drops the vault session. - Settings pages: a `settingsPages()` entry with `'under' => ''` is a tab of that `adminNavGroups()` entry - `settingsPageStart()` draws the group's tabs above it with no link back to Settings, and it isn't in the Settings menu or overview. Find a setting gives where it is as that entry - "Logs › Settings › ..." - and the top bar search the same. Log Settings (`settings_logs.php`) is the first, under `logs`. - 2FA keys: database 4.2.1 makes `credentials.credential_otp_secret` `varchar(500)`. A key is stored as `CREDENTIAL_OTP_VAULT` (`vault:`) and then what `encryptCredentialEntry()` gives - store one with `credentialOtpEncrypt()` (false when the vault isn't open) or `apiCredentialOtpEncrypt()`, and read it with `credentialOtpSecret()` or `apiCredentialOtpSecret()`. A value without the prefix was saved before and is read as it is. `credentialOtpVaultStored()`, from `includes/check_login.php`, encrypts those once a session, 500 at a time. It runs only when `vaultSessionOpens()` (the session's master key decrypts to 16 characters), checks that each decrypts back, and writes it only over the value it read. `credentialOtpSeed()` refuses a seed over 256 characters, so an encrypted one always fits. Pre-2.9.0 credential shares, which read the key live, show no code for an encrypted key. diff --git a/admin/backup.php b/admin/backup.php index ddd77635c..10f6ccf13 100644 --- a/admin/backup.php +++ b/admin/backup.php @@ -42,6 +42,11 @@ $schedule_on = !empty($backup_job) && intval($backup_job['cron_job_enabled']) == $schedule_time = substr((string) ($backup_job['cron_job_daily_at'] ?? ''), 0, 5); $backup_job_id = intval($backup_job['cron_job_id'] ?? 0); +// The copies of the vault's key - each agent's and API key's - and which are still in the old format (functions/security.php) +$vault = vaultCopies(); +$vault_old = count($vault['users']) + count($vault['keys']); +$vault_own_current = !vaultWrapIsLegacy(getFieldById('users', $session_user_id, 'user_specific_encryption_ciphertext')); + // The newest finished backup of each kind cron can make - the vault's key isn't a backup $latest = []; foreach (backupUnattendedTypes() as $type) { @@ -675,6 +680,29 @@ $config_dev_mail_to = ' Export the Master Key + +
+

Copies of the key

+

Each agent and each API key with access to credentials has its own copy, sealed under its password with AES-256. + of sealed the current way. + The rest are sealed the weaker way from before, and move on by themselves - an agent's the next time they sign in, an API key's on its next call that reads credentials. +

+ + + + + Retire the Old Copies + + + diff --git a/admin/post/api_keys.php b/admin/post/api_keys.php index 1e6cc1f6f..004cd5e41 100644 --- a/admin/post/api_keys.php +++ b/admin/post/api_keys.php @@ -24,6 +24,10 @@ if (isset($_POST['add_api_key'])) { // Credential decryption password $apikey_specific_encryption_ciphertext = encryptUserSpecificKey($password); + if ($apikey_specific_encryption_ciphertext === false) { + flashAlert('Your vault session has expired, so the key could not be given access to credentials - sign out and back in, then make it again.', 'error'); + redirect(); + } mysqli_query($mysqli, "INSERT INTO api_keys SET api_key_name = '" . escapeSql($fields['name']) . "', api_key_secret = '" . escapeSql($secret) . "', api_key_decrypt_hash = '$apikey_specific_encryption_ciphertext', api_key_expire = '" . escapeSql($fields['expire']) . "', api_key_user_id = " . intval($fields['user_id'])); diff --git a/admin/post/backup.php b/admin/post/backup.php index bff3affd5..4f59851c2 100644 --- a/admin/post/backup.php +++ b/admin/post/backup.php @@ -37,6 +37,38 @@ if (isset($_GET['queue_backup'])) { redirect("backup.php"); } +/* + * Retire the copies of the vault's key still sealed the old, weaker way (functions/security.php) - for + * agents who haven't signed in, and API keys not used, since. Only by an admin whose own copy is + * current, so a copy that opens the vault is always left. + */ +if (isset($_GET['retire_old_vault_copies'])) { + + validateCSRFToken(); + + if (vaultWrapIsLegacy(getFieldById('users', $session_user_id, 'user_specific_encryption_ciphertext'))) { + flashAlert("Sign out and back in first, so your own copy of the key is sealed the current way.", 'error'); + redirect("backup.php"); + } + + $vault = vaultCopies(); + foreach ($vault['users'] as $vault_user) { + mysqli_query($mysqli, "UPDATE users SET user_specific_encryption_ciphertext = '' WHERE user_id = " . intval($vault_user['user_id']) . " AND user_specific_encryption_ciphertext NOT LIKE '" . escapeSql(VAULT_WRAP_FORMAT) . "%'"); + } + foreach ($vault['keys'] as $vault_key) { + mysqli_query($mysqli, "UPDATE api_keys SET api_key_decrypt_hash = '' WHERE api_key_id = " . intval($vault_key['api_key_id']) . " AND api_key_decrypt_hash NOT LIKE '" . escapeSql(VAULT_WRAP_FORMAT) . "%'"); + } + $names = array_merge(array_column($vault['users'], 'user_name'), array_map(function ($key) { + return $key['api_key_name'] . ' (API key)'; + }, $vault['keys'])); + $count = count($names); + + logAudit("Master Key", "Retire", escapeSql(($session_name ?? 'Unknown User') . " retired $count old cop" . ($count === 1 ? 'y' : 'ies') . " of the vault key: " . implode(', ', $names))); + flashAlert("Retired $count old cop" . ($count === 1 ? 'y' : 'ies') . " of the vault key."); + + redirect("backup.php"); +} + if (isset($_GET['delete_backup'])) { validateCSRFToken(); diff --git a/functions/security.php b/functions/security.php index 22c7550e3..bf4dccab6 100644 --- a/functions/security.php +++ b/functions/security.php @@ -54,30 +54,35 @@ function generateTotpSecret() { return $key; } -// Called during initial setup +/* + * A user's, API key's or invite's copy of the vault's master key, sealed under their password: + * "v2:", then base64 of a 16 byte salt, a 12 byte nonce, the 16 byte GCM tag and the + * ciphertext - AES-256-GCM, under PBKDF2-SHA256 of the password at VAULT_WRAP_ITERATIONS with + * its full 32 bytes. A copy without the prefix was made before (16 hex characters of a 100,000 + * round PBKDF2 under AES-128-CBC - 64 bits): it still opens, and moves to this one at its next + * sign-in (vaultSignIn()) or API call (apiDecryptPasswordOpens()). + */ +define('VAULT_WRAP_FORMAT', 'v2:'); +define('VAULT_WRAP_ITERATIONS', 600000); + +// Called during initial setup, for new users, invites and when moving a copy to the current format // Encrypts the master key with the user's password function setupFirstUserSpecificKey($user_password, $site_encryption_master_key) { - $iv = randomString(); - $salt = randomString(); - - //Generate 128-bit (16 byte/char) kdhash of the users password - $user_password_kdhash = hash_pbkdf2('sha256', $user_password, $salt, 100000, 16); - - //Encrypt the master key with the users kdf'd hash and the IV - $ciphertext = openssl_encrypt($site_encryption_master_key, 'aes-128-cbc', $user_password_kdhash, 0, $iv); - - return $salt . $iv . $ciphertext; + $salt = random_bytes(16); + $nonce = random_bytes(12); + $key = hash_pbkdf2('sha256', (string) $user_password, $salt, VAULT_WRAP_ITERATIONS, 32, true); + $tag = ''; + $ciphertext = openssl_encrypt((string) $site_encryption_master_key, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, VAULT_WRAP_FORMAT); + return VAULT_WRAP_FORMAT . base64_encode($salt . $nonce . $tag . $ciphertext); } /* * For additional users / password changes (and now the API) * New Users: Requires the admin setting up their account have a Specific/Session key configured * Password Changes: Will use the current info in the session. + * False when this session's vault doesn't open - a copy of nothing would lock them out of it. */ function encryptUserSpecificKey($user_password) { - $iv = randomString(); - $salt = randomString(); - // Get the session info. $user_encryption_session_ciphertext = $_SESSION['user_encryption_session_ciphertext'] ?? ''; $user_encryption_session_iv = base64_decode($_SESSION['user_encryption_session_iv'] ?? ''); @@ -85,29 +90,110 @@ function encryptUserSpecificKey($user_password) { // Decrypt the session key to get the master key $site_encryption_master_key = openssl_decrypt($user_encryption_session_ciphertext, 'aes-128-cbc', $user_encryption_session_key, 0, $user_encryption_session_iv); + if (!is_string($site_encryption_master_key) || $site_encryption_master_key === '') { + return false; + } - // Generate 128-bit (16 byte/char) kdhash of the users (new) password - $user_password_kdhash = hash_pbkdf2('sha256', $user_password, $salt, 100000, 16); - - // Encrypt the master key with the users kdf'd hash and the IV - $ciphertext = openssl_encrypt($site_encryption_master_key, 'aes-128-cbc', $user_password_kdhash, 0, $iv); - - return $salt . $iv . $ciphertext; + return setupFirstUserSpecificKey($user_password, $site_encryption_master_key); } // Given a ciphertext (incl. IV) and the user's (or API key) password, returns the site master key -// Ran at login, to facilitate generateUserSessionKey +// Ran at login, to facilitate generateUserSessionKey - and on API calls, once a call (each key is slow to derive by design) function decryptUserSpecificKey($user_encryption_ciphertext, $user_password) { - //Get the IV, salt and ciphertext - $salt = substr($user_encryption_ciphertext, 0, 16); - $iv = substr($user_encryption_ciphertext, 16, 16); - $ciphertext = substr($user_encryption_ciphertext, 32); + static $opened = []; + $user_encryption_ciphertext = (string) $user_encryption_ciphertext; + $memo = hash('sha256', $user_encryption_ciphertext . "\0" . $user_password); + if (isset($opened[$memo])) { + return $opened[$memo]; + } - //Generate 128-bit (16 byte/char) kdhash of the users password - $user_password_kdhash = hash_pbkdf2('sha256', $user_password, $salt, 100000, 16); + if (strpos($user_encryption_ciphertext, VAULT_WRAP_FORMAT) === 0) { + $raw = base64_decode(substr($user_encryption_ciphertext, strlen(VAULT_WRAP_FORMAT)), true); + if ($raw === false || strlen($raw) < 45) { + return false; + } + $key = hash_pbkdf2('sha256', (string) $user_password, substr($raw, 0, 16), VAULT_WRAP_ITERATIONS, 32, true); + $master = openssl_decrypt(substr($raw, 44), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($raw, 16, 12), substr($raw, 28, 16), VAULT_WRAP_FORMAT); + } else { + //Get the IV, salt and ciphertext + $salt = substr($user_encryption_ciphertext, 0, 16); + $iv = substr($user_encryption_ciphertext, 16, 16); + $ciphertext = substr($user_encryption_ciphertext, 32); - //Use this hash to get the original/master key - return openssl_decrypt($ciphertext, 'aes-128-cbc', $user_password_kdhash, 0, $iv); + //Generate 128-bit (16 byte/char) kdhash of the users password + $user_password_kdhash = hash_pbkdf2('sha256', (string) $user_password, $salt, 100000, 16); + + //Use this hash to get the original/master key + $master = openssl_decrypt($ciphertext, 'aes-128-cbc', $user_password_kdhash, 0, $iv); + } + + if (is_string($master) && $master !== '') { + $opened[$memo] = $master; + } + return $master; +} + +/** A copy of the master key in the format from before (setupFirstUserSpecificKey()) - '' is none at all. */ +function vaultWrapIsLegacy($ciphertext) { + $ciphertext = (string) $ciphertext; + return $ciphertext !== '' && strpos($ciphertext, VAULT_WRAP_FORMAT) !== 0; +} + +/* + * Signing in, with the password in hand: open the user's copy of the master key, move it to the + * current format when it is in the old one - written only once the new copy is checked to open, + * and only over the copy it read - and start the vault session (generateUserSessionKey()). + * Whether the vault opened. + */ +function vaultSignIn($user_id, $ciphertext, $password) { + global $mysqli; + if (empty($ciphertext)) { + return false; + } + $master = decryptUserSpecificKey($ciphertext, $password); + if (!is_string($master) || $master === '') { + return false; + } + if (vaultWrapIsLegacy($ciphertext)) { + $rewrapped = setupFirstUserSpecificKey($password, $master); + if (decryptUserSpecificKey($rewrapped, $password) === $master) { + mysqli_query($mysqli, "UPDATE users SET user_specific_encryption_ciphertext = '" . escapeSql($rewrapped) . "' + WHERE user_id = " . intval($user_id) . " AND user_specific_encryption_ciphertext = '" . escapeSql($ciphertext) . "'"); + } + } + generateUserSessionKey($master); + return true; +} + +/* + * The copies of the master key, by format (Admin > Backup): 'old' - the agents' (id, name, email) + * and API keys' (id, name) still in the format from before - and how many there are in all and + * in the current one. + */ +function vaultCopies() { + global $mysqli; + $prefix = escapeSql(VAULT_WRAP_FORMAT); + $copies = ['users' => [], 'keys' => [], 'total' => 0, 'current' => 0]; + $sql = mysqli_query($mysqli, "SELECT user_id, user_name, user_email, user_specific_encryption_ciphertext LIKE '$prefix%' AS current FROM users + WHERE user_type = 1 AND user_specific_encryption_ciphertext <> '' ORDER BY user_name"); + while ($row = mysqli_fetch_assoc($sql)) { + $copies['total']++; + if (intval($row['current'])) { + $copies['current']++; + } else { + $copies['users'][] = $row; + } + } + $sql = mysqli_query($mysqli, "SELECT api_key_id, api_key_name, api_key_decrypt_hash LIKE '$prefix%' AS current FROM api_keys WHERE api_key_decrypt_hash <> '' ORDER BY api_key_name"); + while ($row = mysqli_fetch_assoc($sql)) { + $copies['total']++; + if (intval($row['current'])) { + $copies['current']++; + } else { + $copies['keys'][] = $row; + } + } + return $copies; } /* @@ -218,8 +304,20 @@ function apiDecryptCredentialEntry($credential_ciphertext, $api_key_decrypt_hash * that could never be read again. */ function apiDecryptPasswordOpens($api_key_decrypt_hash, #[\SensitiveParameter]$api_key_decrypt_password) { + global $mysqli; $key = decryptUserSpecificKey((string) $api_key_decrypt_hash, (string) $api_key_decrypt_password); - return is_string($key) && $key !== ''; + if (!is_string($key) || $key === '') { + return false; + } + // The key's copy of the master key in the format from before - moved to the current one now its password is here, + // once the new copy is checked to open, and only over the copy it read + if (vaultWrapIsLegacy($api_key_decrypt_hash)) { + $rewrapped = setupFirstUserSpecificKey((string) $api_key_decrypt_password, $key); + if (decryptUserSpecificKey($rewrapped, (string) $api_key_decrypt_password) === $key) { + mysqli_query($mysqli, "UPDATE api_keys SET api_key_decrypt_hash = '" . escapeSql($rewrapped) . "' WHERE api_key_decrypt_hash = '" . escapeSql((string) $api_key_decrypt_hash) . "'"); + } + } + return true; } function apiEncryptCredentialEntry(#[\SensitiveParameter]$credential_cleartext, $api_key_decrypt_hash, #[\SensitiveParameter]$api_key_decrypt_password) { diff --git a/functions/user.php b/functions/user.php index 0f38a0e35..461171003 100644 --- a/functions/user.php +++ b/functions/user.php @@ -221,7 +221,9 @@ function userPasswordProblem($password) { function userSetPassword($user_id, $password) { global $mysqli; $hash = password_hash((string) $password, PASSWORD_DEFAULT); - $ciphertext = escapeSql(encryptUserSpecificKey((string) $password)); + // No copy when this session's vault doesn't open (a reset from the sign-in page) - an admin resetting it later gives them one + $ciphertext = encryptUserSpecificKey((string) $password); + $ciphertext = escapeSql($ciphertext === false ? '' : $ciphertext); mysqli_query($mysqli, "UPDATE users SET user_password = '" . escapeSql($hash) . "', user_specific_encryption_ciphertext = '$ciphertext' WHERE user_id = " . intval($user_id)); userSessionRestamp($user_id, $hash); } diff --git a/login.php b/login.php index 45525e428..675cb1a17 100644 --- a/login.php +++ b/login.php @@ -316,24 +316,21 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_ // Show role choice screen $show_role_choice = true; - // If this is the first time (Step 1), we need to stash allowed ids and (optional) decrypted agent encryption key + // If this is the first time (Step 1), we need to stash allowed ids and open the agent's vault // WITHOUT storing password. if ($is_login_step) { $pending_token = bin2hex(random_bytes(32)); - // If agent has user-specific encryption ciphertext, decrypt it NOW while password is present. - $agent_master_key = null; - $agent_cipher = $agentRow['user_specific_encryption_ciphertext'] ?? null; - if (!empty($agent_cipher)) { - $agent_master_key = decryptUserSpecificKey($agent_cipher, $password); - } + // Open the agent's vault NOW while the password is present - into the vault session, so the master + // key itself is never kept in the session (vaultSignIn()); dropped if they go on as the client + $agent_vault = vaultSignIn(intval($agentRow['user_id']), $agentRow['user_specific_encryption_ciphertext'] ?? null, $password); $_SESSION['pending_dual_login'] = [ 'email' => $email, 'agent_user_id' => intval($agentRow['user_id']), 'client_user_id' => intval($clientRow['contact_user_id'] ?? 0) ?: intval($clientRow['user_id'] ?? 0), - 'agent_master_key' => $agent_master_key, // may be null + 'agent_vault' => $agent_vault, 'token' => $pending_token, 'created' => time() ]; @@ -358,7 +355,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_ $pending_dual = $_SESSION['pending_dual_login'] ?? null; $pending_mfa = $_SESSION['pending_mfa_login'] ?? null; - // NOTE: do NOT unset pending_dual_login here anymore; we may still need agent_master_key for MFA or role-step agent login + // NOTE: do NOT unset pending_dual_login here anymore; we may still need agent_vault for MFA or role-step agent login $user_id = intval($selectedRow['user_id']); $user_email = escapeSql($selectedRow['user_email']); @@ -503,32 +500,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_ $config_start_page = "user/mfa_enforcement.php"; } - // Setup encryption session key WITHOUT PASSWORD IN SESSION - $site_encryption_master_key = null; - - if ($is_mfa_step) { - // Step 3: MFA submit - $sess = $pending_mfa ?? ($_SESSION['pending_mfa_login'] ?? null); - if ($sess && !empty($sess['agent_master_key'])) { - $site_encryption_master_key = $sess['agent_master_key']; - } - - } elseif ($is_role_step) { - // Step 2: role choice (no password available) - $sess = $pending_dual ?? ($_SESSION['pending_dual_login'] ?? null); - if ($sess && !empty($sess['agent_master_key'])) { - $site_encryption_master_key = $sess['agent_master_key']; - } - - } else { - // Step 1: initial login (password available in this request) - if (!empty($user_encryption_ciphertext)) { - $site_encryption_master_key = decryptUserSpecificKey($user_encryption_ciphertext, $password); - } - } - - if (!empty($site_encryption_master_key)) { - generateUserSessionKey($site_encryption_master_key); + // 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) { + vaultSignIn($user_id, $user_encryption_ciphertext, $password); } // NOW safe to clear pending sessions AFTER we used them @@ -553,25 +528,21 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_ // MFA required — store *only what we need*, not password $pending_mfa_token = bin2hex(random_bytes(32)); - // If we arrived here from role-choice step, the agent master key may be in cached pending_dual - // If we arrived from initial login step, decrypt now (password in memory) and store master key. - $agent_master_key = null; - + // The vault: from the role choice it was opened at step 1, on a retried code it was opened before, + // and from the initial login step it is opened now, with the password in memory (vaultSignIn()) if ($is_role_step) { $sess = $pending_dual ?? ($_SESSION['pending_dual_login'] ?? null); - if ($sess && array_key_exists('agent_master_key', $sess)) { - $agent_master_key = $sess['agent_master_key']; - } + $agent_vault = !empty($sess['agent_vault']); + } elseif ($is_mfa_step) { + $agent_vault = !empty($pending_mfa['agent_vault']); } else { - if (!empty($user_encryption_ciphertext)) { - $agent_master_key = decryptUserSpecificKey($user_encryption_ciphertext, $password); - } + $agent_vault = vaultSignIn($user_id, $user_encryption_ciphertext, $password); } $_SESSION['pending_mfa_login'] = [ 'email' => $user_email, 'agent_user_id' => $user_id, - 'agent_master_key' => $agent_master_key, // may be null + 'agent_vault' => $agent_vault, 'token' => $pending_mfa_token, // Keep the original issue time on a retry so the pending // window actually expires, instead of being pushed forward @@ -733,10 +704,12 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_ $session_user_id = $user_id; logAudit("Client Login", "Success", "Client contact $user_email successfully logged in locally$client_mfa_how", $client_id, $user_id); - // Clear any pending sessions (avoid stale dual-role/MFA state), and an agent's View as contact + // Clear any pending sessions (avoid stale dual-role/MFA state), and an agent's View as contact - + // 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['portal_view_as']); + unset($_SESSION['user_encryption_session_ciphertext'], $_SESSION['user_encryption_session_iv']); header("Location: client/index.php"); exit();