mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 09:09:01 +00:00
680 lines
32 KiB
PHP
680 lines
32 KiB
PHP
<?php
|
|
|
|
/*
|
|
* ITFlow - identity providers (database 4.2.5, identity_providers): agents and client contacts
|
|
* signing in with their Microsoft 365, Google Workspace or Nextcloud account, or with their mail
|
|
* password through an IMAP server (Admin > Identity Providers, admin/identity_providers.php).
|
|
*
|
|
* 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 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
|
|
* swaps it for a token, server to server with the app's secret and PKCE, and asks the provider
|
|
* 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 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.
|
|
*/
|
|
|
|
/** Whether the database has identity providers yet (4.2.5). */
|
|
function identityProvidersReady() {
|
|
global $mysqli;
|
|
static $ready = null;
|
|
if ($ready === null) {
|
|
if (defined('CURRENT_DATABASE_VERSION')) {
|
|
$version = CURRENT_DATABASE_VERSION;
|
|
} else {
|
|
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
|
|
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
|
|
}
|
|
$ready = version_compare($version, '4.2.5', '>=');
|
|
}
|
|
return $ready;
|
|
}
|
|
|
|
/** The kinds of identity provider, and what each needs. */
|
|
function identityProviderKinds() {
|
|
return [
|
|
'microsoft' => [
|
|
'name' => 'Microsoft 365',
|
|
'button' => 'Sign in with Microsoft',
|
|
'icon' => 'fab fa-microsoft',
|
|
'oauth' => true,
|
|
'domains_optional' => true,
|
|
'about' => 'Work accounts in Microsoft 365 - an app registered in Microsoft Entra',
|
|
'fields' => ['client_id', 'client_secret', 'tenant'],
|
|
],
|
|
'google' => [
|
|
'name' => 'Google Workspace',
|
|
'button' => 'Sign in with Google',
|
|
'icon' => 'fab fa-google',
|
|
'oauth' => true,
|
|
'domains_optional' => true,
|
|
'about' => 'Google Workspace accounts - an OAuth client in Google Cloud',
|
|
'fields' => ['client_id', 'client_secret'],
|
|
],
|
|
'nextcloud' => [
|
|
'name' => 'Nextcloud',
|
|
'button' => 'Sign in with Nextcloud',
|
|
'icon' => 'fas fa-cloud',
|
|
'oauth' => true,
|
|
'domains_optional' => false,
|
|
'about' => 'Nextcloud accounts - its OIDC Identity Provider app',
|
|
'fields' => ['url', 'client_id', 'client_secret'],
|
|
],
|
|
'imap' => [
|
|
'name' => 'IMAP',
|
|
'button' => '',
|
|
'icon' => 'fas fa-envelope',
|
|
'oauth' => false,
|
|
'domains_optional' => false,
|
|
'about' => 'A mail server - the password typed on the sign-in page is checked with it',
|
|
'fields' => ['url', 'port', 'security', 'username'],
|
|
],
|
|
];
|
|
}
|
|
|
|
/** The kind of an identity_providers row, or null when this ITFlow doesn't know it. */
|
|
function identityProviderKind(array $row) {
|
|
return identityProviderKinds()[(string) ($row['identity_provider_kind'] ?? '')] ?? null;
|
|
}
|
|
|
|
/** An identity provider's row, or null. */
|
|
function identityProviderRow($identity_provider_id) {
|
|
global $mysqli;
|
|
if (!identityProvidersReady()) {
|
|
return null;
|
|
}
|
|
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM identity_providers WHERE identity_provider_id = " . intval($identity_provider_id))) ?: null;
|
|
}
|
|
|
|
/** Every provider that is on, of a known kind - once a request. */
|
|
function identityProvidersOn() {
|
|
global $mysqli;
|
|
static $rows = null;
|
|
if ($rows === null) {
|
|
$rows = [];
|
|
if (identityProvidersReady()) {
|
|
$sql = mysqli_query($mysqli, "SELECT * FROM identity_providers WHERE identity_provider_enabled = 1 ORDER BY identity_provider_name ASC, identity_provider_id ASC");
|
|
while ($row = mysqli_fetch_assoc($sql)) {
|
|
if (identityProviderKind($row)) {
|
|
$rows[] = $row;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return $rows;
|
|
}
|
|
|
|
/** A list of email domains as they are kept - lowercase, one each, no @ - from what was typed. */
|
|
function identityProviderDomainList($text) {
|
|
$domains = [];
|
|
foreach (preg_split('/[\s,;]+/', strtolower((string) $text)) as $domain) {
|
|
$domain = trim($domain, " \t.@");
|
|
if ($domain !== '') {
|
|
$domains[$domain] = true;
|
|
}
|
|
}
|
|
return array_keys($domains);
|
|
}
|
|
|
|
/** Whether a domain is one - letters, digits and hyphens, in parts. */
|
|
function identityProviderDomainValid($domain) {
|
|
return (bool) preg_match('/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/', $domain);
|
|
}
|
|
|
|
/** The domains a provider signs in - [] for any, where its kind allows that. */
|
|
function identityProviderDomains(array $row) {
|
|
return identityProviderDomainList($row['identity_provider_domains'] ?? '');
|
|
}
|
|
|
|
/** The part of an email address after the @, lowercase. */
|
|
function identityProviderEmailDomain($email) {
|
|
$at = strrpos((string) $email, '@');
|
|
return $at === false ? '' : strtolower(substr((string) $email, $at + 1));
|
|
}
|
|
|
|
/** Whether a provider signs in this email address - its domain is on the list, or the list is empty where that means any. */
|
|
function identityProviderCovers(array $row, $email) {
|
|
$kind = identityProviderKind($row);
|
|
if (!$kind) {
|
|
return false;
|
|
}
|
|
$domains = identityProviderDomains($row);
|
|
if (!$domains) {
|
|
return !empty($kind['domains_optional']);
|
|
}
|
|
return in_array(identityProviderEmailDomain($email), $domains, true);
|
|
}
|
|
|
|
/** Whether a provider is for this kind of account - 1 an agent, 2 a client contact (only while the portal is on). */
|
|
function identityProviderFor(array $row, $user_type) {
|
|
global $config_client_portal_enable;
|
|
if (intval($user_type) === 1) {
|
|
return intval($row['identity_provider_agents']) === 1;
|
|
}
|
|
return intval($row['identity_provider_contacts']) === 1 && intval($config_client_portal_enable ?? 0) === 1;
|
|
}
|
|
|
|
/** The IMAP provider that checks this account's password, or null. */
|
|
function identityProviderImapFor($email, $user_type) {
|
|
foreach (identityProvidersOn() as $row) {
|
|
if ($row['identity_provider_kind'] === 'imap' && identityProviderFor($row, $user_type) && identityProviderCovers($row, $email)) {
|
|
return $row;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* The provider this account has to sign in with, when one on its domains is required - null when
|
|
* its password still works. An agent whose role is an administrator's keeps their password, to
|
|
* get back in when the provider is down or set up wrong.
|
|
*/
|
|
function identityProviderRequiredFor($email, $user_type, $role_id = 0) {
|
|
foreach (identityProvidersOn() as $row) {
|
|
$kind = identityProviderKind($row);
|
|
if (!$kind['oauth'] || intval($row['identity_provider_required']) !== 1 || !identityProviderDomains($row)
|
|
|| !identityProviderFor($row, $user_type) || !identityProviderCovers($row, $email)) {
|
|
continue;
|
|
}
|
|
if (intval($user_type) === 1 && identityProviderAdminRole($role_id)) {
|
|
continue;
|
|
}
|
|
return $row;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Whether an agent's role is an administrator's - who keeps their ITFlow password, to get back in when a provider is down. */
|
|
function identityProviderAdminRole($role_id) {
|
|
global $mysqli;
|
|
if (intval($role_id) <= 0) {
|
|
return false;
|
|
}
|
|
$admin = mysqli_fetch_row(mysqli_query($mysqli, "SELECT role_is_admin FROM user_roles WHERE role_id = " . intval($role_id)));
|
|
return intval($admin[0] ?? 0) === 1;
|
|
}
|
|
|
|
/** 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) {
|
|
return identityProviderKind($row)['oauth'] && (identityProviderFor($row, 1) || identityProviderFor($row, 2));
|
|
}));
|
|
}
|
|
|
|
/** Where a provider sends people back to - the address registered with it. */
|
|
function identityProviderRedirectUri(array $row) {
|
|
global $config_base_url;
|
|
$path = (string) ($row['identity_provider_redirect_path'] ?? '') ?: '/login_provider.php';
|
|
return 'https://' . preg_replace('#^https?://#', '', rtrim((string) $config_base_url, '/')) . $path;
|
|
}
|
|
|
|
/**
|
|
* The names of the providers on for client contacts, Microsoft 365, Google or Nextcloud - for what
|
|
* the portal tells them. With an email address, only the ones that sign that address in.
|
|
*/
|
|
function identityProviderNamesForContacts($email = null) {
|
|
$names = [];
|
|
foreach (identityProvidersOn() as $row) {
|
|
if (identityProviderKind($row)['oauth'] && identityProviderFor($row, 2) && ($email === null || identityProviderCovers($row, $email))) {
|
|
$names[] = (string) $row['identity_provider_name'];
|
|
}
|
|
}
|
|
return array_values(array_unique($names));
|
|
}
|
|
|
|
/** What contacts sign in with besides a password, for what they and agents are told - "Microsoft 365 or Google Workspace", or "an identity provider". */
|
|
function identityProviderContactsWording($email = null) {
|
|
$names = identityProviderNamesForContacts($email);
|
|
return $names ? implode(' or ', $names) : 'an identity provider';
|
|
}
|
|
|
|
/** A Nextcloud's address, as typed - https, no trailing slash. */
|
|
function identityProviderNextcloudUrl(array $row) {
|
|
return rtrim(trim((string) ($row['identity_provider_url'] ?? '')), '/');
|
|
}
|
|
|
|
/** An HTTP request to a provider - [status, decoded JSON or null, raw body]. Never sent anywhere but its own endpoints. */
|
|
function identityProviderHttp($method, $url, $fields = null, $headers = []) {
|
|
$ch = curl_init();
|
|
curl_setopt($ch, CURLOPT_URL, $url);
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
|
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
|
|
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
|
|
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
|
|
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
|
|
if ($method === 'POST') {
|
|
curl_setopt($ch, CURLOPT_POST, true);
|
|
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query((array) $fields));
|
|
}
|
|
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge(['Accept: application/json'], $headers));
|
|
$body = curl_exec($ch);
|
|
$status = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
|
|
curl_close($ch);
|
|
$json = is_string($body) ? json_decode($body, true) : null;
|
|
return [$status, is_array($json) ? $json : null, is_string($body) ? $body : ''];
|
|
}
|
|
|
|
/**
|
|
* Where a provider's sign-in happens - authorize, token and userinfo endpoints, and how the token
|
|
* endpoint takes the secret. Microsoft and Google are fixed; a Nextcloud says in its OpenID
|
|
* configuration. [endpoints, error].
|
|
*/
|
|
function identityProviderEndpoints(array $row) {
|
|
$kind = (string) $row['identity_provider_kind'];
|
|
if ($kind === 'microsoft') {
|
|
$tenant = trim((string) ($row['identity_provider_tenant'] ?? '')) ?: 'organizations';
|
|
$tenant = preg_match('/^[a-z0-9.-]{1,100}$/i', $tenant) ? $tenant : 'organizations';
|
|
return [[
|
|
'authorize' => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/authorize",
|
|
'token' => "https://login.microsoftonline.com/$tenant/oauth2/v2.0/token",
|
|
'userinfo' => 'https://graph.microsoft.com/v1.0/me',
|
|
'scope' => 'openid profile email User.Read',
|
|
'auth' => 'post',
|
|
], ''];
|
|
}
|
|
if ($kind === 'google') {
|
|
return [[
|
|
'authorize' => 'https://accounts.google.com/o/oauth2/v2/auth',
|
|
'token' => 'https://oauth2.googleapis.com/token',
|
|
'userinfo' => 'https://openidconnect.googleapis.com/v1/userinfo',
|
|
'scope' => 'openid email profile',
|
|
'auth' => 'post',
|
|
], ''];
|
|
}
|
|
if ($kind === 'nextcloud') {
|
|
$base = identityProviderNextcloudUrl($row);
|
|
if (!preg_match('#^https://[^/\s]+#i', $base)) {
|
|
return [null, 'its address is not an https:// one'];
|
|
}
|
|
$config = null;
|
|
foreach (["$base/index.php/.well-known/openid-configuration", "$base/.well-known/openid-configuration"] as $url) {
|
|
[$status, $json] = identityProviderHttp('GET', $url);
|
|
if ($status === 200 && $json && !empty($json['authorization_endpoint']) && !empty($json['token_endpoint']) && !empty($json['userinfo_endpoint'])) {
|
|
$config = $json;
|
|
break;
|
|
}
|
|
}
|
|
if (!$config) {
|
|
return [null, "it didn't give its OpenID configuration - is its OIDC Identity Provider app installed?"];
|
|
}
|
|
foreach (['authorization_endpoint', 'token_endpoint', 'userinfo_endpoint'] as $key) {
|
|
if (stripos((string) $config[$key], 'https://') !== 0) {
|
|
return [null, 'its OpenID configuration gives an address that is not https://'];
|
|
}
|
|
}
|
|
$methods = (array) ($config['token_endpoint_auth_methods_supported'] ?? ['client_secret_post']);
|
|
return [[
|
|
'authorize' => (string) $config['authorization_endpoint'],
|
|
'token' => (string) $config['token_endpoint'],
|
|
'userinfo' => (string) $config['userinfo_endpoint'],
|
|
'scope' => 'openid profile email',
|
|
'auth' => in_array('client_secret_post', $methods, true) ? 'post' : 'basic',
|
|
], ''];
|
|
}
|
|
return [null, 'it is not a kind that signs in with a button'];
|
|
}
|
|
|
|
/** PKCE - a random verifier, and its S256 challenge. */
|
|
function identityProviderPkce() {
|
|
$verifier = rtrim(strtr(base64_encode(random_bytes(48)), '+/', '-_'), '=');
|
|
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
|
return [$verifier, $challenge];
|
|
}
|
|
|
|
/** The address that starts signing in with a provider. */
|
|
function identityProviderAuthorizeUrl(array $row, array $endpoints, $state, $challenge) {
|
|
$params = [
|
|
'client_id' => (string) $row['identity_provider_client_id'],
|
|
'redirect_uri' => identityProviderRedirectUri($row),
|
|
'response_type' => 'code',
|
|
// Back as a top-level GET - the session cookie isn't sent on a cross-site POST
|
|
'response_mode' => 'query',
|
|
'scope' => $endpoints['scope'],
|
|
'state' => $state,
|
|
'code_challenge' => $challenge,
|
|
'code_challenge_method' => 'S256',
|
|
'prompt' => 'select_account',
|
|
];
|
|
$domains = identityProviderDomains($row);
|
|
if ($row['identity_provider_kind'] === 'google' && count($domains) === 1) {
|
|
$params['hd'] = $domains[0]; // straight to their Workspace's accounts
|
|
}
|
|
if ($row['identity_provider_kind'] === 'nextcloud') {
|
|
unset($params['prompt'], $params['response_mode']);
|
|
}
|
|
return $endpoints['authorize'] . (str_contains($endpoints['authorize'], '?') ? '&' : '?') . http_build_query($params);
|
|
}
|
|
|
|
/**
|
|
* Who signed in, from the code the provider sent back - ['email' => ..., 'name' => ...], or
|
|
* ['error' => why, for the log]. The code is swapped for a token server to server, with the app's
|
|
* secret and the PKCE verifier, then the provider is asked who it is for.
|
|
*/
|
|
function identityProviderIdentity(array $row, array $endpoints, $code, $verifier) {
|
|
$fields = [
|
|
'grant_type' => 'authorization_code',
|
|
'code' => (string) $code,
|
|
'redirect_uri' => identityProviderRedirectUri($row),
|
|
'client_id' => (string) $row['identity_provider_client_id'],
|
|
'code_verifier' => (string) $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']));
|
|
} else {
|
|
$fields['client_secret'] = (string) $row['identity_provider_client_secret'];
|
|
}
|
|
[$status, $token] = identityProviderHttp('POST', $endpoints['token'], $fields, $headers);
|
|
if (empty($token['access_token']) || !is_string($token['access_token'])) {
|
|
$why = is_array($token) && !empty($token['error']) ? (string) $token['error'] . (!empty($token['error_description']) ? ' - ' . mb_substr((string) $token['error_description'], 0, 200) : '') : "HTTP $status";
|
|
return ['error' => "it gave no token for the code ($why)"];
|
|
}
|
|
|
|
[$status, $who] = identityProviderHttp('GET', $endpoints['userinfo'], null, ['Authorization: Bearer ' . $token['access_token']]);
|
|
if (!$who || $status !== 200) {
|
|
return ['error' => "it didn't say who signed in (HTTP $status)"];
|
|
}
|
|
|
|
$kind = (string) $row['identity_provider_kind'];
|
|
if ($kind === 'microsoft') {
|
|
// The sign-in name, on a domain the directory has proved it owns - not mail, which anyone in a directory can be given
|
|
$email = (string) ($who['userPrincipalName'] ?? '');
|
|
$name = (string) ($who['displayName'] ?? '');
|
|
if (str_contains($email, '#EXT#')) {
|
|
return ['error' => 'it is a guest account in another organization'];
|
|
}
|
|
} 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"];
|
|
}
|
|
// 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"];
|
|
}
|
|
}
|
|
$email = strtolower(trim($email));
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
return ['error' => 'it gave no email address'];
|
|
}
|
|
return ['email' => $email, 'name' => $name];
|
|
}
|
|
|
|
/**
|
|
* The accounts a provider can sign in for this address - ['agent' => user id or 0, 'client' =>
|
|
* user id or 0]: an agent that is active, and a contact with portal access at a current client.
|
|
*/
|
|
function identityProviderAccounts(array $row, $email) {
|
|
global $mysqli;
|
|
$accounts = ['agent' => 0, 'client' => 0];
|
|
if (!identityProviderCovers($row, $email)) {
|
|
return $accounts;
|
|
}
|
|
$email_sql = escapeSql($email);
|
|
if (identityProviderFor($row, 1)) {
|
|
$agent = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$email_sql' AND user_type = 1 AND user_status = 1
|
|
AND user_archived_at IS NULL" . serviceAccountsOutSql('users.user_service_account') . " ORDER BY user_id LIMIT 1"));
|
|
$accounts['agent'] = intval($agent[0] ?? 0);
|
|
}
|
|
if (identityProviderFor($row, 2)) {
|
|
$contact = mysqli_fetch_row(mysqli_query($mysqli, "SELECT users.user_id FROM users
|
|
JOIN contacts ON contact_user_id = users.user_id AND contact_archived_at IS NULL
|
|
JOIN clients ON client_id = contact_client_id AND client_archived_at IS NULL
|
|
WHERE user_email = '$email_sql' AND user_type = 2 AND user_status = 1 AND user_archived_at IS NULL AND user_auth_method IN ('local', 'azure')
|
|
ORDER BY users.user_id LIMIT 1"));
|
|
$accounts['client'] = intval($contact[0] ?? 0);
|
|
}
|
|
return $accounts;
|
|
}
|
|
|
|
/** 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;
|
|
}
|
|
|
|
/**
|
|
* Whether the mail server takes this password for the address - [ok, why not, for the log]. A
|
|
* server that can't be reached is said apart from a wrong password, and goes in the app log.
|
|
*/
|
|
function identityProviderImapCheck(array $row, $email, #[\SensitiveParameter] $password) {
|
|
static $checked = [];
|
|
if ((string) $password === '' || strpos((string) $email, '@') === false) {
|
|
return [false, 'no password was typed'];
|
|
}
|
|
$key = intval($row['identity_provider_id']) . '|' . strtolower((string) $email) . '|' . hash('sha256', (string) $password);
|
|
if (isset($checked[$key])) {
|
|
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,
|
|
'username' => identityProviderImapUsername($row, $email),
|
|
'password' => (string) $password,
|
|
]);
|
|
try {
|
|
$mailbox->connect();
|
|
try {
|
|
$mailbox->disconnect();
|
|
} catch (\Throwable $e) {
|
|
// Signed in is all that was asked
|
|
}
|
|
return $checked[$key] = [true, ''];
|
|
} catch (\DirectoryTree\ImapEngine\Exceptions\ImapCommandException $e) {
|
|
return $checked[$key] = [false, 'the mail server said the password is wrong'];
|
|
} catch (\Throwable $e) {
|
|
logApp('Identity Provider', 'warning', 'Could not reach the mail server for ' . $row['identity_provider_name'] . ' (' . $row['identity_provider_url'] . '): ' . mb_substr($e->getMessage(), 0, 300));
|
|
return $checked[$key] = [false, "the mail server couldn't be reached"];
|
|
}
|
|
}
|
|
|
|
/** A provider was just used to sign in - for its list. */
|
|
function identityProviderUsed($identity_provider_id) {
|
|
global $mysqli;
|
|
if (identityProvidersReady()) {
|
|
mysqli_query($mysqli, "UPDATE identity_providers SET identity_provider_used_at = NOW(), identity_provider_updated_at = identity_provider_updated_at WHERE identity_provider_id = " . intval($identity_provider_id));
|
|
}
|
|
}
|
|
|
|
/*
|
|
* ---------- Admin > Identity Providers ----------
|
|
*
|
|
* Add and Edit are one window (admin/modals/identity_provider/identity_provider_edit.php), saved by
|
|
* save_identity_provider (admin/post/identity_provider.php). Which kind it is stays once added.
|
|
* The secret is never put back into the page - left empty, it stays as saved.
|
|
*/
|
|
|
|
/** What is typed in an identity provider's window, checked - [the row to save, errors by field]. */
|
|
function identityProviderCheck(array $in, ?array $before): array
|
|
{
|
|
$errors = [];
|
|
$kind_key = $before ? (string) $before['identity_provider_kind'] : (string) ($in['kind'] ?? '');
|
|
$kind = identityProviderKinds()[$kind_key] ?? null;
|
|
if (!$kind) {
|
|
return [[], ['kind' => 'Pick the kind of identity provider.']];
|
|
}
|
|
$text = function ($key, $max = 255) use ($in) {
|
|
return trim((string) ($in[$key] ?? ''));
|
|
};
|
|
$fields = $kind['fields'];
|
|
|
|
$name = $text('name');
|
|
if ($name === '') {
|
|
$errors['name'] = 'Give it a name - its button on the sign-in page says Sign in with it.';
|
|
} elseif (mb_strlen($name) > 100) {
|
|
$errors['name'] = 'Its name is 100 characters at most.';
|
|
}
|
|
|
|
$agents = intval($in['agents'] ?? 0) === 1 ? 1 : 0;
|
|
$contacts = intval($in['contacts'] ?? 0) === 1 ? 1 : 0;
|
|
if (!$agents && !$contacts) {
|
|
$errors['agents'] = 'Pick who it signs in - agents, client contacts or both.';
|
|
}
|
|
|
|
$domains = identityProviderDomainList($text('domains'));
|
|
$bad = array_values(array_filter($domains, function ($domain) {
|
|
return !identityProviderDomainValid($domain);
|
|
}));
|
|
if ($bad) {
|
|
$errors['domains'] = $bad[0] . ' isn\'t an email domain - type them as example.com, with a comma between.';
|
|
} elseif (!$domains && !$kind['domains_optional']) {
|
|
$errors['domains'] = 'List the email domains it signs in - ' . ($kind_key === 'imap' ? 'the ones whose mailboxes are all on this server.' : 'the ones whose people are all on your Nextcloud.');
|
|
} elseif (strlen(implode(', ', $domains)) > 1000) {
|
|
$errors['domains'] = 'That many email domains don\'t fit - split them over two providers.';
|
|
}
|
|
|
|
$required = $kind['oauth'] && intval($in['required'] ?? 0) === 1 ? 1 : 0;
|
|
if ($required && !$domains) {
|
|
$errors['required'] = 'List the email domains it is required for.';
|
|
}
|
|
|
|
$client_id = $secret = $tenant = $url = '';
|
|
$port = 0;
|
|
$security = $username = '';
|
|
if (in_array('client_id', $fields, true)) {
|
|
$client_id = $text('client_id');
|
|
if ($client_id === '') {
|
|
$errors['client_id'] = $kind_key === 'microsoft' ? 'The Application (client) ID, from the app\'s Overview.' : 'Its client ID.';
|
|
} elseif ($kind_key === 'microsoft' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $client_id)) {
|
|
$errors['client_id'] = 'The Application (client) ID - 32 letters and numbers in five groups, as e721e3b6-01d6-50e8-7f22-c84d951a52e7.';
|
|
} elseif ($kind_key === 'google' && !preg_match('/^[A-Za-z0-9-]+\.apps\.googleusercontent\.com$/', $client_id)) {
|
|
$errors['client_id'] = 'The Client ID of the OAuth client - it ends in .apps.googleusercontent.com.';
|
|
} 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) {
|
|
$errors['client_secret'] = 'That is too long for a client secret - copy it again.';
|
|
}
|
|
}
|
|
if (in_array('tenant', $fields, true)) {
|
|
$tenant = strtolower($text('tenant'));
|
|
if (in_array($tenant, ['common', 'consumers'], true)) {
|
|
$errors['tenant'] = 'Personal Microsoft accounts can\'t sign in here - leave it empty for any organization\'s work accounts.';
|
|
} elseif ($tenant === 'organizations') {
|
|
$tenant = '';
|
|
} elseif ($tenant !== '' && !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/', $tenant) && !identityProviderDomainValid($tenant)) {
|
|
$errors['tenant'] = 'The Directory (tenant) ID, or one of its domains as contoso.onmicrosoft.com - or leave it empty.';
|
|
}
|
|
}
|
|
if ($kind_key === 'nextcloud') {
|
|
$url = rtrim($text('url'), '/');
|
|
$parts = parse_url($url);
|
|
if ($url === '' || !$parts || strtolower($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) || isset($parts['query']) || isset($parts['fragment']) || isset($parts['user']) || strlen($url) > 500) {
|
|
$errors['url'] = 'Your Nextcloud\'s address, starting with https:// - as https://cloud.example.com.';
|
|
}
|
|
}
|
|
if ($kind_key === 'imap') {
|
|
$url = strtolower($text('url'));
|
|
if ($url === '' || (!identityProviderDomainValid($url) && !filter_var($url, FILTER_VALIDATE_IP))) {
|
|
$errors['url'] = 'The mail server\'s name, as mail.example.com.';
|
|
}
|
|
$security = (string) ($in['security'] ?? 'ssl');
|
|
if (!in_array($security, ['ssl', 'starttls', 'none'], true)) {
|
|
$security = 'ssl';
|
|
}
|
|
$port_text = $text('port');
|
|
$port = $port_text === '' ? ($security === 'ssl' ? 993 : 143) : intval($port_text);
|
|
if ($port < 1 || $port > 65535 || ($port_text !== '' && !ctype_digit($port_text))) {
|
|
$errors['port'] = 'A port is a number from 1 to 65535 - 993 for SSL/TLS, 143 for STARTTLS.';
|
|
}
|
|
$username = ($in['username'] ?? 'email') === 'local' ? 'local' : 'email';
|
|
}
|
|
|
|
$after = [
|
|
'identity_provider_kind' => $kind_key,
|
|
'identity_provider_name' => mb_substr($name, 0, 100),
|
|
'identity_provider_enabled' => intval($in['enabled'] ?? 0) === 1 ? 1 : 0,
|
|
'identity_provider_agents' => $agents,
|
|
'identity_provider_contacts' => $contacts,
|
|
'identity_provider_domains' => implode(', ', $domains),
|
|
'identity_provider_required' => $required,
|
|
'identity_provider_client_id' => $client_id,
|
|
'identity_provider_client_secret' => $secret,
|
|
'identity_provider_tenant' => $tenant,
|
|
'identity_provider_url' => $url,
|
|
'identity_provider_port' => $port,
|
|
'identity_provider_security' => $security,
|
|
'identity_provider_username' => $username,
|
|
];
|
|
|
|
// A Nextcloud has to say where its OpenID Connect is - asked when its address is new
|
|
if (!$errors && $kind_key === 'nextcloud' && (!$before || identityProviderNextcloudUrl($before) !== $url)) {
|
|
[, $why] = identityProviderEndpoints($after);
|
|
if ($why) {
|
|
$errors['url'] = 'ITFlow asked your Nextcloud, but ' . $why;
|
|
}
|
|
}
|
|
|
|
return [$after, $errors];
|
|
}
|
|
|
|
/** 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
|
|
{
|
|
global $mysqli;
|
|
$set = implode(', ', array_map(function ($column, $value) {
|
|
return "`$column` = '" . escapeSql((string) $value) . "'";
|
|
}, array_keys($after), $after));
|
|
if ($identity_provider_id) {
|
|
mysqli_query($mysqli, "UPDATE identity_providers SET $set WHERE identity_provider_id = $identity_provider_id");
|
|
return $identity_provider_id;
|
|
}
|
|
mysqli_query($mysqli, "INSERT INTO identity_providers SET $set");
|
|
return intval(mysqli_insert_id($mysqli));
|
|
}
|
|
|
|
/** What changed on an identity provider, for the audit log - its secret is never written down. */
|
|
function identityProviderChangeLines(array $before, array $after): array
|
|
{
|
|
$labels = [
|
|
'identity_provider_name' => 'name', 'identity_provider_enabled' => 'on', 'identity_provider_agents' => 'agents',
|
|
'identity_provider_contacts' => 'client contacts', 'identity_provider_domains' => 'email domains', 'identity_provider_required' => 'required',
|
|
'identity_provider_client_id' => 'client ID', 'identity_provider_client_secret' => 'secret', 'identity_provider_tenant' => 'tenant',
|
|
'identity_provider_url' => 'address', 'identity_provider_port' => 'port', 'identity_provider_security' => 'security', 'identity_provider_username' => 'username',
|
|
];
|
|
$switches = [
|
|
'identity_provider_enabled' => ['turned it on', 'turned it off'],
|
|
'identity_provider_agents' => ['signs in agents', 'no longer signs in agents'],
|
|
'identity_provider_contacts' => ['signs in client contacts', 'no longer signs in client contacts'],
|
|
'identity_provider_required' => ['made it required', 'made it not required'],
|
|
];
|
|
$lines = [];
|
|
foreach ($labels as $column => $label) {
|
|
$old = (string) ($before[$column] ?? '');
|
|
$new = (string) ($after[$column] ?? '');
|
|
if ($old === $new) {
|
|
continue;
|
|
}
|
|
if (isset($switches[$column])) {
|
|
$lines[] = $switches[$column][$new === '1' ? 0 : 1];
|
|
} elseif ($column === 'identity_provider_client_secret') {
|
|
$lines[] = 'a new secret';
|
|
} else {
|
|
$lines[] = "$label: " . ($old === '' ? '(none)' : $old) . ' to ' . ($new === '' ? '(none)' : $new);
|
|
}
|
|
}
|
|
return $lines;
|
|
}
|