(NOW() - INTERVAL " . SIGN_IN_WINDOW_MINUTES . " MINUTE)"
));
$failed_login_count = intval($row['failed_login_count']);
if ($failed_login_count >= SIGN_IN_LOCKOUT) {
// Make sure global session_user_id is not required here (will be 0 anyway)
logAudit("Login", "Blocked", "Sign in turned away from $session_ip - " . SIGN_IN_LOCKOUT . " failed sign-ins in " . SIGN_IN_WINDOW_MINUTES . " minutes");
header("HTTP/1.1 429 Too Many Requests");
exit("
$config_app_name
Your IP address has been blocked due to repeated failed login attempts. Please try again later.
This action has been logged.");
}
// Settings
$sql_settings = mysqli_query($mysqli, "
SELECT settings.*, companies.company_name, companies.company_logo
FROM settings
LEFT JOIN companies ON settings.company_id = companies.company_id
WHERE settings.company_id = 1
");
$row = mysqli_fetch_assoc($sql_settings);
$company_name = $row['company_name'];
$company_logo = $row['company_logo'];
$config_start_page = escapeHtml($row['config_start_page']);
$config_login_message = escapeHtml($row['config_login_message']);
$config_smtp_provider = $row['config_smtp_provider'];
$config_smtp_host = $row['config_smtp_host'];
$config_smtp_port = intval($row['config_smtp_port']);
$config_smtp_encryption = $row['config_smtp_encryption'];
$config_smtp_username = $row['config_smtp_username'];
$config_smtp_password = $row['config_smtp_password'];
$config_mail_from_email = escapeSql($row['config_mail_from_email']);
$config_mail_from_name = escapeSql($row['config_mail_from_name']);
$config_client_portal_enable = intval($row['config_client_portal_enable']);
$config_login_remember_me_expire = intval($row['config_login_remember_me_expire']);
$config_whitelabel_enabled = intval($row['config_whitelabel_enabled']);
$config_login_key_required = $row['config_login_key_required'];
$config_login_key_secret = $row['config_login_key_secret'];
// Signing in through an identity provider - Microsoft 365, Google, Nextcloud (functions/identity_provider.php, login_provider.php).
// Without the login key the page is the contacts', so only theirs show - the agents' sign-in stays out of sight
$login_providers = identityProviderButtons();
$login_key_ok = !$config_login_key_required || hash_equals((string) $config_login_key_secret, is_string($_GET['key'] ?? null) ? $_GET['key'] : '');
if (!$login_key_ok) {
$login_providers = array_values(array_filter($login_providers, function ($login_provider) {
return identityProviderFor($login_provider, 2);
}));
}
// Signing in with a passkey (functions/passkey.php, login_passkey.php) - once the database has them
$config_login_passkeys = intval($row['config_login_passkeys'] ?? 0);
// The public help center link, once the database has the Knowledge Base settings (functions/kb.php)
if (isset($row['config_module_enable_kb'], $row['config_kb_public_enable'])) {
$config_module_enable_kb = intval($row['config_module_enable_kb']);
$config_kb_public_enable = intval($row['config_kb_public_enable']);
}
$response = null;
$token_field = null;
$show_role_choice = false;
$email = '';
$password = ''; // only ever used in the initial POST request
// The demo's sign-in buttons - each signs in as one of its accounts, through the same sign-in as
// an email and password (functions/demo.php)
if (demoModeOn() && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['demo_sign_in'])) {
$demo_email = demoModeSignInEmail((string) $_POST['demo_sign_in']);
if ($demo_email === null) {
$response = "
That demo account isn't there right now - another visitor changed it. It's back after the nightly reset, so try another for now.
";
} else {
$_POST['email'] = $demo_email;
$_POST['password'] = DEMO_MODE_PASSWORD;
$_POST['login'] = '';
}
}
// Helpers
function pendingExpired($sess, $ttl_seconds = 120) {
return !$sess || empty($sess['created']) || (time() - intval($sess['created']) > $ttl_seconds);
}
// POST handling
// Back from an identity provider, which login_provider.php has checked - a GET, as the provider's redirect was
$is_provider_return = $_SERVER['REQUEST_METHOD'] === 'GET' && is_string($_GET['provider_login'] ?? null) && $_GET['provider_login'] !== '';
if (($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($_POST['role_choice']) || isset($_POST['mfa_login']) || isset($_POST['passkey_login']))) || $is_provider_return) {
$role_choice = $_POST['role_choice'] ?? null;
$is_login_step = isset($_POST['login']);
$is_role_step = isset($_POST['role_choice']) && !$is_login_step && !isset($_POST['mfa_login']);
$is_mfa_step = isset($_POST['mfa_login']);
// After login_passkey.php checked a passkey - which counts as two-step sign-in
$is_passkey_step = isset($_POST['passkey_login']) && !$is_login_step && !$is_mfa_step && !$is_role_step;
// After login_provider.php: an identity provider signed them in - its own two-step sign-in stands in for ours
$is_provider_step = $is_provider_return && !$is_login_step && !$is_mfa_step && !$is_role_step && !$is_passkey_step;
// Signed in by a provider - straight back from it, or choosing agent or client after it (functions/identity_provider.php)
$via_provider = null;
// The IMAP provider that checked the password, when one did - the password is the mail server's, not ours.
// By account type, as one may be an agent's and not a client's; $via_imap is the signed-in one's
$via_imap = null;
$via_imap_types = [];
// A provider on the address's domain that is required, so its password isn't looked at here; whether
// its mail server has had too many wrong passwords for it to be asked again for now; and whether a
// password was checked at all. The kinds of account this page can sign in - without the login key, contacts
$required_provider = null;
$mail_locked = false;
$password_checked = false;
$login_types = $login_key_ok ? [1, 2] : [2];
// -----------------------------------
// STEP 2: ROLE CHOICE (no email/pass)
// -----------------------------------
if ($is_role_step) {
$posted_token = $_POST['pending_login_token'] ?? '';
$sess = $_SESSION['pending_dual_login'] ?? null;
if (pendingExpired($sess) || empty($posted_token) || empty($sess['token']) || !hash_equals($sess['token'], $posted_token)) {
unset($_SESSION['pending_dual_login']);
header("HTTP/1.1 401 Unauthorized");
$response = "
Your login session expired. Please sign in again.
";
} else {
$email = escapeSql($sess['email'] ?? '');
$email_raw = (string) ($sess['email'] ?? '');
// Agent or client, after a provider signed them in - or after the mail server checked their password
if (($sess['via'] ?? '') === 'provider') {
$via_provider = $sess['provider'] ?? null;
}
$via_imap_types = (array) ($sess['via_imap'] ?? []);
}
}
// -----------------------------------
// STEP 3: MFA SUBMIT (no email/pass)
// -----------------------------------
if ($is_mfa_step && empty($response)) {
$posted_token = $_POST['pending_mfa_token'] ?? '';
$sess = $_SESSION['pending_mfa_login'] ?? null;
if (pendingExpired($sess) || empty($posted_token) || empty($sess['token']) || !hash_equals($sess['token'], $posted_token)) {
unset($_SESSION['pending_mfa_login']);
header("HTTP/1.1 401 Unauthorized");
$response = "
Your MFA session expired. Please sign in again.
";
} else {
$email = escapeSql($sess['email'] ?? '');
$email_raw = (string) ($sess['email'] ?? '');
// A client portal user's code, or an agent's
$role_choice = ($sess['type'] ?? 'agent') === 'client' ? 'client' : 'agent';
// The mail server checked their password (an IMAP provider) - for the one account this code is for
$via_imap_types = !empty($sess['via_imap']) ? [1 => $sess['via_imap'], 2 => $sess['via_imap']] : [];
}
}
// -----------------------------------
// A PASSKEY, checked by login_passkey.php (no email/pass)
// -----------------------------------
if ($is_passkey_step && empty($response)) {
$posted_token = $_POST['pending_passkey_token'] ?? '';
$sess = $_SESSION['pending_passkey_login'] ?? null;
if (pendingExpired($sess) || empty($posted_token) || empty($sess['token']) || !hash_equals($sess['token'], $posted_token)) {
unset($_SESSION['pending_passkey_login']);
header("HTTP/1.1 401 Unauthorized");
$response = "
Your passkey sign in expired. Please sign in again.
";
}
}
// Continue only if no response error
if (empty($response)) {
// Query all possible matches for that email
$sql = mysqli_query($mysqli, "
SELECT users.*,
user_settings.*,
contacts.*,
clients.*
FROM users
LEFT JOIN user_settings ON users.user_id = user_settings.user_id
LEFT JOIN contacts ON users.user_id = contacts.contact_user_id
LEFT JOIN clients ON contacts.contact_client_id = clients.client_id
WHERE user_email = '$email'
AND user_archived_at IS NULL
AND user_status = 1
AND (
(user_type = 1" . serviceAccountsOutSql('users.user_service_account') . ")
OR (user_type = 2 AND client_archived_at IS NULL)
)
");
$agentRow = null;
$clientRow = null;
// Step 1: verify password. Step 2/3: use stored allowed ids.
$allowed_agent_id = null;
$allowed_client_id = null;
if ($is_role_step) {
$sess = $_SESSION['pending_dual_login'] ?? null;
$allowed_agent_id = isset($sess['agent_user_id']) ? intval($sess['agent_user_id']) : null;
$allowed_client_id = isset($sess['client_user_id']) ? intval($sess['client_user_id']) : null;
}
// The accounts the provider can sign in - the other kind, or one it isn't for, is left out (-1 matches no one)
if ($is_provider_step) {
$allowed_agent_id = $provider_accounts['agent'] ?: -1;
$allowed_client_id = $provider_accounts['client'] ?: -1;
}
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;
} else {
$allowed_agent_id = isset($sess['agent_user_id']) ? intval($sess['agent_user_id']) : null;
$allowed_client_id = -1;
}
}
// Too many wrong passwords for an address its mail server checks - it isn't asked again for now (functions/identity_provider.php)
if ($is_login_step && empty($response)) {
$mail_locked = identityProviderMailLocked($email_raw, $login_types);
}
while ($r = mysqli_fetch_assoc($sql)) {
$ut = intval($r['user_type']);
if ($is_login_step) {
// A required provider on its domains turns its password off, the mail server's too - an administrator
// keeps theirs. Decided before the password is looked at, so what the page says can't tell whether it was right
$required = identityProviderRequiredFor($email_raw, $ut, intval($r['user_role_id'] ?? 0));
if ($required) {
if (in_array($ut, $login_types, true)) {
$required_provider = $required_provider ?: $required;
}
continue;
}
// Only Step 1 checks password - the mail server's, for an account an IMAP provider signs in
$password_checked = true;
$imap = identityProviderImapFor($email_raw, $ut);
if ($imap) {
$mail_ok = $ut === 1 || ($r['user_auth_method'] ?? '') === 'local';
if ($mail_ok && !$mail_locked && identityProviderImapCheck($imap, $email_raw, $password)[0]) {
$via_imap_types[$ut] = ['id' => intval($imap['identity_provider_id']), 'name' => (string) $imap['identity_provider_name']];
identityProviderUsed($via_imap_types[$ut]['id']);
} elseif ($ut !== 1 || !identityProviderAdminRole($r['user_role_id'] ?? 0) || !password_verify($password, $r['user_password'])) {
// An administrator's own password still works - for when the mail server is down
continue;
}
} elseif (!password_verify($password, $r['user_password'])) {
continue;
}
} else {
// Step 2/3: restrict to ids we previously verified
if ($ut === 1 && $allowed_agent_id !== null && intval($r['user_id']) !== $allowed_agent_id) {
continue;
}
// A client's users.user_id can come back NULL from the user_settings join (they have
// no row there) - contact_user_id is theirs
if ($ut === 2 && $allowed_client_id !== null && (intval($r['contact_user_id'] ?? 0) ?: intval($r['user_id'] ?? 0)) !== $allowed_client_id) {
continue;
}
}
if ($ut === 1 && $agentRow === null) {
$agentRow = $r;
}
if ($ut === 2 && $clientRow === null) {
$clientRow = $r;
}
}
// Nobody signed in: a provider required on the address's domain says so - whatever was typed, account or not
if ($is_login_step && $agentRow === null && $clientRow === null) {
foreach ($login_types as $login_type) {
$required_provider = $required_provider ?: identityProviderRequiredFor($email_raw, $login_type);
}
}
if ($agentRow === null && $clientRow === null && $required_provider) {
header("HTTP/1.1 401 Unauthorized");
// Its password isn't looked at - this address signs in through its provider (an administrator's mistyped is said the same)
$failed_why = signInFailureReason($email_raw ?? '');
$required_name = (string) $required_provider['identity_provider_name'];
$failed_reason = $failed_why['reason'] === 'wrong password' && !$password_checked ? "it signs in with $required_name, not a password" : $failed_why['reason'] . " - $required_name is required for it";
signInLogFailure($failed_why['type'], 'Failed', escapeSql('Failed sign in as ' . ($email_raw ?? '') . ' - ' . $failed_reason), $failed_why['user_id'], $failed_why['client_id']);
$response = "
Sign in with " . escapeHtml($required_name) . " - accounts on " . escapeHtml(identityProviderEmailDomain($email_raw)) . " don't sign in with a password here.
";
} elseif ($agentRow === null && $clientRow === null && $mail_locked) {
header("HTTP/1.1 429 Too Many Requests");
// Its mail server wasn't asked - guesses spread over many IP addresses would otherwise go on to it
$failed_why = signInFailureReason($email_raw ?? '');
signInLogFailure($failed_why['type'], 'Failed', escapeSql('Failed sign in as ' . ($email_raw ?? '') . ' - ' . IDENTITY_PROVIDER_MAIL_TRIES . ' wrong passwords in ' . SIGN_IN_WINDOW_MINUTES . ' minutes, so its mail server wasn\'t asked'), $failed_why['user_id'], $failed_why['client_id']);
$response = "
Too many wrong passwords for this address - wait " . SIGN_IN_WINDOW_MINUTES . " minutes, then try again.
";
} elseif ($agentRow === null && $clientRow === null) {
header("HTTP/1.1 401 Unauthorized");
// Why, and whose account it was - so it counts against the account too
$failed_why = signInFailureReason($email_raw ?? '');
signInLogFailure($failed_why['type'], 'Failed', escapeSql('Failed sign in as ' . ($email_raw ?? '') . ' - ' . $failed_why['reason']), $failed_why['user_id'], $failed_why['client_id']);
$response = "
Incorrect username or password.
";
} else {
$selectedRow = null;
$selectedType = null; // 1 agent, 2 client
// Dual role
if ($agentRow !== null && $clientRow !== null) {
if ($role_choice === 'agent') {
$selectedRow = $agentRow;
$selectedType = 1;
} elseif ($role_choice === 'client') {
$selectedRow = $clientRow;
$selectedType = 2;
} else {
// Show role choice screen
$show_role_choice = true;
// Straight back from a provider - stash who it can be, as for a password; the vault stays locked
if ($is_provider_step) {
$_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_vault' => false,
'via' => 'provider',
'provider' => $via_provider,
'token' => bin2hex(random_bytes(32)),
'created' => time()
];
}
// 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));
// 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_vault' => $agent_vault,
'via_imap' => $via_imap_types,
'token' => $pending_token,
'created' => time()
];
}
}
} else {
// Single role
if ($agentRow !== null) {
$selectedRow = $agentRow;
$selectedType = 1;
} else {
$selectedRow = $clientRow;
$selectedType = 2;
}
}
// Proceed if selected
if ($selectedRow !== null && $selectedType !== null) {
// Whether the mail server checked this account's password (an IMAP provider)
$via_imap = $via_imap_types[$selectedType] ?? null;
// Cache pending sessions BEFORE unsetting anything (needed for role->MFA and MFA success)
$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_vault for MFA or role-step agent login
$user_id = intval($selectedRow['user_id']);
$user_email = escapeSql($selectedRow['user_email']);
// =========================
// AGENT FLOW
// =========================
if ($selectedType === 1) {
if ($config_login_key_required) {
if (!isset($_GET['key']) || $_GET['key'] !== $config_login_key_secret) {
redirect();
}
}
$user_name = escapeSql($selectedRow['user_name']);
$token = escapeSql($selectedRow['user_token']);
$force_mfa = intval($selectedRow['user_config_force_mfa']);
$user_encryption_ciphertext = $selectedRow['user_specific_encryption_ciphertext'];
// Whether a code was typed at all - 000000 is a real code, which intval() makes 0
$code_given = trim((string) ($_POST['current_code'] ?? '')) !== '';
$current_code = $code_given ? intval($_POST['current_code']) : 0;
// Per-account limit on second factor attempts. The IP lockout at the
// top of this file can be spread across hosts, and anything reaching
// this point has already cleared the password, so the second factor
// needs a limit tied to the account rather than the source address.
// Only a request that passed the password check can add to this
// counter, so it cannot be used to lock another user out.
$mfa_locked = false;
if ($code_given) {
// This counter needs its own lock. The IP lock above does not
// serialize a burst spread across hosts, and a burst spread
// across hosts is the exact case this per-account limit exists
// for. Keyed on the account, released with the request.
$mfa_lock_name = "itflow_login_mfa_$user_id";
$mfa_lock = mysqli_fetch_row(mysqli_query($mysqli, "SELECT GET_LOCK('$mfa_lock_name', 10)"));
if (empty($mfa_lock[0])) {
error_log("ITFlow: timed out waiting on the MFA rate limit lock for user $user_id, proceeding unserialized");
}
$row_mfa = mysqli_fetch_assoc(mysqli_query(
$mysqli,
"SELECT COUNT(log_id) AS failed_mfa_count
FROM logs
WHERE log_user_id = $user_id
AND log_type = 'Login'
AND log_action = 'MFA Failed'
AND log_created_at > (NOW() - INTERVAL 10 MINUTE)"
));
$mfa_locked = intval($row_mfa['failed_mfa_count']) >= 5;
}
$mfa_is_complete = false;
$extended_log = '';
if (empty($token)) {
$mfa_is_complete = true; // no MFA configured
}
// remember-me cookie allows bypass
if (isset($_COOKIE['rememberme'])) {
$remember_tokens = mysqli_query($mysqli, "
SELECT remember_token_token
FROM remember_tokens
WHERE remember_token_user_id = $user_id
AND remember_token_created_at > (NOW() - INTERVAL $config_login_remember_me_expire DAY)
");
while ($remember_row = mysqli_fetch_assoc($remember_tokens)) {
if (hash_equals($remember_row['remember_token_token'], $_COOKIE['rememberme'])) {
$mfa_is_complete = true;
$extended_log = 'with 2FA remember-me cookie';
break;
}
}
}
// Validate MFA code
if (!$mfa_locked && $code_given && TokenAuth6238::verify($token, $current_code, 1)) {
$mfa_is_complete = true;
$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)";
}
// So is an identity provider - its own two-step sign-in stands in for ours
if ($via_provider) {
$mfa_is_complete = true;
$extended_log = 'with ' . escapeSql($via_provider['name']);
}
// The mail server checked the password - the two-step code is still ours to ask
if ($via_imap && $mfa_is_complete) {
$extended_log = trim('with their mail password (' . escapeSql($via_imap['name']) . ") $extended_log");
}
if ($mfa_is_complete) {
// Remember me token creation
if (isset($_POST['remember_me'])) {
$newRememberToken = bin2hex(random_bytes(64));
setcookie('rememberme', $newRememberToken, time() + 86400 * $config_login_remember_me_expire, "/", null, true, true);
mysqli_query($mysqli, "
INSERT INTO remember_tokens
SET remember_token_user_id = $user_id,
remember_token_token = '$newRememberToken'
");
$extended_log .= ", generated a new remember-me token";
}
// Suspicious login checks / email notify
$sql_ip_prev_logins = mysqli_fetch_assoc(mysqli_query($mysqli, "
SELECT COUNT(log_id) AS ip_previous_logins
FROM logs
WHERE log_type = 'Login'
AND log_action = 'Success'
AND log_ip = '$session_ip'
AND log_user_id = $user_id
"));
$ip_previous_logins = escapeSql($sql_ip_prev_logins['ip_previous_logins']);
$sql_ua_prev_logins = mysqli_fetch_assoc(mysqli_query($mysqli, "
SELECT COUNT(log_id) AS ua_previous_logins
FROM logs
WHERE log_type = 'Login'
AND log_action = 'Success'
AND log_user_agent = '$session_user_agent'
AND log_user_id = $user_id
"));
$ua_prev_logins = escapeSql($sql_ua_prev_logins['ua_previous_logins']);
// Not in the demo, where everyone signs in from somewhere new (functions/demo.php)
if ($ip_previous_logins == 0 && $ua_prev_logins == 0 && !demoModeOn()) {
userMailSignInAlert($selectedRow['user_name'], $selectedRow['user_email'], 'new', getIP(), $_SERVER['HTTP_USER_AGENT'] ?? '');
}
// Option B: set session_user_id BEFORE logAudit()
$session_user_id = $user_id;
logAudit("Login", "Success", "$user_name successfully logged in $extended_log", 0, $user_id);
// New session ID for the authenticated session (CWE-384)
session_regenerate_id(true);
$_SESSION['user_id'] = $user_id;
$_SESSION['csrf_token'] = randomString(32);
$_SESSION['logged'] = true;
// A later password change ends this session (userSessionStamp())
$_SESSION['user_session_stamp'] = userSessionStamp($selectedRow['user_password'] ?? '');
// A passkey or provider sign-in is two-step already - MFA enforcement leaves it be (includes/load_user_session.php)
$_SESSION['signed_in_with'] = $via_provider ? 'provider' : ($is_passkey_step ? 'passkey' : ($via_imap ? 'imap' : 'password'));
$_SESSION['signed_in_via'] = ($via_provider ?: $via_imap)['name'] ?? '';
$mfa_to_set_up = $force_mfa == 1 && $token == NULL && !$is_passkey_step && !$via_provider;
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.
// With a passkey it was opened by login_passkey.php, when the passkey could - or is unlocked later (vaultUnlock()).
// After a provider it stays locked - they never typed their password here
if (!$is_mfa_step && !$is_role_step && !$is_passkey_step && !$via_provider) {
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 (!$mfa_to_set_up && !isset($_GET['last_visited']) && gettingStartedFirstVisit($user_id)) {
redirect('admin/getting_started.php');
}
// Redirect
if (isset($_GET['last_visited']) && (str_starts_with(base64_decode($_GET['last_visited']), '/agent') || str_starts_with(base64_decode($_GET['last_visited']), '/admin'))) {
redirect($_SERVER["REQUEST_SCHEME"] . "://" . $config_base_url . base64_decode($_GET['last_visited']));
} else {
redirect("agent/$config_start_page");
}
} else {
// MFA required — store *only what we need*, not password
$pending_mfa_token = bin2hex(random_bytes(32));
// 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);
$agent_vault = !empty($sess['agent_vault']);
} elseif ($is_mfa_step) {
$agent_vault = !empty($pending_mfa['agent_vault']);
} else {
$agent_vault = vaultSignIn($user_id, $user_encryption_ciphertext, $password);
}
$_SESSION['pending_mfa_login'] = [
'email' => $user_email,
'agent_user_id' => $user_id,
'agent_vault' => $agent_vault,
'via_imap' => $via_imap,
'token' => $pending_mfa_token,
// Keep the original issue time on a retry so the pending
// window actually expires, instead of being pushed forward
// by every wrong code.
'created' => ($is_mfa_step && !empty($pending_mfa['created']))
? intval($pending_mfa['created'])
: time()
];
// Now that we've transferred what we need, it's safe to clear the dual-role pending session.
unset($_SESSION['pending_dual_login']);
$token_field = otpCodeInput('current_code', ['class' => 'mb-3', 'submit' => true, 'autofocus' => true, 'invalid' => $code_given && !$mfa_locked]);
if ($mfa_locked) {
// No log row and no email while locked out. Both are
// per-request writes the attacker controls, and logging here
// would keep pushing the 10 minute window forward so the
// lockout could never clear. The MFA Failed rows that
// triggered it are already the audit trail.
header("HTTP/1.1 429 Too Many Requests");
$response = "
Too many incorrect 2FA codes. Please wait 10 minutes and sign in again.
";
} elseif ($code_given) {
signInLogFailure('Login', 'MFA Failed', "$user_email entered a wrong MFA code - the password was right", $user_id);
userMailSignInAlert($selectedRow['user_name'], $selectedRow['user_email'], 'mfa', getIP(), $_SERVER['HTTP_USER_AGENT'] ?? '');
$response = "
";
} else {
// Client login user id can be clobbered by SELECT users.*, contacts.*, clients.* collisions.
// Prefer contact_user_id (ties to the portal user), fallback to user_id if present.
$user_id = intval($selectedRow['contact_user_id'] ?? 0);
if ($user_id === 0) {
$user_id = intval($selectedRow['user_id'] ?? 0);
}
$client_id = intval($selectedRow['contact_client_id'] ?? 0);
$contact_id = intval($selectedRow['contact_id'] ?? 0);
$user_auth_method = escapeSql($selectedRow['user_auth_method'] ?? '');
// Two-step sign-in, when the contact turned it on (functions/portal.php):
// 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'] ?? ''));
// A passkey is two-step sign-in in itself, and so is an identity provider
$client_mfa_done = $client_mfa_secret === '' || $is_passkey_step || $via_provider;
$client_mfa_how = $via_provider ? ' with ' . escapeSql($via_provider['name']) : ($is_passkey_step ? " with a passkey ($passkey_name)" : '');
if ($via_imap) {
$client_mfa_how = ' with their mail password (' . escapeSql($via_imap['name']) . ')' . $client_mfa_how;
}
// A provider signs in a contact set to sign in only that way, too (user_auth_method azure)
$client_can_sign_in = $user_auth_method === 'local' || ($via_provider && $user_auth_method === 'azure');
$client_mfa_locked = false;
$client_code = preg_replace('/\s+/', '', (string) ($_POST['current_code'] ?? ''));
if (!preg_match('/^[0-9]{6}$/', $client_code)) {
$client_code = '';
}
if ($client_id && $contact_id && $client_can_sign_in && !$client_mfa_done) {
if (isset($_COOKIE['rememberme'])) {
$remember_tokens = mysqli_query($mysqli, "SELECT remember_token_token FROM remember_tokens
WHERE remember_token_user_id = $user_id AND remember_token_created_at > (NOW() - INTERVAL $config_login_remember_me_expire DAY)");
while ($remember_row = mysqli_fetch_assoc($remember_tokens)) {
if (hash_equals($remember_row['remember_token_token'], (string) $_COOKIE['rememberme'])) {
$client_mfa_done = true;
$client_mfa_how = ' with a remembered browser';
break;
}
}
}
if (!$client_mfa_done && $client_code !== '') {
$mfa_lock = mysqli_fetch_row(mysqli_query($mysqli, "SELECT GET_LOCK('itflow_login_mfa_$user_id', 10)"));
if (empty($mfa_lock[0])) {
error_log("ITFlow: timed out waiting on the MFA rate limit lock for user $user_id, proceeding unserialized");
}
$client_mfa_locked = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(log_id) FROM logs
WHERE log_user_id = $user_id AND log_type = 'Client Login' AND log_action = 'MFA Failed'
AND log_created_at > (NOW() - INTERVAL 10 MINUTE)"))[0]) >= 5;
if (!$client_mfa_locked && TokenAuth6238::verify($client_mfa_secret, $client_code, 1)) {
$client_mfa_done = true;
$client_mfa_how = ' with two-step sign-in';
}
}
}
if ($client_id && $contact_id && $client_can_sign_in && !$client_mfa_done) {
// Ask for the code - keeping only who it is for, never the password
$pending_mfa_token = bin2hex(random_bytes(32));
$_SESSION['pending_mfa_login'] = [
'type' => 'client',
'email' => $user_email,
'client_user_id' => $user_id,
'via_imap' => $via_imap,
'token' => $pending_mfa_token,
'created' => ($is_mfa_step && !empty($pending_mfa['created'])) ? intval($pending_mfa['created']) : time(),
];
unset($_SESSION['pending_dual_login']);
$token_field = otpCodeInput('current_code', ['class' => 'mb-3', 'submit' => true, 'autofocus' => true, 'invalid' => !$client_mfa_locked && ($client_code !== '' || isset($_POST['current_code']))]);
if ($client_mfa_locked) {
// As for agents: no log row while locked, so the window can run out
header("HTTP/1.1 429 Too Many Requests");
$response = "
Too many wrong codes. Wait 10 minutes and sign in again.
Client portal signs in as = escapeHtml($demo_portal['name']) ?> at = escapeHtml($demo_portal['client']) ?>.
Anyone can sign in, so don't put anything real in it - it goes back to fresh demo data every night.