From adbd8866c2850e9b147af2be77eaab4692c7e3f4 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 30 Nov 2026 01:36:20 -0500 Subject: [PATCH] Fix identity provider gaps: a required provider is decided before any password or mail password is checked and the sign-in page says the same whatever was typed, account or not; required beats IMAP on the same domain; after five wrong passwords for an address in ten minutes its mail server isn't asked; Google signs in only Workspace accounts and Nextcloud has to say the address is verified; client secrets are sealed with the install key, with RMM's sealing moved to shared secretSeal and secretOpen; an IMAP server is tried when saved or turned on and Required waits for a first sign-in; joining, Forgot password, password links and welcome emails follow mail-password and required domains; Turn Off says who goes back to a password; 26.12.3 changelog entries --- CHANGELOG.md | 14 +- admin/database_updates/4.2.5.php | 8 +- admin/identity_providers.php | 11 +- .../identity_provider_edit.php | 25 ++- .../modals/portal_user/portal_user_access.php | 11 +- admin/post/identity_provider.php | 8 + admin/post/portal_users.php | 10 +- client/functions.php | 5 +- client/join.php | 52 +++-- client/login_reset.php | 49 +++-- functions/identity_provider.php | 193 +++++++++++++++--- functions/portal.php | 52 ++++- functions/portal_invite.php | 21 +- functions/rmm.php | 30 +-- functions/security.php | 41 ++++ functions/sign_in.php | 14 ++ join.php | 36 +++- login.php | 61 ++++-- 18 files changed, 499 insertions(+), 142 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24a8eb38a..639408aeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,9 +29,13 @@ Update from Maintenance > Update as usual - this release has four database chang - Pictures already inside tickets move to files in the background - the new Ticket Pictures job in Maintenance > Cron does a batch every minute until every ticket is done, then keeps an eye on new ones. - Taking a picture out of a reply or the ticket's details when editing it, or redacting it, deletes it - it no longer opens from an old link. Redact now takes a picture selected on its own, as well as text. - A picture from an internal note put in a reply the client sees, or from a ticket merged into another, is copied, so it shows for the client and stays when the other is deleted. -- Identity providers: agents and client contacts can sign in with their Microsoft 365, Google Workspace or Nextcloud account, each a button on the sign-in page, or with their mail password through an IMAP server. Set them up in the new Admin > Identity Providers, under Integrations: each is for agents, client contacts or both, and for the email domains you list. Only people already in ITFlow sign in - an agent, or a contact with portal access, with the same email address - and no one new is added. +- Identity providers: agents and client contacts can sign in with their Microsoft 365, Google Workspace or Nextcloud account, each a button on the sign-in page, or with their mail password through an IMAP server. Set them up in the new Admin > Identity Providers, under Integrations: each is for agents, client contacts or both, and for the email domains you list. Only people already in ITFlow sign in - an agent, or a contact with portal access, with the same email address - and no one new is added. Google signs in only Google Workspace accounts, not a personal Google account made with a work address, and Nextcloud has to say the address is verified. Client secrets are kept encrypted with your ITFlow's backup key. - Microsoft 365, Google Workspace and Nextcloud do their own sign-in checks, so ITFlow doesn't ask for its two-step code after them, and they meet a role's or the client portal's requirement for it. A mail password (IMAP) is still asked for the code. -- An identity provider can be required: the accounts on its email domains then can't sign in with a password, and the sign-in page says which button to use. Passkeys still work, and an agent with an administrator role keeps their password, to get back in if the provider is down. +- An identity provider can be required: the accounts on its email domains then can't sign in with a password or a mail password, and the sign-in page says which button to use. Passkeys still work, and an agent with an administrator role keeps their password, to get back in if the provider is down. It can be made required once it has signed someone in, so you know it works first. +- On a required provider's domains the sign-in page doesn't look at the password: it says to use the button whatever was typed, and whether or not the address has an account, so it never shows whether a password was right. +- A mail server (IMAP) is tried when you save the provider or turn it on, and one ITFlow can't reach isn't saved, so a typo can't turn everyone on its domains away. After five wrong passwords for one address in ten minutes, ITFlow stops asking the mail server about it until ten minutes pass, so guesses spread over many IP addresses don't go on to it. +- Contacts joining the portal on a domain whose mail server checks passwords, or where a provider is required, don't choose a password, and Forgot password tells them how they sign in instead of sending a link. So do the portal's welcome email and Email a Password Link. An agent joining on such a domain is told how they sign in, and chooses a password only to open their credentials. +- Turning an identity provider off says who goes back to their ITFlow password, and that contacts who sign in only through an identity provider can't sign in meanwhile. - An agent who signs in with an identity provider or their mail password finds their credentials locked, as after some passkeys: the first username or password they open asks for their ITFlow password, once, until they sign out. - Admin > Settings > Single Sign-on is gone: the client portal's Microsoft 365 sign-in is now a Microsoft 365 identity provider. A contact's Login of Only with an identity provider (once called With their Microsoft account) signs in only that way, with no password, and is offered when a provider is on for client contacts. - Printing a ticket prints a work order instead of the page as it looks on screen: your letterhead, the client and contact, the site with its access notes, the job's details, its assets, the description, the fill-ins the client can see, the tasks as boxes to tick, the public replies oldest first, and a sign-off with arrival and departure times, lines for the work done and signatures. Internal notes never print. It's Print Work Order in the ticket's menu, or the browser's own print. @@ -79,8 +83,10 @@ Update from Maintenance > Update as usual - this release has four database chang - agent/modals/document/document_view.php uses .itflow-prose and linkGroupsHtml()'s compact mode, which takes $open_up_to (5 by default, 0 for the quick view: always closed). Its Edit goes to agent/document_edit.php, so agent/modals/document/document_edit.php, which only it opened, is gone. - A document's editor is .tinymce-document (agent/modals/document/document_form.php; .tinymce-page on agent/document_edit.php): js/app.js itflowDocumentWriter, the document editor with its own toolbar and itflowProseContentStyle() - .itflow-prose as literal CSS, as the editor is an iframe. The page's editor saves on Ctrl+S (addShortcut), the fields and Markdown box through a keydown on the page; the Markdown Preview has .itflow-prose; Markdown pasted into the editor (js/document_markdown.js) takes .tinymce-document too. Other editors (.tinymce) are as they were. - Database 4.2.5: identity_providers (kind microsoft, google, nextcloud or imap; name, on, agents, contacts, domains, required, client id and secret, tenant, url, port, security, username, redirect_path, used_at). settings.config_azure_client_id and config_azure_client_secret are copied to a microsoft provider for contacts with redirect_path /client/login_microsoft.php, then dropped; users.user_auth_method azure now means only through an identity provider. -- functions/identity_provider.php: the kinds, who a provider covers (identityProviderCovers(), identityProviderFor(), identityProviderRequiredFor(), identityProviderImapFor()), the OpenID Connect code flow with PKCE S256 (identityProviderEndpoints() - Microsoft and Google fixed, Nextcloud from its discovery document; identityProviderAuthorizeUrl(), identityProviderIdentity()) and the IMAP check (identityProviderImapCheck(), DirectoryTree ImapEngine, certificate checked). Microsoft's address is Graph /me userPrincipalName (guests refused), Google's needs email_verified. -- login_provider.php starts a sign-in (?provider=N, a single-use state in the session, ten minutes) and takes the code back, then hands the account to login.php as ?provider_login= with $_SESSION['pending_provider_login'], which signs in through its usual success path - role choice included - with $_SESSION['signed_in_with'] = 'provider' (left out of MFA enforcement as a passkey is) and signed_in_via the provider's name. client/login_microsoft.php serves it for the migrated app's redirect address. IMAP is checked in login.php's password step ('imap'); an administrator's own password still works there. +- functions/identity_provider.php: the kinds, who a provider covers (identityProviderCovers(), identityProviderFor(), identityProviderRequiredFor(), identityProviderImapFor()), the OpenID Connect code flow with PKCE S256 (identityProviderEndpoints() - Microsoft and Google fixed, Nextcloud from its discovery document; identityProviderAuthorizeUrl(), identityProviderIdentity()) and the IMAP check (identityProviderImapCheck(), DirectoryTree ImapEngine, certificate checked). Microsoft's address is Graph /me userPrincipalName (guests refused), Google's needs email_verified and hd (a Workspace account), Nextcloud's needs email_verified. identityProviderPasswordUse() says how an address's password is used ('password', 'mail' or 'provider', by its domain), for portalSignInMethods(), portalSignInHow(), client/join.php, client/login_reset.php, join.php and the portal emails. +- login_provider.php starts a sign-in (?provider=N, a single-use state in the session, ten minutes) and takes the code back, then hands the account to login.php as ?provider_login= with $_SESSION['pending_provider_login'], which signs in through its usual success path - role choice included - with $_SESSION['signed_in_with'] = 'provider' (left out of MFA enforcement as a passkey is) and signed_in_via the provider's name. client/login_microsoft.php serves it for the migrated app's redirect address. IMAP is checked in login.php's password step ('imap'); an administrator's own password still works there. login.php decides a required provider before any password or IMAP check, and after a failure falls back to identityProviderRequiredFor() for the address alone (contacts only without the login key), so the message is the same with or without an account. identityProviderMailLocked() (IDENTITY_PROVIDER_MAIL_TRIES, 5) counts the address's failures with signInAddressFailures() (functions/sign_in.php), by its "Failed sign in as - " log rows, and answers 429 without contacting the server. +- Identity provider client secrets are sealed with secretSeal() / read with secretOpen() (functions/security.php - AES-256-GCM under a key derived from $config_backup_key per purpose, 'enc1:' prefix; the RMM secrets' rmmSecret() and rmmSecretSeal() now use them too, rmmSealKey() is gone). identityProviderSecret() reads a plaintext one saved before as it is, and saving it again seals it ("its secret kept encrypted" in the audit log). 4.2.5 seals the migrated Microsoft secret when it can. A secret is 500 characters at most. +- identityProviderCheck(): Required needs identityProviderRequiredAllowed() (already required, or identity_provider_used_at set); an IMAP provider that is on and new, moved or being turned on must pass identityProviderImapReach() (ImapEngine's ImapConnection, greeting and TLS only, no login), as must turn_identity_provider_on. - Admin: admin/identity_providers.php (list), admin/modals/identity_provider/identity_provider_edit.php (Add and Edit), admin/post/identity_provider.php (save_identity_provider, turn_identity_provider_on / off, delete_identity_provider - locked in the demo). The identity settings page and edit_identity_provider are gone. portalSignInMethods() and identityProviderContactsWording() take an email, to offer only the providers that sign it in; vaultLockedReason() says why the vault is locked. - functions/print_sheet.php draws the work order (ticketWorkOrderHtml()) and spec sheet (assetSpecSheetHtml()) into their pages, hidden on screen; css .itflow-print-sheet hides the rest of the page when printing (the .container-fluid:has() rule). [data-print-page] buttons call window.print() (js/app.js). The ticket's actions bar and menu now show for every agent. - includes/document_editors.php is a document's two editors and the switch between them, shared by agent/modals/document/document_form.php and client/document_add.php (which now posts format, content and markdown, saved through documentPostedContent()). js/document_markdown.js converts at the address its script tag gives (data-markdown-url, client/post.php markdown_to_html and html_to_markdown in the portal). itflowProseContentStyle() moved to js/tinymce_defaults.js; js/portal.js sets up .tinymce-document, and its required check looks in the Markdown box when that is shown. diff --git a/admin/database_updates/4.2.5.php b/admin/database_updates/4.2.5.php index 65674690c..6e5bab4c2 100644 --- a/admin/database_updates/4.2.5.php +++ b/admin/database_updates/4.2.5.php @@ -13,8 +13,8 @@ * * The Microsoft Entra app the client portal signed in with (settings.config_azure_client_id and * config_azure_client_secret) becomes the first provider, for client contacts on any domain, still - * sending them back to /client/login_microsoft.php - the address registered with it - and the two - * settings go. Contacts set to sign in with Microsoft keep that (users.user_auth_method azure), + * sending them back to /client/login_microsoft.php - the address registered with it - with its + * secret sealed (secretSeal()), and the two settings go. Contacts set to sign in with Microsoft keep that (users.user_auth_method azure), * now meaning through an identity provider, without a password. Re-runnable. */ @@ -52,6 +52,10 @@ defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); $itflow_azure_secret = trim((string) ($itflow_azure['config_azure_client_secret'] ?? '')); $itflow_providers = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM identity_providers"))[0] ?? 0); if ($itflow_azure_id !== '' && $itflow_providers === 0) { + // Its secret sealed with this install's key, as one typed in Admin > Identity Providers is (secretSeal()) - kept as it + // was when the install can't make a key, or this run started on code from before it, and read as it is + $itflow_azure_sealed = function_exists('secretSeal') && $itflow_azure_secret !== '' ? secretSeal($itflow_azure_secret, 'identity-provider') : ''; + $itflow_azure_secret = $itflow_azure_sealed !== '' ? $itflow_azure_sealed : $itflow_azure_secret; mysqli_query($mysqli, "INSERT INTO identity_providers SET identity_provider_kind = 'microsoft', identity_provider_name = 'Microsoft 365', identity_provider_enabled = 1, identity_provider_agents = 0, identity_provider_contacts = 1, identity_provider_client_id = '" . mysqli_real_escape_string($mysqli, $itflow_azure_id) . "', diff --git a/admin/identity_providers.php b/admin/identity_providers.php index 3a251743b..b600385af 100644 --- a/admin/identity_providers.php +++ b/admin/identity_providers.php @@ -115,6 +115,15 @@ $add_url = 'modals/identity_provider/identity_provider_edit.php?kind='; $where = ''; } $who = array_filter([$agents ? 'Agents' : '', $contacts ? 'Client contacts' : '']); + // What turning it off does - who goes back to a password, and who has none to go back to + if ($kind && !$kind['oauth']) { + $off_text = 'No one signs in with their mail password until it is on again. The accounts on its email domains go back to their ITFlow password' + . ($contacts ? ' - a contact who never chose one can set one with Forgot password.' : '.'); + } else { + $off_text = 'No one signs in with it until it is on again.' + . ($required ? ' The accounts on its email domains that have an ITFlow password sign in with it meanwhile.' : '') + . ($contacts ? ' A contact who signs in only through an identity provider can\'t, unless another one is on for their address.' : ''); + } ?> @@ -167,7 +176,7 @@ $add_url = 'modals/identity_provider/identity_provider_edit.php?kind='; + data-confirm-text=""> Turn Off diff --git a/admin/modals/identity_provider/identity_provider_edit.php b/admin/modals/identity_provider/identity_provider_edit.php index eeee19ca7..12be3b604 100644 --- a/admin/modals/identity_provider/identity_provider_edit.php +++ b/admin/modals/identity_provider/identity_provider_edit.php @@ -33,7 +33,11 @@ $fields = $kind['fields']; $value = function ($column, $default = '') use ($row) { return $row ? (string) ($row["identity_provider_$column"] ?? $default) : $default; }; -$secret_saved = $row && trim((string) $row['identity_provider_client_secret']) !== ''; +// A saved secret that can't be read - this install's key in config.php changed - has to be typed again +$secret_saved = $row && identityProviderSecret($row) !== ''; +$secret_lost = $row && !$secret_saved && trim((string) $row['identity_provider_client_secret']) !== ''; +// Required once it has signed someone in, so it is known to work (identityProviderRequiredAllowed()) +$required_allowed = identityProviderRequiredAllowed($row); $redirect_uri = identityProviderRedirectUri($row ?: []); $form_id = 'identityProvider' . ($identity_provider_id ?: 'New'); $security = $value('security', 'ssl'); @@ -142,10 +146,15 @@ ob_start();
- > + data-identity-provider-required-switch>
-
Passkeys still work, and an agent with an administrator role keeps their password, to get back in when it is down. Needs email domains.
+
+ + Sign in with it once first, so you know it works - then it can be required. + + Passkeys still work, and an agent with an administrator role keeps their password, to get back in when it is down. Mail passwords (IMAP) on its domains stop working too. Needs email domains. +
@@ -177,10 +186,14 @@ ob_start();
- + placeholder="">
-
A secret runs out - put the new one here before it does.
+ +
The saved secret can't be read - this install's key in config.php was changed. Type it again.
+ +
Kept encrypted with this install's key.
+ @@ -222,7 +235,7 @@ ob_start(); -
Empty port is 993 for SSL/TLS, 143 otherwise. Its certificate has to be a valid one.
+
Empty port is 993 for SSL/TLS, 143 otherwise. Its certificate has to be a valid one - ITFlow tries the server when you save.
diff --git a/admin/modals/portal_user/portal_user_access.php b/admin/modals/portal_user/portal_user_access.php index e4e67428a..ae22c159d 100644 --- a/admin/modals/portal_user/portal_user_access.php +++ b/admin/modals/portal_user/portal_user_access.php @@ -23,6 +23,7 @@ if (!$portal_user) { ?> $user_id = intval($portal_user['user_id']); $name = escapeHtml($portal_user['contact_name']); $methods = portalSignInMethods($portal_user['user_email']); + $password_use = identityProviderPasswordUse($portal_user['user_email'], 2); $archived = !empty($portal_user['client_archived_at']) || !empty($portal_user['contact_archived_at']); $mail_ready = portalMailReady() && filter_var($portal_user['user_email'], FILTER_VALIDATE_EMAIL); ?> @@ -56,7 +57,15 @@ if (!$portal_user) { ?>
-
With a password, they choose their own from an emailed link - the one they had still works too.
+
+ + Their mail server checks their email password (), so there is none to choose here. + + is required for their email domain, so there is no password here. + + With a password, they choose their own from an emailed link - the one they had still works too. + +
diff --git a/admin/post/identity_provider.php b/admin/post/identity_provider.php index 01e4a4633..a5f1efafc 100644 --- a/admin/post/identity_provider.php +++ b/admin/post/identity_provider.php @@ -62,6 +62,14 @@ if (isset($_GET['turn_identity_provider_off']) || isset($_GET['turn_identity_pro redirect('identity_providers.php'); } $identity_provider_id = intval($provider['identity_provider_id']); + // A mail server has to answer before it checks passwords - one that doesn't would turn every one on its domains away + if ($on && $provider['identity_provider_kind'] === 'imap') { + [$reached, $why] = identityProviderImapReach($provider); + if (!$reached) { + flashAlert('' . escapeHtml($provider['identity_provider_name']) . ' is still off - ' . escapeHtml(lcfirst($why)), 'error'); + redirect(); + } + } mysqli_query($mysqli, "UPDATE identity_providers SET identity_provider_enabled = " . ($on ? 1 : 0) . " WHERE identity_provider_id = $identity_provider_id"); logAudit("Identity Provider", "Edit", "$session_name turned identity provider " . escapeSql($provider['identity_provider_name']) . ($on ? ' on' : ' off'), 0, $identity_provider_id); flashAlert('' . escapeHtml($provider['identity_provider_name']) . ' turned ' . ($on ? 'on' : 'off - no one signs in with it'), $on ? 'success' : 'error'); diff --git a/admin/post/portal_users.php b/admin/post/portal_users.php index fd178d87b..db6bf0320 100644 --- a/admin/post/portal_users.php +++ b/admin/post/portal_users.php @@ -49,8 +49,12 @@ if (isset($_GET['portal_user_reset_link'])) { $row = portalUserForRequest($_GET['portal_user_reset_link']); $name = escapeHtml($row['contact_name']); - if (!$row['portal_on'] || $row['user_auth_method'] !== 'local') { - flashAlert("$name " . ($row['portal_on'] ? 'signs in with Microsoft 365 - there is no password here to reset' : "can't sign in - " . lcfirst($row['portal_off_why'])), 'error'); + // Only with an identity provider, or their mail server checks the password, or a provider is required for them (functions/portal.php) + if (!$row['portal_on'] || portalSignInHow($row['user_email'], $row['user_auth_method']) !== '') { + $use = identityProviderPasswordUse($row['user_email'], 2); + $how = $row['user_auth_method'] !== 'local' ? 'signs in only with ' . identityProviderContactsWording($row['user_email']) + : ($use['use'] === 'mail' ? 'signs in with their email password, which their mail server checks (' . $use['name'] . ')' : 'signs in with ' . $use['name'] . ', required for their email domain'); + flashAlert("$name " . ($row['portal_on'] ? escapeHtml($how) . ' - there is no password here to reset' : "can't sign in - " . lcfirst($row['portal_off_why'])), 'error'); redirect(); } if (!portalMailPasswordReset($row['user_id'])) { @@ -186,7 +190,7 @@ if (isset($_POST['bulk_portal_reset_links'])) { $count++; } - flashAlert("Emailed " . portalUsersCount($count) . " a link to choose a new password" . ($skipped ? " - not $skipped who " . ($skipped === 1 ? 'signs' : 'sign') . " in with Microsoft 365, can't sign in, or can't be emailed" : ''), $skipped ? 'warning' : 'success'); + flashAlert("Emailed " . portalUsersCount($count) . " a link to choose a new password" . ($skipped ? " - not $skipped who " . ($skipped === 1 ? 'signs' : 'sign') . " in without a password here, can't sign in, or can't be emailed" : ''), $skipped ? 'warning' : 'success'); redirect(); diff --git a/client/functions.php b/client/functions.php index cdd614d86..7a5851c95 100644 --- a/client/functions.php +++ b/client/functions.php @@ -654,8 +654,9 @@ function portalContactInvite($contact_id, $method, $by) { if (!$contact) { return ['ok' => false, 'error' => "That person isn't here", 'emailed' => false]; } - if (!isset(portalSignInMethods($contact['contact_email'])[$method])) { - $method = 'local'; + $methods = portalSignInMethods($contact['contact_email']); + if (!isset($methods[$method])) { + $method = array_key_first($methods); } $name = (string) $contact['contact_name']; $email = trim((string) $contact['contact_email']); diff --git a/client/join.php b/client/join.php index f6ddf7a3e..22aa0b046 100644 --- a/client/join.php +++ b/client/join.php @@ -4,7 +4,8 @@ * Joining - from an invite (ours, or a colleague's in the portal) or the link * to finish signing up: ?invite=&token=. The person puts in their name, job * title, phone and a password - or, when an identity provider signs in their address, - * chooses that instead - and is made a contact who can sign in + * chooses that instead; no password where their mail server checks it (IMAP) or a + * provider is required for their domain - and is made a contact who can sign in * (portalInviteAccept(), functions/portal_invite.php). Then they sign in on * the usual page. A link that has run out, been used or cancelled says so, * and what to do instead. @@ -42,6 +43,9 @@ $invite = $link['row']; $error = ''; $in = ['name' => '', 'title' => '', 'phone' => '']; +// Whether a password is chosen here - not where their mail server checks it, or a provider is required for them (functions/identity_provider.php) +$password_use = $invite ? identityProviderPasswordUse($invite['invite_email'], 2)['use'] : 'password'; + if ($invite && $link['state'] === 'pending') { // Only an identity provider that signs in their address (functions/identity_provider.php) $methods = portalSignInMethods($invite['invite_email']); @@ -62,9 +66,8 @@ if ($invite && $link['state'] === 'pending') { ], $error); if ($contact_id) { $first = strtok(trim(preg_replace('/\s+/', ' ', $in['name'])), ' '); - $_SESSION['login_message'] = "Welcome, $first - your account is ready. " . (isset($methods[$method]) && $method === 'azure' - ? 'Sign in with your ' . identityProviderContactsWording($invite['invite_email']) . ' account below.' - : 'Sign in with ' . $invite['invite_email'] . ' and your new password.'); + $how = portalSignInHow($invite['invite_email'], isset($methods[$method]) ? $method : array_key_first($methods)); + $_SESSION['login_message'] = "Welcome, $first - your account is ready. " . ($how !== '' ? $how : 'Sign in with ' . $invite['invite_email'] . ' and your new password.'); $_SESSION['login_message_type'] = 'success'; redirect("/login.php"); } @@ -80,7 +83,9 @@ $ask = $by !== '' ? "Ask $by to send it again." : 'Ask your company\'s primary c $notes = [ 'gone' => ["That link doesn't work", 'It may have been copied only in part - or a newer email replaced it, so use the link in the latest one.'], 'expired' => ['That link has run out', $signup ? 'Links to finish signing up work for ' . PORTAL_SIGNUP_LINK_HOURS . ' hours - ask for a new one.' : 'Invites work for ' . PORTAL_INVITE_LINK_DAYS . " days. $ask"], - 'accepted' => ["You've joined already", 'Sign in with ' . ($invite['invite_email'] ?? 'your email address') . '. Forgot your password? Choose Forgot password on the sign-in page.'], + 'accepted' => ["You've joined already", $password_use === 'password' + ? 'Sign in with ' . ($invite['invite_email'] ?? 'your email address') . '. Forgot your password? Choose Forgot password on the sign-in page.' + : portalSignInHow($invite['invite_email'], 'local')], 'cancelled' => ['That invite was cancelled', $ask], ]; $state = $link['state']; @@ -158,20 +163,31 @@ $title = $state === 'pending' ? ($signup ? 'Finish signing up' : 'Join ' . $invi
- -
- - > -
-
- - -
+ + +

Accounts on sign in with here, so there is no password to choose.

+ + + + +

You sign in with your email password - the one for your mailbox - so there is no password to choose here.

+ + +
+ + > +
+
+ + +
+ - - -
or, with no password here
- + + +
or, with no password here
+ + diff --git a/client/login_reset.php b/client/login_reset.php index 0b9d6864b..e919d58de 100644 --- a/client/login_reset.php +++ b/client/login_reset.php @@ -8,7 +8,9 @@ * runs out: an hour for Forgot password, a week for an invite * (functions/portal.php). Using it spends it. Asking for a link always says * the same thing, whether or not the address has an account, and sends at - * most one per account every PORTAL_RESET_REQUEST_GAP_MINUTES. + * most one per account every PORTAL_RESET_REQUEST_GAP_MINUTES. On a domain + * whose password isn't one here - its mail server checks it (IMAP), or a + * provider is required - it says how they sign in instead, and sends nothing. */ header("Content-Security-Policy: default-src 'self'; img-src 'self' data:"); @@ -52,8 +54,17 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password_reset_email_ $asked = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM logs WHERE log_type = 'Client Login' AND log_action = 'Reset Requested' AND log_ip = '$ip' AND log_created_at > NOW() - INTERVAL 10 MINUTE"))[0]); + // Where the password isn't ITFlow's - their mail server checks it, or a provider is required - there is nothing to reset. + // Said by the address's domain, so it tells no one whether the address has an account (functions/portal.php) + $how = filter_var($email, FILTER_VALIDATE_EMAIL) ? portalSignInHow($email, 'local') : ''; + $row = null; - if ($asked < 10 && filter_var($email, FILTER_VALIDATE_EMAIL)) { + if ($how !== '') { + $reset_log('Reset Requested', 'Asked for a portal password link for ' . mb_substr($email, 0, 200) . ' - none sent, its domain doesn\'t sign in with a password here', 0, 0); + $message = 'There is no password to reset here for an address on ' . identityProviderEmailDomain($email) . '. ' . $how + . (identityProviderPasswordUse($email, 2)['use'] === 'mail' ? ' To change your email password, ask whoever looks after your email.' : ''); + $message_type = 'info'; + } elseif ($asked < 10 && filter_var($email, FILTER_VALIDATE_EMAIL)) { $email_sql = escapeSql($email); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_id, user_email, contact_name, contact_client_id FROM users JOIN contacts ON contact_user_id = user_id @@ -62,29 +73,36 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password_reset_email_ AND contact_archived_at IS NULL AND client_archived_at IS NULL LIMIT 1")); } - $reset_log('Reset Requested', 'Asked for a portal password link for ' . mb_substr($email, 0, 200), intval($row['user_id'] ?? 0), intval($row['contact_client_id'] ?? 0)); + if ($how === '') { + $reset_log('Reset Requested', 'Asked for a portal password link for ' . mb_substr($email, 0, 200), intval($row['user_id'] ?? 0), intval($row['contact_client_id'] ?? 0)); - if ($row) { - $user_id = intval($row['user_id']); - $recent = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM logs WHERE log_type = 'Client Login' AND log_action = 'Reset Sent' - AND log_user_id = $user_id AND log_created_at > NOW() - INTERVAL " . PORTAL_RESET_REQUEST_GAP_MINUTES . " MINUTE"))[0]); - if (!$recent) { - portalMailPasswordReset($user_id); - $reset_log('Reset Sent', 'Emailed a portal password link to ' . $row['user_email'], $user_id, intval($row['contact_client_id'])); + if ($row) { + $user_id = intval($row['user_id']); + $recent = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM logs WHERE log_type = 'Client Login' AND log_action = 'Reset Sent' + AND log_user_id = $user_id AND log_created_at > NOW() - INTERVAL " . PORTAL_RESET_REQUEST_GAP_MINUTES . " MINUTE"))[0]); + if (!$recent && portalMailPasswordReset($user_id)) { + $reset_log('Reset Sent', 'Emailed a portal password link to ' . $row['user_email'], $user_id, intval($row['contact_client_id'])); + } } - } - $message = "If there is a client portal account for that address, a link to reset its password is on its way. It works for " . PORTAL_RESET_LINK_MINUTES . " minutes."; - $message_type = 'success'; + $message = "If there is a client portal account for that address, a link to reset its password is on its way. It works for " . PORTAL_RESET_LINK_MINUTES . " minutes."; + $message_type = 'success'; + } } elseif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password_reset_set_password'])) { $link = ['email' => (string) ($_POST['email'] ?? ''), 'token' => (string) ($_POST['token'] ?? ''), 'client' => intval($_POST['client'] ?? 0)]; $link_user = portalPasswordLinkUser($link['email'], $link['token'], $link['client']); $password = (string) ($_POST['new_password'] ?? ''); + $how = $link_user ? portalSignInHow($link_user['user_email'], 'local') : ''; if (!$link_user) { $message = 'That link has run out or has been used already. Ask for a new one below.'; + } elseif ($how !== '') { + // Sent before their mail server or a required provider took over - a password here wouldn't sign them in + $link_user = null; + $message = "There is no password to set here any more. $how"; + $message_type = 'info'; } elseif (($problem = userPasswordProblem($password)) !== '') { $message = $problem; } elseif ($password !== (string) ($_POST['confirm_password'] ?? '')) { @@ -105,8 +123,13 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password_reset_email_ $link = ['email' => (string) ($_GET['email'] ?? ''), 'token' => (string) $_GET['token'], 'client' => intval($_GET['client'] ?? 0)]; $link_user = portalPasswordLinkUser($link['email'], $link['token'], $link['client']); + $how = $link_user ? portalSignInHow($link_user['user_email'], 'local') : ''; if (!$link_user) { $message = 'That link has run out or has been used already.' . ($can_email ? ' Ask for a new one below.' : ' Ask us for a new one.'); + } elseif ($how !== '') { + $link_user = null; + $message = "There is no password to set here any more. $how"; + $message_type = 'info'; } } diff --git a/functions/identity_provider.php b/functions/identity_provider.php index 39b817ab0..d0aaae7d6 100644 --- a/functions/identity_provider.php +++ b/functions/identity_provider.php @@ -8,12 +8,17 @@ * Who a provider signs in goes by email domain: each provider is for agents, client contacts or * both, and lists the email domains it signs in - any account on them can use it. Microsoft 365 * and Google can leave the list empty and sign in any account, as both vouch for the address - * (Microsoft's sign-in name is on a domain its directory has proved it owns, and Google says when - * an address is verified); Nextcloud and IMAP need it, as a Nextcloud's users can set their own email - * address, and a mail server only says whether a password is right. - * A provider made required turns off password sign-in for the accounts on its domains - an - * agent with an administrator role keeps theirs, to get back in when it is down. No one is made - * an account by signing in: an agent, or a contact with portal access, has to be there already. + * (Microsoft's sign-in name is on a domain its directory has proved it owns, and Google's is a + * Workspace account - hd - on a domain the Workspace has proved it owns: a personal Google account + * can be made with any address, so it is turned away); Nextcloud and IMAP need it, as a + * Nextcloud's users can set their own email address, and a mail server only says whether a + * password is right. + * A provider made required turns off password sign-in for the accounts on its domains, mail + * passwords (IMAP) included - an agent with an administrator role keeps theirs, to get back in + * when it is down. It can be made required once it has signed someone in, so it is known to work. + * The sign-in page decides it before any password is looked at, and says the same for an address + * on its domains whatever was typed, account or not. No one is made an account by signing in: an + * agent, or a contact with portal access, has to be there already. * * Microsoft 365, Google and Nextcloud sign in by OpenID Connect's code flow (login_provider.php): * the button on the sign-in page goes to the provider, which sends them back with a code; ITFlow @@ -21,12 +26,19 @@ * who they are - Microsoft Graph's /me, or the userinfo endpoint. Their own two-step sign-in * stands in for ITFlow's. IMAP is a password, so it is checked in the password step of * login.php instead of ITFlow's - against the mail server - and the two-step code is still asked. - * An administrator's ITFlow password still works too, for when the mail server is down. + * An administrator's ITFlow password still works too, for when the mail server is down. After + * IDENTITY_PROVIDER_MAIL_TRIES wrong passwords for an address in SIGN_IN_WINDOW_MINUTES the mail + * server isn't asked again until they are older - spread over many IP addresses, guesses would + * otherwise go on to it, and its own lockout would land on ITFlow's address. * * An agent signed in through a provider has their credentials locked until they type their ITFlow * password once (vaultUnlock()), as the vault key is opened with it and the provider never sees it. + * The app's secret is kept sealed with this install's key (secretSeal()). */ +/** Wrong passwords for one address, in SIGN_IN_WINDOW_MINUTES, before its mail server (an IMAP provider) isn't asked. */ +const IDENTITY_PROVIDER_MAIL_TRIES = 5; + /** Whether the database has identity providers yet (4.2.5). */ function identityProvidersReady() { global $mysqli; @@ -207,6 +219,39 @@ function identityProviderAdminRole($role_id) { return intval($admin[0] ?? 0) === 1; } +/** + * How an address's password is used here, by its domain - for what joining, Forgot password and + * the welcome emails say: 'password' (its ITFlow password), 'mail' (its mailbox's, which an IMAP + * provider checks) or 'provider' (none - a required provider signs it in). ['use' => ..., 'name' + * => the provider's name, '' for password]. 1 an agent, 2 a client contact. + */ +function identityProviderPasswordUse($email, $user_type, $role_id = 0) { + $required = identityProviderRequiredFor($email, $user_type, $role_id); + if ($required) { + return ['use' => 'provider', 'name' => (string) $required['identity_provider_name']]; + } + $imap = identityProviderImapFor($email, $user_type); + if ($imap) { + return ['use' => 'mail', 'name' => (string) $imap['identity_provider_name']]; + } + return ['use' => 'password', 'name' => '']; +} + +/** + * Whether the sign-in page stops asking the mail server about this address for now - an IMAP + * provider checks its password, for one of $user_types, and it has had IDENTITY_PROVIDER_MAIL_TRIES + * wrong ones in SIGN_IN_WINDOW_MINUTES. Counted by the address, so it is the same whether or not + * it has an account here. + */ +function identityProviderMailLocked($email, array $user_types) { + foreach ($user_types as $user_type) { + if (identityProviderImapFor($email, $user_type)) { + return signInAddressFailures($email) >= IDENTITY_PROVIDER_MAIL_TRIES; + } + } + return false; +} + /** The providers with a button on the sign-in page - Microsoft 365, Google and Nextcloud that sign anyone in here. */ function identityProviderButtons() { return array_values(array_filter(identityProvidersOn(), function ($row) { @@ -241,6 +286,16 @@ function identityProviderContactsWording($email = null) { return $names ? implode(' or ', $names) : 'an identity provider'; } +/** A provider's client secret, as typed (kept sealed - secretSeal()). '' when there is none, or it can't be read: config.php's key was changed. */ +function identityProviderSecret(array $row) { + return secretOpen((string) ($row['identity_provider_client_secret'] ?? ''), 'identity-provider'); +} + +/** A client secret sealed for keeping - '' when this install has no key to do it with. */ +function identityProviderSecretSeal(#[\SensitiveParameter] $secret) { + return secretSeal((string) $secret, 'identity-provider'); +} + /** A Nextcloud's address, as typed - https, no trailing slash. */ function identityProviderNextcloudUrl(array $row) { return rtrim(trim((string) ($row['identity_provider_url'] ?? '')), '/'); @@ -364,6 +419,10 @@ function identityProviderAuthorizeUrl(array $row, array $endpoints, $state, $cha * secret and the PKCE verifier, then the provider is asked who it is for. */ function identityProviderIdentity(array $row, array $endpoints, $code, $verifier) { + $secret = identityProviderSecret($row); + if ($secret === '') { + return ['error' => "its client secret can't be read - this install's key in config.php was changed, so type the secret again in Admin > Identity Providers"]; + } $fields = [ 'grant_type' => 'authorization_code', 'code' => (string) $code, @@ -373,9 +432,9 @@ function identityProviderIdentity(array $row, array $endpoints, $code, $verifier ]; $headers = []; if ($endpoints['auth'] === 'basic') { - $headers[] = 'Authorization: Basic ' . base64_encode(rawurlencode((string) $row['identity_provider_client_id']) . ':' . rawurlencode((string) $row['identity_provider_client_secret'])); + $headers[] = 'Authorization: Basic ' . base64_encode(rawurlencode((string) $row['identity_provider_client_id']) . ':' . rawurlencode($secret)); } else { - $fields['client_secret'] = (string) $row['identity_provider_client_secret']; + $fields['client_secret'] = $secret; } [$status, $token] = identityProviderHttp('POST', $endpoints['token'], $fields, $headers); if (empty($token['access_token']) || !is_string($token['access_token'])) { @@ -399,12 +458,13 @@ function identityProviderIdentity(array $row, array $endpoints, $code, $verifier } else { $email = (string) ($who['email'] ?? ''); $name = (string) ($who['name'] ?? ''); - if ($kind === 'google' && ($who['email_verified'] ?? false) !== true && ($who['email_verified'] ?? '') !== 'true') { - return ['error' => "Google hasn't verified the address $email"]; + // Verified, and said so - its OIDC app sends email_verified with the email scope + if (in_array($kind, ['google', 'nextcloud'], true) && ($who['email_verified'] ?? false) !== true && ($who['email_verified'] ?? '') !== 'true') { + return ['error' => ($kind === 'google' ? 'Google' : 'Nextcloud') . " didn't say it has verified the address $email"]; } - // A Nextcloud that says the address isn't verified is taken at its word - if ($kind === 'nextcloud' && array_key_exists('email_verified', $who) && $who['email_verified'] !== true && $who['email_verified'] !== 'true') { - return ['error' => "Nextcloud hasn't verified the address $email"]; + // A Workspace's own account - anyone can make a personal Google account with any address, and verify it + if ($kind === 'google' && trim((string) ($who['hd'] ?? '')) === '') { + return ['error' => "$email is a personal Google account, not one in a Google Workspace"]; } } $email = strtolower(trim($email)); @@ -441,6 +501,46 @@ function identityProviderAccounts(array $row, $email) { return $accounts; } +/** Where an IMAP provider's mail server is, for ImapEngine - host, port, encryption, a valid certificate, ten seconds. */ +function identityProviderImapServer(array $row) { + $security = (string) ($row['identity_provider_security'] ?? 'ssl'); + return [ + 'host' => (string) $row['identity_provider_url'], + 'port' => intval($row['identity_provider_port']) ?: ($security === 'ssl' ? 993 : 143), + 'encryption' => $security === 'none' ? '' : $security, + 'validate_cert' => true, + 'timeout' => 10, + ]; +} + +/** + * Whether ITFlow reaches an IMAP provider's mail server and it answers as one - over TLS with a + * valid certificate unless its security is None - without signing in: [ok, why not, in words]. + * Asked when one is saved, as a mistyped server would turn every password on its domains away. + */ +function identityProviderImapReach(array $row) { + require_once dirname(__DIR__) . '/libs/vendor/autoload.php'; + $server = identityProviderImapServer($row); + $where = $server['host'] . ':' . $server['port']; + $connection = new \DirectoryTree\ImapEngine\Connection\ImapConnection(new \DirectoryTree\ImapEngine\Connection\Streams\ImapStream()); + try { + $connection->connect($server['host'], $server['port'], $server); + } catch (\Throwable $e) { + $why = trim(preg_replace('/\s*\(\)$/', '', $e->getMessage())); + if ($server['encryption'] !== '' && (str_ends_with($e->getMessage(), '()') || stripos($why, 'TLS') !== false)) { + $why = "TLS didn't work - its certificate may not be a valid one for $server[host], or it doesn't take " . ($server['encryption'] === 'ssl' ? 'SSL/TLS' : 'STARTTLS') . " on port $server[port]"; + } + return [false, "ITFlow couldn't reach the mail server at $where - " . mb_substr($why, 0, 200)]; + } + try { + $connection->logout(); + $connection->disconnect(); + } catch (\Throwable $e) { + // It answered - that was the question + } + return [true, '']; +} + /** The name an IMAP server is given for this address - the address, or the part before the @. */ function identityProviderImapUsername(array $row, $email) { return ($row['identity_provider_username'] ?? '') === 'local' ? substr((string) $email, 0, strrpos((string) $email, '@')) : (string) $email; @@ -460,13 +560,7 @@ function identityProviderImapCheck(array $row, $email, #[\SensitiveParameter] $p return $checked[$key]; } require_once dirname(__DIR__) . '/libs/vendor/autoload.php'; - $security = (string) ($row['identity_provider_security'] ?? 'ssl'); - $mailbox = new \DirectoryTree\ImapEngine\Mailbox([ - 'host' => (string) $row['identity_provider_url'], - 'port' => intval($row['identity_provider_port']) ?: ($security === 'ssl' ? 993 : 143), - 'encryption' => $security === 'none' ? '' : $security, - 'validate_cert' => true, - 'timeout' => 10, + $mailbox = new \DirectoryTree\ImapEngine\Mailbox(identityProviderImapServer($row) + [ 'username' => identityProviderImapUsername($row, $email), 'password' => (string) $password, ]); @@ -544,6 +638,8 @@ function identityProviderCheck(array $in, ?array $before): array $required = $kind['oauth'] && intval($in['required'] ?? 0) === 1 ? 1 : 0; if ($required && !$domains) { $errors['required'] = 'List the email domains it is required for.'; + } elseif ($required && !identityProviderRequiredAllowed($before)) { + $errors['required'] = 'Sign in with it once before making it required, so you know it works - then passwords on its domains stop working.'; } $client_id = $secret = $tenant = $url = ''; @@ -560,12 +656,22 @@ function identityProviderCheck(array $in, ?array $before): array } elseif (strlen($client_id) > 255 || preg_match('/\s/', $client_id)) { $errors['client_id'] = 'That isn\'t a client ID - copy it again, with no spaces.'; } - $secret = (string) ($in['client_secret'] ?? ''); - $secret = trim($secret) !== '' ? trim($secret) : (string) ($before['identity_provider_client_secret'] ?? ''); - if ($secret === '') { - $errors['client_secret'] = $kind_key === 'microsoft' ? 'And a secret for it, from Certificates & secrets - its Value, not its ID.' : 'And its client secret.'; - } elseif (strlen($secret) > 1000) { + // Sealed when one is typed; left empty, the saved one stays as it is kept + $typed = trim((string) ($in['client_secret'] ?? '')); + if ($typed === '') { + $secret = $before && identityProviderSecret($before) !== '' ? (string) $before['identity_provider_client_secret'] : ''; + if ($secret === '') { + $errors['client_secret'] = $before && trim((string) $before['identity_provider_client_secret']) !== '' + ? 'The saved secret can\'t be read - this install\'s key in config.php was changed. Type it again.' + : ($kind_key === 'microsoft' ? 'And a secret for it, from Certificates & secrets - its Value, not its ID.' : 'And its client secret.'); + } + } elseif (strlen($typed) > 500) { $errors['client_secret'] = 'That is too long for a client secret - copy it again.'; + } else { + $secret = identityProviderSecretSeal($typed); + if ($secret === '') { + $errors['client_secret'] = 'ITFlow keeps the secret encrypted with its own key, and couldn\'t make one - config.php needs to be writable by the web server once. See Maintenance > Backup.'; + } } } if (in_array('tenant', $fields, true)) { @@ -627,9 +733,35 @@ function identityProviderCheck(array $in, ?array $before): array } } + // A mail server that is on has to answer - one mistyped turns away every password on its domains + if (!$errors && $kind_key === 'imap' && $after['identity_provider_enabled'] === 1 && identityProviderImapMoved($before, $after)) { + [$reached, $why] = identityProviderImapReach($after); + if (!$reached) { + $errors['url'] = $why . '. Check the server, port and security - or save it turned off for now.'; + } + } + return [$after, $errors]; } +/** Whether an IMAP provider is new, or its server, port or security changed, or it is being turned on - when its server is tried. */ +function identityProviderImapMoved(?array $before, array $after) { + if (!$before || intval($before['identity_provider_enabled']) !== 1) { + return true; + } + foreach (['identity_provider_url', 'identity_provider_port', 'identity_provider_security'] as $column) { + if ((string) $before[$column] !== (string) $after[$column]) { + return true; + } + } + return false; +} + +/** Whether a provider can be made required - once it has signed someone in, so it is known to work (or it is already). */ +function identityProviderRequiredAllowed(?array $row) { + return $row && (intval($row['identity_provider_required']) === 1 || !empty($row['identity_provider_used_at'])); +} + /** Save an identity provider's row - a new one when $identity_provider_id is 0. Its id. */ function identityProviderWrite(array $after, int $identity_provider_id = 0): int { @@ -664,6 +796,15 @@ function identityProviderChangeLines(array $before, array $after): array foreach ($labels as $column => $label) { $old = (string) ($before[$column] ?? ''); $new = (string) ($after[$column] ?? ''); + if ($column === 'identity_provider_client_secret') { + // Sealed afresh each time it is typed - the same secret typed again isn't a new one, though one kept before sealing now is + if (identityProviderSecret($before) === identityProviderSecret($after)) { + if (!str_starts_with($old, 'enc1:') && str_starts_with($new, 'enc1:')) { + $lines[] = 'its secret kept encrypted'; + } + continue; + } + } if ($old === $new) { continue; } diff --git a/functions/portal.php b/functions/portal.php index 0f3947ab9..b9b94fb8d 100644 --- a/functions/portal.php +++ b/functions/portal.php @@ -203,8 +203,9 @@ function portalUserAccessOn($user_id, $method) { if (!empty($row['client_archived_at']) || !empty($row['contact_archived_at'])) { return ($row['client_archived_at'] ? 'Their client' : 'The contact') . ' is archived - restore it first'; } - if (!isset(portalSignInMethods($row['user_email'])[$method])) { - $method = 'local'; + $methods = portalSignInMethods($row['user_email']); + if (!isset($methods[$method])) { + $method = array_key_first($methods); } $error = ''; if (userCheckIdentity(['name' => $row['contact_name'], 'email' => $row['user_email']], $row['user_id'], $error) === null) { @@ -217,10 +218,17 @@ function portalUserAccessOn($user_id, $method) { /* * The ways a portal user can sign in here - a password (and any identity provider on their email's * domain), and only through a provider, when one is on for contacts - for this email address, when - * it is given. method => label. + * it is given. method => label. On a domain whose mail server checks passwords (an IMAP provider) + * the password is their mailbox's; where a provider is required there is no password, so only it. */ function portalSignInMethods($email = null) { - $methods = ['local' => 'With a password']; + $use = $email === null ? 'password' : identityProviderPasswordUse($email, 2)['use']; + $methods = []; + if ($use === 'mail') { + $methods['local'] = 'With their email password'; + } elseif ($use === 'password') { + $methods['local'] = 'With a password'; + } if (identityProviderNamesForContacts($email)) { $methods['azure'] = 'Only with ' . identityProviderContactsWording($email) . ' - no password'; } @@ -311,8 +319,9 @@ function portalMailAccountChange($email, $name, $change) { /** * Invite a contact to the client portal - a link to set their password (good - * for PORTAL_INVITE_LINK_DAYS, the reset page's own link), or for a Microsoft - * account a link to the sign-in page. Never a password. $by is who gave them + * for PORTAL_INVITE_LINK_DAYS, the reset page's own link), or when they don't + * sign in with a password here (portalSignInHow()) a link to the sign-in page + * and how. Never a password. $by is who gave them * access, raw - a primary contact in the portal, or '' when it was us. * False when it can't go. */ @@ -328,14 +337,15 @@ function portalMailInvite($user_id, $by = '') { $company_name = (string) (billingCompany()['company_name'] ?? ''); $by = trim((string) $by); $who = $by !== '' ? $by : $company_name; - if ($row['user_auth_method'] === 'local') { + $how = portalSignInHow($row['user_email'], $row['user_auth_method']); + $set_password = $how === ''; + if ($set_password) { $button = ['label' => 'Set your password', 'url' => portalPasswordLink($user_id, PORTAL_INVITE_LINK_DAYS * 1440)]; $how = 'Set a password with the button below, then sign in with this email address.'; $after = 'The link works once, for ' . PORTAL_INVITE_LINK_DAYS . ' days. After that, choose Forgot password on the sign-in page.'; } else { portalPasswordLinkClear($user_id); $button = ['label' => 'Sign in', 'url' => "https://$config_base_url/login.php"]; - $how = 'Sign in with your ' . identityProviderContactsWording($row['user_email']) . ' account - choose its button on the sign-in page.'; $after = 'Questions? Reply to this email.'; } return (bool) emailQueue([['email' => $row['user_email'], 'name' => $row['contact_name'], @@ -346,16 +356,36 @@ function portalMailInvite($user_id, $by = '') { 'summary' => ['Sign in as' => (string) $row['user_email']], 'button' => $button, 'after' => [$after], - ], ['sensitive' => $row['user_auth_method'] === 'local']); + ], ['sensitive' => $set_password]); } -/** A Forgot password link for a portal user, good for PORTAL_RESET_LINK_MINUTES. False when it can't go. */ +/** + * How a portal user with this address and way of signing in (users.user_auth_method) signs in, in + * a sentence for them - '' when it is with a password here, which they set from an emailed link. + * On a domain whose mail server checks passwords (an IMAP provider) it is their email password; + * where a provider is required, or they sign in only through one, it is its button. + */ +function portalSignInHow($email, $method) { + $use = identityProviderPasswordUse($email, 2)['use']; + if ($method === 'local' && $use === 'mail') { + return 'Sign in with ' . $email . ' and your email password - the one for your mailbox.'; + } + if ($method !== 'local' || $use === 'provider') { + return 'Sign in with your ' . identityProviderContactsWording($email) . ' account - choose its button on the sign-in page.'; + } + return ''; +} + +/** + * A Forgot password link for a portal user, good for PORTAL_RESET_LINK_MINUTES. False when it can't + * go - or when the password here isn't the one they sign in with (portalSignInHow()). + */ function portalMailPasswordReset($user_id) { global $mysqli; $user_id = intval($user_id); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_email, contact_name FROM users JOIN contacts ON contact_user_id = user_id WHERE user_id = $user_id AND user_type = 2 AND user_auth_method = 'local' LIMIT 1")); - if (!$row || !portalMailReady()) { + if (!$row || !portalMailReady() || portalSignInHow($row['user_email'], 'local') !== '') { return false; } $company_name = (string) (billingCompany()['company_name'] ?? ''); diff --git a/functions/portal_invite.php b/functions/portal_invite.php index c2aa1b940..3a40e8d87 100644 --- a/functions/portal_invite.php +++ b/functions/portal_invite.php @@ -432,16 +432,19 @@ function portalInviteAccept(array $invite, array $in, &$error = '') { $title = trim(mb_substr((string) ($in['title'] ?? ''), 0, 200)); $phone = substr(preg_replace('/[^0-9]/', '', (string) ($in['phone'] ?? '')), 0, 200); $method = (string) ($in['method'] ?? 'local'); - if (!isset(portalSignInMethods($email)[$method])) { - $method = 'local'; + $methods = portalSignInMethods($email); + if (!isset($methods[$method])) { + $method = array_key_first($methods); } + // Their mailbox's password, on a domain an IMAP provider checks - none is chosen here + $choose_password = $method === 'local' && portalSignInHow($email, 'local') === ''; $password = (string) ($in['password'] ?? ''); if ($name === '') { $error = 'Put in your name.'; return 0; } - if ($method === 'local') { + if ($choose_password) { if (($problem = userPasswordProblem($password)) !== '') { $error = $problem; return 0; @@ -501,8 +504,9 @@ function portalInviteAccept(array $invite, array $in, &$error = '') { WHERE contact_id = $contact_id AND contact_client_id = $client_id"); } - // Their portal account - a password, or only an identity provider (functions/identity_provider.php) - $hash = escapeSql(password_hash($method === 'local' ? $password : randomString(32), PASSWORD_DEFAULT)); + // Their portal account - a password, or only an identity provider (functions/identity_provider.php). Where the mail server + // checks it, the password here is a random one nobody knows - if that provider goes, Forgot password sets one + $hash = escapeSql(password_hash($choose_password ? $password : randomString(32), PASSWORD_DEFAULT)); $user_id = intval($who['user_id'] ?? 0); if ($user_id) { mysqli_query($mysqli, "UPDATE users SET user_name = '$name_sql', user_email = '$email_sql', user_password = '$hash', user_auth_method = '$method', @@ -789,7 +793,7 @@ function portalSignupRequest($email, $ip, $user_agent) { return 'sent'; } -/** Tell someone who tried to sign up that they have an account - with a link to set a new password, or for Microsoft how to sign in. */ +/** Tell someone who tried to sign up that they have an account - with a link to set a new password, or when they don't sign in with one here how they do. */ function portalMailSignupExists($user_id) { global $mysqli, $config_base_url; $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_email, user_auth_method, contact_name FROM users JOIN contacts ON contact_user_id = user_id @@ -798,13 +802,14 @@ function portalMailSignupExists($user_id) { return false; } $company_name = (string) (billingCompany()['company_name'] ?? ''); - $local = $row['user_auth_method'] === 'local'; + $how = portalSignInHow($row['user_email'], $row['user_auth_method']); + $local = $how === ''; return (bool) emailQueue([['email' => $row['user_email'], 'name' => $row['contact_name'], 'footnote' => 'You received this because someone tried to sign up for the client portal with this address.']], "You already have a $company_name client portal account", [ 'kind' => 'Client portal', 'tone' => 'primary', 'preview' => 'Sign in with the account you have', 'title' => "You already have a $company_name client portal account", 'intro' => ["Someone - probably you - tried to sign up for the $company_name client portal with this address, but it has an account already.", - $local ? 'Forgot your password? Choose a new one with the button below.' : 'Sign in with your ' . identityProviderContactsWording($row['user_email']) . ' account - choose its button on the sign-in page.'], + $local ? 'Forgot your password? Choose a new one with the button below.' : $how], 'summary' => ['Account' => (string) $row['user_email']], 'button' => $local ? ['label' => 'Set a new password', 'url' => portalPasswordLink($user_id, PORTAL_RESET_LINK_MINUTES)] : ['label' => 'Sign in', 'url' => "https://$config_base_url/login.php"], 'after' => [$local ? 'The link works once, for the next ' . PORTAL_RESET_LINK_MINUTES . ' minutes. If you did not ask, ignore this email - your account stays as it is.' : 'If you did not ask, ignore this email - your account stays as it is.'], diff --git a/functions/rmm.php b/functions/rmm.php index dcc27c908..a12582f00 100644 --- a/functions/rmm.php +++ b/functions/rmm.php @@ -222,42 +222,18 @@ function rmmProviderUsable(?array $provider): bool /** * A provider's secret, as typed - its api_key or api_secret. A kind that seals them (seal) keeps - * them encrypted with this install's key (backupEncryptionKey(), in config.php); one saved before + * them encrypted with this install's key (secretSeal(), functions/security.php); one saved before * it did is read as it is. '' when it can't be read - config.php's key was changed. */ function rmmSecret(array $provider, string $field): string { - $stored = (string) ($provider["rmm_provider_$field"] ?? ''); - if (!str_starts_with($stored, 'enc1:')) { - return $stored; - } - $raw = base64_decode(substr($stored, 5), true); - $key = rmmSealKey(); - if ($raw === false || strlen($raw) < 29 || $key === '') { - return ''; - } - $plain = openssl_decrypt(substr($raw, 28), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($raw, 0, 12), substr($raw, 12, 16)); - return $plain === false ? '' : $plain; + return secretOpen((string) ($provider["rmm_provider_$field"] ?? ''), 'rmm'); } /** A secret encrypted for keeping (rmmSecret() reads it) - '' when this install has no key to do it with. */ function rmmSecretSeal(string $plain): string { - $key = rmmSealKey(); - if ($key === '' || $plain === '') { - return ''; - } - $iv = random_bytes(12); - $tag = ''; - $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, '', 16); - return $cipher === false ? '' : 'enc1:' . base64_encode($iv . $tag . $cipher); -} - -/** The key secrets are sealed with - from this install's key, so a backup restored with it reads them. */ -function rmmSealKey(): string -{ - $install = function_exists('backupEncryptionKey') ? backupEncryptionKey() : ''; - return $install === '' ? '' : hash('sha256', "itflow-rmm-secrets|$install", true); + return secretSeal($plain, 'rmm'); } /** An address typed in, tidied - https:// in front when there is no scheme, no trailing slash. '' when it isn't a web address. */ diff --git a/functions/security.php b/functions/security.php index fc812cb8b..f276fbbbf 100644 --- a/functions/security.php +++ b/functions/security.php @@ -228,6 +228,47 @@ function generateUserSessionKey($site_encryption_master_key) { } } +/* + * A secret an integration keeps - an RMM's API key, an identity provider's client secret - sealed + * with this install's key (backupEncryptionKey(), in config.php), so the database alone doesn't + * give it away and a backup restored with the key reads it. AES-256-GCM, 'enc1:' then base64 of + * IV, tag and ciphertext; $purpose keeps each kind's key apart. '' when the install has no key + * and config.php can't be written to make one. + */ +function secretSeal(#[\SensitiveParameter] string $plain, string $purpose): string +{ + $key = secretSealKey($purpose); + if ($key === '' || $plain === '') { + return ''; + } + $iv = random_bytes(12); + $tag = ''; + $cipher = openssl_encrypt($plain, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, '', 16); + return $cipher === false ? '' : 'enc1:' . base64_encode($iv . $tag . $cipher); +} + +/** A secret as typed, from what secretSeal() kept - one saved before it was sealed is read as it is. '' when it can't be read: config.php's key was changed. */ +function secretOpen(string $stored, string $purpose): string +{ + if (!str_starts_with($stored, 'enc1:')) { + return $stored; + } + $raw = base64_decode(substr($stored, 5), true); + $key = secretSealKey($purpose); + if ($raw === false || strlen($raw) < 29 || $key === '') { + return ''; + } + $plain = openssl_decrypt(substr($raw, 28), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($raw, 0, 12), substr($raw, 12, 16)); + return $plain === false ? '' : $plain; +} + +/** The key secretSeal() uses for $purpose - from this install's key. */ +function secretSealKey(string $purpose): string +{ + $install = function_exists('backupEncryptionKey') ? backupEncryptionKey() : ''; + return $install === '' ? '' : hash('sha256', "itflow-$purpose-secrets|$install", true); +} + // Decrypts an encrypted password (website/asset credentials), returns it as a string function decryptCredentialEntry($credential_password_ciphertext) { diff --git a/functions/sign_in.php b/functions/sign_in.php index e46061d93..cbd4d4b15 100644 --- a/functions/sign_in.php +++ b/functions/sign_in.php @@ -78,6 +78,20 @@ function signInFailureReason($email) { ]; } +/* + * How many times the sign-in page turned away $email (raw) in the last + * SIGN_IN_WINDOW_MINUTES - its "Failed sign in as - ..." rows, whether + * or not the address has an account. + */ +function signInAddressFailures($email) { + global $mysqli; + $prefix = escapeSql('Failed sign in as ' . trim((string) $email) . ' - '); + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(log_id) FROM logs + WHERE log_type IN ('" . implode("', '", SIGN_IN_TYPES) . "') AND log_action = 'Failed' + AND log_created_at > NOW() - INTERVAL " . SIGN_IN_WINDOW_MINUTES . " MINUTE + AND LEFT(log_description, CHAR_LENGTH('$prefix')) = '$prefix'"))[0] ?? 0); +} + /* * A sign in event in the audit log, as $user_id - whose account it was, even * when nobody signed in - from this request's IP address and browser. diff --git a/join.php b/join.php index 84d51a9d7..85c32c771 100644 --- a/join.php +++ b/join.php @@ -4,7 +4,9 @@ * started > Your team): ?invite=&token=. The person checks their name and * chooses a password - nobody else ever knows it - and is made an agent with * the role, MFA and client access the invite set (userInviteAccept(), - * functions/user_invite.php). Then they sign in on the usual page. A link + * functions/user_invite.php). Then they sign in on the usual page - or, where + * their email domain's mail server checks passwords (IMAP) or a provider is + * required for it, that way, the password only opening their credentials. A link * that has run out, been used or cancelled says so, and what to do instead. * * The client portal's own invites open client/join.php. @@ -66,6 +68,15 @@ if ($invite && in_array($link['state'], ['pending', 'accepted'], true) && !empty $sign_in .= '?key=' . rawurlencode((string) $config_login_key_secret); } +// How they sign in - their email domain's mail server may check the password (IMAP), or a provider be required +// for it (functions/identity_provider.php). The password chosen here still opens their credentials either way +$password_use = $invite ? identityProviderPasswordUse($invite['invite_email'], 1, intval($invite['invite_role_id'] ?? 0)) : ['use' => 'password', 'name' => '']; +$sign_in_how = [ + 'provider' => 'Sign in with ' . $password_use['name'] . ' - its button on the sign-in page.', + 'mail' => 'Sign in with ' . ($invite['invite_email'] ?? 'your email address') . ' and your email password - the one for your mailbox.', + 'password' => 'Sign in with ' . ($invite['invite_email'] ?? 'your email address') . ' and your new password.', +][$password_use['use']]; + if ($invite && $link['state'] === 'pending' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['agent_join'])) { $in_name = (string) ($_POST['name'] ?? ''); $user_id = userInviteAccept($invite, $token, [ @@ -75,8 +86,9 @@ if ($invite && $link['state'] === 'pending' && $_SERVER['REQUEST_METHOD'] === 'P ], $error); if ($user_id) { $first = strtok(trim(preg_replace('/\s+/', ' ', strip_tags($in_name))), ' '); - $_SESSION['login_message'] = "Welcome, $first - your account is ready. Sign in with " . $invite['invite_email'] . ' and your new password.' - . (intval($invite['invite_force_mfa']) ? ' Have your authenticator app ready - you set up multi-factor authentication as you sign in.' : ''); + $_SESSION['login_message'] = "Welcome, $first - your account is ready. $sign_in_how" + . ($password_use['use'] !== 'password' ? ' The password you chose opens your credentials - you are asked for it the first time you open one.' : '') + . (intval($invite['invite_force_mfa']) && $password_use['use'] !== 'provider' ? ' Have your authenticator app ready - you set up multi-factor authentication as you sign in.' : ''); $_SESSION['login_message_type'] = 'success'; header("Location: $sign_in"); exit(); @@ -91,7 +103,7 @@ $ask = $by !== '' ? "Ask $by to send it again." : 'Ask your administrator to sen $notes = [ 'gone' => ["That link doesn't work", 'It may have been copied only in part - or a newer invite replaced it, so use the link in the latest one.'], 'expired' => ['That invite has run out', 'Invites work for ' . USER_INVITE_LINK_DAYS . " days. $ask"], - 'accepted' => ["You've joined already", 'Sign in with ' . ($invite['invite_email'] ?? 'your email address') . ' and the password you chose.'], + 'accepted' => ["You've joined already", $password_use['use'] === 'password' ? 'Sign in with ' . ($invite['invite_email'] ?? 'your email address') . ' and the password you chose.' : $sign_in_how], 'cancelled' => ['That invite was cancelled', $by !== '' ? "Ask $by about it." : 'Ask your administrator about it.'], ]; $state = $link['state']; @@ -130,7 +142,13 @@ $title = $state === 'pending' ? "Join $where" : $notes[$state][0];

to join , as . - Choose your password and you're ready to sign in. + + You sign in with - choose a password for opening your credentials. + + You sign in with your email password - choose a password for opening your credentials. + + Choose your password and you're ready to sign in. +

@@ -158,9 +176,13 @@ $title = $state === 'pending' ? "Join $where" : $notes[$state][0]; -

It also unlocks the credential vault for you, so keep it to yourself.

+ +

It also unlocks the credential vault for you, so keep it to yourself.

+ +

- this one unlocks the credential vault for you: you're asked for it the first time you open a credential. Keep it to yourself.

+ - +
Multi-factor authentication is required: have an authenticator app on your phone ready - you set it up as you sign in.
diff --git a/login.php b/login.php index 0862bbc39..3ec60a69f 100644 --- a/login.php +++ b/login.php @@ -108,7 +108,8 @@ $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(); -if ($config_login_key_required && !hash_equals((string) $config_login_key_secret, is_string($_GET['key'] ?? null) ? $_GET['key'] : '')) { +$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); })); @@ -172,8 +173,13 @@ if (($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($ // 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 account's domains that is required, so its password doesn't work here + // 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) @@ -342,16 +348,31 @@ if (($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($ } } + // 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) { - [$imap_ok] = identityProviderImapCheck($imap, $email_raw, $password); - if ($imap_ok && ($ut === 1 || ($r['user_auth_method'] ?? '') === 'local')) { + $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'])) { @@ -361,12 +382,6 @@ if (($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($ } elseif (!password_verify($password, $r['user_password'])) { continue; } - // A required provider on its domains turns its password off - an administrator keeps theirs - $required = isset($via_imap_types[$ut]) ? null : identityProviderRequiredFor($email_raw, $ut, intval($r['user_role_id'] ?? 0)); - if ($required) { - $required_provider = $required; - 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) { @@ -387,16 +402,36 @@ if (($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['login']) || isset($ } } + // 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"); - // The password was right, but this account signs in through its provider + // 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 ?? ''); - signInLogFailure($failed_why['type'], 'Failed', escapeSql('Failed sign in as ' . ($email_raw ?? '') . ' - it signs in with ' . $required_provider['identity_provider_name'] . ', not a password'), $failed_why['user_id'], $failed_why['client_id']); + $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_provider['identity_provider_name']) . " - your account doesn't sign in with a password here. + 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");