diff --git a/CHANGELOG.md b/CHANGELOG.md index 33a3328ac..e3b198854 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,13 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.3 -Update from Maintenance > Update as usual - this release has nine database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, and 4.3.0 lets contacts unsubscribe from bulk email. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. +Update from Maintenance > Update as usual - this release has ten database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, and 4.3.1 encrypts the mail passwords and tokens. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. + +### Security + +- The mail passwords, the OAuth client secret and the tokens ITFlow signs in to Microsoft 365 and Google with are encrypted in the database, where they were kept as typed - anyone with a copy of the database, or a backup, could sign in to your mailboxes. They're encrypted with a key made from config.php's backup key, so keep that key as Maintenance > Backup says: an install restored without it needs the passwords entered again, and Admin > Settings > Mail says so. Without a backup key - config.php not writable - they stay as typed, and Admin > Settings > Mail says that too. +- Pictures from other sites in a client's email - a logo, or a tracking pixel that tells the sender when it was read and from where - are hidden on a ticket until you click Show pictures, on the ticket, its quick look and its work order. Pictures kept with the ticket show as always. +- The sign-in page no longer loads the mail server's password. ### New Features & Updates @@ -153,6 +159,7 @@ Update from Maintenance > Update as usual - this release has nine database chang - Mail review stage 4: a failed email is still being tried while it is under MAIL_QUEUE_TRIES and its last try is within MAIL_QUEUE_GIVE_UP_HOURS (24) - mailQueueRetryingSql(), mailQueueFailedSql() and mailQueueRetrying(), for the job, the tabs, an email's state, Cancel and the summary - so one given up on before the tries went from 4 to 8 stays Failed rather than being sent again, and Failed gives its own count of tries. mailQueueRefusedForGood() decides which refused recipients are for good: the enhanced codes 5.1.1, 5.1.2, 5.1.3, 5.1.6 and 5.1.10, or 550, 551 or 553 naming an unknown recipient from a server that gives none (MailQueueSmtp keeps code_ex). Any other refusal is tried again and counts toward the two-in-a-row stop. mailQueueNotifyAdmins() counts dismissed notices toward its hour. The job orders by email_bulk, then email_sensitive DESC. - Mail review stage 5: cron/ticket_email_parser.php - an email with no From address is from '' rather than itflow-guest@example.com: addReply() takes it as a stranger's ($no_sender) and addTicket() makes no CC and sends no answer. contactBounceClearEmail() runs after ticketMailSenderCheck(), and only when it didn't fail. ticketMailReplyTo() (functions/ticket_mail_auto.php) reads Reply-To: one at From's domain is taken as the sender ($via, shown as "sent by"); else, when ticketMailSystemSender() says From is a no-reply or website address (TICKET_MAIL_SYSTEM_SENDERS) or there is none, it is $answer - steps 4 to 6 raise the ticket with contact_id 0 for it at the From contact's or domain's client, or none. addTicket() makes the sender a CC whenever there is no contact (was: no client), answers anyone not a contact through ticketMailCreated()'s new $stranger (no Subject row and no button - its last parameter was the subject), and skips ticketMailColleaguesNew() for a forged ticket or one with no contact. ticketMailSenderContact() (functions/ticket_mail_thread.php) picks the contact for steps 3 and 4 by the From domain's client, then the latest ticket, then contact_id, and ticketMailSenderContactNote() notes the others; Try an Email uses it. An agent's email whose To or Cc has the ticket's contact, a CC or another of the client's contacts (ticketMailClientAddresses()) is a Public reply - addReplyAgentToClient() fills ticket_reply_emailed_to, calls setTicketFirstResponse(), assigns it through ticketChangeAssignee() under ticketReplyAssigns() or moves New to Open, and fires reply_reply_agent_public. ticketNotifyOwner() (functions/ticket.php) puts a bell notice with the assigned agent or the admins (appNotifyUsers(), functions/logging.php) - for bounces and closed-ticket replies, where appNotify() told every agent - and ticketMailAssigneeReplied() goes to ticketMailUnassignedReplied() on a ticket nobody has: the new-ticket address, else that notice. That covers portal and text replies too. - Mail review stage 6: database 4.3.0 adds contacts.contact_unsubscribed_at and settings.config_mail_unsubscribe_secret. functions/contact_unsubscribe.php signs each contact's link with an HMAC of the contact id and address (contactUnsubscribeToken(), the key made on first use), and contactUnsubscribeSet() takes every contact with the address out or back in; contactUnsubscribedAddresses() is checked at send time, so a contact added since at another client is out too. guest/unsubscribe.php asks on GET, acts on its form's POST, and takes RFC 8058's List-Unsubscribe=One-Click POST with no page. emailBulkRecipients() (functions/email.php) builds the recipients from contact rows - the bounced, the unsubscribed, no address and the same address left out and counted - each with an unsubscribe link (emailHtml()'s new unsubscribe field) and its own List-Unsubscribe and List-Unsubscribe-Post headers (emailQueue() recipients' headers, let through by MAIL_QUEUE_HEADERS); emailBulkPost() now takes contact rows and converts Send at with timezoneFromView(). sendQueueEmail() sets the envelope sender per email - setFrom(..., false) with Sender reset, as PHPMailer's setFrom() kept the first email's From as Sender for the whole kept-alive connection - and for email_bulk passes mailQueueReturnPath(), the read mailbox when ticket parsing is on, the provider isn't Graph sending, the SMTP username is empty or that mailbox, and the domains align; a MAIL FROM refusal sends it again from the From address and sets mailQueueReturnPathRefused() for the run. mailQueueBouncesTo() tells the Email window. +- Mail review stage 7a: database 4.3.1 widens config_smtp_password, config_imap_password and config_mail_oauth_client_secret to varchar(500) and encrypts what is saved. functions/mail_secret.php seals MAIL_SECRET_COLUMNS (the two passwords, the OAuth secret, refresh and access tokens, and config_mail_graph_token) with secretSeal($plain, 'mail') as RMM and identity provider secrets are - but keeps a value as typed when there is no key, as mail would otherwise stop. mailSecretOpen() reads an unsealed value as it is, so nothing breaks before it is sealed: load_global_settings.php, cron/mail_queue.php, cron/nightly_tasks.php and mailGraphToken() open them; settingsWrite() seals secret-kind mail columns; every token write (the parser's two refreshes, persistMailOauthTokens(), the Microsoft callback, the Test OAuth refresh, mailGraphToken()) goes through mailSecretSql(). mailSecretsSealAll() runs in the update and nightly; mailSecretProblem() is the Admin > Settings > Mail warning. Remote pictures: ticketHtmlForAgents($purifier, $html) purifies and then ticketRemoteImagesHold() moves an http(s) or // img src to data-remote-src (a blank GIF and .itflow-remote-image in its place) and a style with a remote url() to data-remote-style - in agent/ticket.php, the quick look and ticketWorkOrderHtml(); ticketRemoteImagesNote() and js/app.js show the note and put them back. login.php drops the SMTP host, port, encryption, username and password it loaded but never used. ## [26.12.2] diff --git a/admin/database_updates/4.3.1.php b/admin/database_updates/4.3.1.php new file mode 100644 index 000000000..4ec2c24f2 --- /dev/null +++ b/admin/database_updates/4.3.1.php @@ -0,0 +1,26 @@ + + + +
+ +
diff --git a/agent/modals/ticket/ticket.php b/agent/modals/ticket/ticket.php index f30bd3490..3dcac9fca 100644 --- a/agent/modals/ticket/ticket.php +++ b/agent/modals/ticket/ticket.php @@ -222,8 +222,10 @@ ob_start();
+ +
What it is about
-
purify($ticket['ticket_details']) ?: 'No details.' ?>
+
No details.' ?>
@@ -240,7 +242,7 @@ ob_start(); -
purify($reply['ticket_reply']) ?>
+
diff --git a/agent/ticket.php b/agent/ticket.php index fde10fd47..9a0484b75 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -70,7 +70,8 @@ if (isset($_GET['ticket_id'])) { $ticket_category = intval($ticket['ticket_category']); $ticket_category_display = escapeHtml($ticket['category_name']); $ticket_subject = escapeHtml($ticket['ticket_subject']); - $ticket_details = $purifier->purify($ticket['ticket_details']); + // Pictures from other sites held back until Show pictures (functions/ticket_pictures.php) + $ticket_details = ticketHtmlForAgents($purifier, $ticket['ticket_details']); $ticket_priority = escapeHtml($ticket['ticket_priority']); $ticket_billable = intval($ticket['ticket_billable']); $ticket_scheduled_for = escapeHtml($ticket['ticket_schedule']); @@ -774,6 +775,9 @@ if (isset($_GET['ticket_id'])) { + + +
@@ -1079,7 +1083,7 @@ if (isset($_GET['ticket_id'])) { foreach ($ticket_reply_rows as $reply_row) { $ticket_reply_id = intval($reply_row['ticket_reply_id']); - $ticket_reply = $purifier->purify($reply_row['ticket_reply']); + $ticket_reply = ticketHtmlForAgents($purifier, $reply_row['ticket_reply']); $ticket_reply_type = escapeHtml($reply_row['ticket_reply_type']); // A note that mentions you says so, and your name in it stands out $reply_mentions_me = in_array(intval($session_user_id), $reply_mentions[$ticket_reply_id] ?? [], true); diff --git a/cron/mail_queue.php b/cron/mail_queue.php index 77d122775..53ce0d4de 100644 --- a/cron/mail_queue.php +++ b/cron/mail_queue.php @@ -67,17 +67,18 @@ $config_enable_cron = intval($row['config_enable_cron']); // SMTP baseline $config_smtp_host = $row['config_smtp_host']; $config_smtp_username = $row['config_smtp_username']; -$config_smtp_password = $row['config_smtp_password']; +// Encrypted in the database (functions/mail_secret.php) +$config_smtp_password = mailSecretOpen($row['config_smtp_password']); $config_smtp_port = intval($row['config_smtp_port']); $config_smtp_encryption = $row['config_smtp_encryption']; // SMTP provider + shared OAuth fields $config_smtp_provider = $row['config_smtp_provider']; // 'standard_smtp' | 'google_oauth' | 'microsoft_oauth' $config_mail_oauth_client_id = $row['config_mail_oauth_client_id'] ?? ''; -$config_mail_oauth_client_secret = $row['config_mail_oauth_client_secret'] ?? ''; +$config_mail_oauth_client_secret = mailSecretOpen($row['config_mail_oauth_client_secret'] ?? ''); $config_mail_oauth_tenant_id = $row['config_mail_oauth_tenant_id'] ?? ''; -$config_mail_oauth_refresh_token = $row['config_mail_oauth_refresh_token'] ?? ''; -$config_mail_oauth_access_token = $row['config_mail_oauth_access_token'] ?? ''; +$config_mail_oauth_refresh_token = mailSecretOpen($row['config_mail_oauth_refresh_token'] ?? ''); +$config_mail_oauth_access_token = mailSecretOpen($row['config_mail_oauth_access_token'] ?? ''); $config_mail_oauth_access_token_expires_at = $row['config_mail_oauth_access_token_expires_at'] ?? ''; // Switched off isn't an error - Maintenance > Cron shows why it stopped @@ -126,16 +127,12 @@ function tokenIsExpired(?string $expires_at): bool { function persistMailOauthTokens(string $access_token, string $expires_at, ?string $refresh_token = null): void { global $mysqli; - $access_token_esc = mysqli_real_escape_string($mysqli, $access_token); $expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); - $refresh_sql = ''; - if (!empty($refresh_token)) { - $refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token); - $refresh_sql = ", config_mail_oauth_refresh_token = '{$refresh_token_esc}'"; - } + // Sealed (functions/mail_secret.php) + $refresh_sql = !empty($refresh_token) ? ', ' . mailSecretSql('config_mail_oauth_refresh_token', $refresh_token) : ''; - mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '{$access_token_esc}', config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1"); + mysqli_query($mysqli, "UPDATE settings SET " . mailSecretSql('config_mail_oauth_access_token', $access_token) . ", config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1"); // This run's copy too, so the next email uses the new token rather than fetching another $GLOBALS['config_mail_oauth_access_token'] = $access_token; diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index 4608c0fb3..9f37a6df4 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -66,7 +66,7 @@ $config_invoice_late_fee_percent = floatval($row['config_invoice_late_fee_percen $config_smtp_provider = escapeSql($row['config_smtp_provider']); $config_smtp_host = $row['config_smtp_host']; $config_smtp_username = $row['config_smtp_username']; -$config_smtp_password = $row['config_smtp_password']; +$config_smtp_password = mailSecretOpen($row['config_smtp_password']); $config_smtp_port = intval($row['config_smtp_port']); $config_smtp_encryption = $row['config_smtp_encryption']; $config_mail_from_email = escapeSql($row['config_mail_from_email']); @@ -182,6 +182,9 @@ mailQueueClearSensitive(); mailQueueImageCleanup(); mysqli_query($mysqli, "DELETE FROM email_queue WHERE email_queued_at < CURDATE() - INTERVAL " . MAIL_QUEUE_KEEP_DAYS . " DAY"); +// Mail passwords and tokens still saved as typed - while config.php had no backup key - encrypted once it has one (functions/mail_secret.php) +mailSecretsSealAll(); + // Clean-up the PDFs made to go with billing emails - sent or given up on by now billingEmailPdfCleanup(7); diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php index 3c07ce17b..45af777fd 100644 --- a/cron/ticket_email_parser.php +++ b/cron/ticket_email_parser.php @@ -663,10 +663,10 @@ function getGoogleAccessToken(string $username): ?string { $config_mail_oauth_access_token = $json['access_token']; $config_mail_oauth_access_token_expires_at = $expires_at; - $at_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token); $exp_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token_expires_at); + // Sealed (functions/mail_secret.php) mysqli_query($mysqli, "UPDATE settings SET - config_mail_oauth_access_token = '{$at_esc}', + " . mailSecretSql('config_mail_oauth_access_token', $config_mail_oauth_access_token) . ", config_mail_oauth_access_token_expires_at = '{$exp_esc}' WHERE company_id = 1 "); @@ -716,10 +716,10 @@ function getMicrosoftAccessToken(string $username): ?string { $config_mail_oauth_access_token = $json['access_token']; $config_mail_oauth_access_token_expires_at = $expires_at; - $at_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token); $exp_esc = mysqli_real_escape_string($mysqli, $config_mail_oauth_access_token_expires_at); + // Sealed (functions/mail_secret.php) mysqli_query($mysqli, "UPDATE settings SET - config_mail_oauth_access_token = '{$at_esc}', + " . mailSecretSql('config_mail_oauth_access_token', $config_mail_oauth_access_token) . ", config_mail_oauth_access_token_expires_at = '{$exp_esc}' WHERE company_id = 1 "); diff --git a/css/itflow_custom.css b/css/itflow_custom.css index f988fed98..c67322948 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -6374,6 +6374,17 @@ tr:hover .itflow-files-rename, /* Ticket quick look - agent/modals/ticket/ticket.php. The details and replies are whatever came in by email, so they scroll in their box and their pictures and tables fit it. */ +/* A picture from another site in a ticket, held back until Show pictures (functions/ticket_pictures.php) - a small + dashed box where it goes, whatever size it asks for */ +img.itflow-remote-image { + display: inline-block; + width: 2.5rem !important; + height: 2rem !important; + border: 1px dashed var(--bs-border-color); + border-radius: .25rem; + background: var(--bs-tertiary-bg); +} + .itflow-ticket-glance-text { max-height: 14rem; overflow: auto; diff --git a/db.sql b/db.sql index 19bfe501f..1ea892379 100644 --- a/db.sql +++ b/db.sql @@ -4027,14 +4027,14 @@ CREATE TABLE `settings` ( `config_smtp_port` int(5) DEFAULT NULL, `config_smtp_encryption` varchar(200) DEFAULT NULL, `config_smtp_username` varchar(200) DEFAULT NULL, - `config_smtp_password` varchar(200) DEFAULT NULL, + `config_smtp_password` varchar(500) DEFAULT NULL, `config_mail_send_per_minute` int(11) NOT NULL DEFAULT 30, `config_mail_unsubscribe_secret` varchar(64) DEFAULT NULL, `config_mail_from_email` varchar(200) DEFAULT NULL, `config_mail_from_name` varchar(200) DEFAULT NULL, `config_imap_provider` varchar(200) DEFAULT NULL, `config_mail_oauth_client_id` varchar(255) DEFAULT NULL, - `config_mail_oauth_client_secret` varchar(255) DEFAULT NULL, + `config_mail_oauth_client_secret` varchar(500) DEFAULT NULL, `config_mail_oauth_tenant_id` varchar(255) DEFAULT NULL, `config_mail_oauth_refresh_token` text DEFAULT NULL, `config_mail_oauth_access_token` text DEFAULT NULL, @@ -4046,7 +4046,7 @@ CREATE TABLE `settings` ( `config_imap_port` int(5) DEFAULT NULL, `config_imap_encryption` varchar(200) DEFAULT NULL, `config_imap_username` varchar(200) DEFAULT NULL, - `config_imap_password` varchar(200) DEFAULT NULL, + `config_imap_password` varchar(500) DEFAULT NULL, `config_default_transfer_from_account` int(11) DEFAULT NULL, `config_default_transfer_to_account` int(11) DEFAULT NULL, `config_default_payment_account` int(11) DEFAULT NULL, diff --git a/functions.php b/functions.php index 470a67256..b4fcea574 100644 --- a/functions.php +++ b/functions.php @@ -147,6 +147,7 @@ require_once __DIR__ . '/functions/quick_ticket.php'; require_once __DIR__ . '/functions/getting_started.php'; require_once __DIR__ . '/functions/settings.php'; require_once __DIR__ . '/functions/mail_queue.php'; +require_once __DIR__ . '/functions/mail_secret.php'; require_once __DIR__ . '/functions/mail_graph.php'; require_once __DIR__ . '/functions/purchase_orders.php'; require_once __DIR__ . '/functions/kb.php'; diff --git a/functions/mail_graph.php b/functions/mail_graph.php index 2444d8711..1f03b732a 100644 --- a/functions/mail_graph.php +++ b/functions/mail_graph.php @@ -89,9 +89,10 @@ function mailGraphToken($permission, $fresh = false) { return null; } $client_id = trim((string) $row['config_mail_oauth_client_id']); - $secret = trim((string) $row['config_mail_oauth_client_secret']); + // Encrypted in the database (functions/mail_secret.php) + $secret = trim(mailSecretOpen($row['config_mail_oauth_client_secret'])); $tenant = trim((string) $row['config_mail_oauth_tenant_id']); - $refresh_token = trim((string) $row['config_mail_oauth_refresh_token']); + $refresh_token = trim(mailSecretOpen($row['config_mail_oauth_refresh_token'])); if ($client_id === '' || $secret === '' || $tenant === '' || $refresh_token === '') { return null; } @@ -99,7 +100,7 @@ function mailGraphToken($permission, $fresh = false) { $had = mailGraphScopesOf($row['config_mail_graph_scopes']); $expires = strtotime((string) $row['config_mail_graph_token_expires_at']); if (!$fresh && $expires && $expires - 120 > time()) { - $token = (string) $row['config_mail_graph_token']; + $token = mailSecretOpen($row['config_mail_graph_token']); return $token !== '' && in_array($permission, $had, true) ? $token : null; } @@ -125,11 +126,11 @@ function mailGraphToken($permission, $fresh = false) { // A token without the mail permissions is kept too - it is the answer until it runs out $scope = mb_substr((string) ($response['json']['scope'] ?? ''), 0, 2000); $expires_at = date('Y-m-d H:i:s', time() + max(300, intval($response['json']['expires_in'] ?? 3600))); - $set = "config_mail_graph_token = '" . mysqli_real_escape_string($mysqli, $token) . "', config_mail_graph_token_expires_at = '$expires_at', + $set = mailSecretSql('config_mail_graph_token', $token) . ", config_mail_graph_token_expires_at = '$expires_at', config_mail_graph_scopes = '" . mysqli_real_escape_string($mysqli, $scope) . "'"; // Microsoft hands back a new refresh token each time - the one to keep if (!empty($response['json']['refresh_token'])) { - $set .= ", config_mail_oauth_refresh_token = '" . mysqli_real_escape_string($mysqli, (string) $response['json']['refresh_token']) . "'"; + $set .= ', ' . mailSecretSql('config_mail_oauth_refresh_token', (string) $response['json']['refresh_token']); } mysqli_query($mysqli, "UPDATE settings SET $set WHERE company_id = 1"); diff --git a/functions/mail_secret.php b/functions/mail_secret.php new file mode 100644 index 000000000..fb24610f8 --- /dev/null +++ b/functions/mail_secret.php @@ -0,0 +1,137 @@ + Settings > Mail says so. One that can't be + * opened - the backup key was changed - reads as empty, and Admin > Settings > Mail says to enter it again. + */ + +/** The columns that hold one. */ +const MAIL_SECRET_COLUMNS = ['config_smtp_password', 'config_imap_password', 'config_mail_oauth_client_secret', + 'config_mail_oauth_refresh_token', 'config_mail_oauth_access_token', 'config_mail_graph_token']; + +/* Whether there is a key to seal them with - making the backup key when there is none and config.php can be written. */ +function mailSecretKeyThere() { + return secretSealKey('mail') !== ''; +} + +/* Whether a stored value is sealed (secretSeal()'s "enc1:"). */ +function mailSecretSealed($stored) { + return str_starts_with((string) $stored, 'enc1:'); +} + +/* $plain sealed to store - '' stays '', one sealed already stays as it is, and without a key it goes as it is. */ +function mailSecretSeal($plain) { + $plain = (string) $plain; + if ($plain === '' || mailSecretSealed($plain)) { + return $plain; + } + $sealed = secretSeal($plain, 'mail'); + return $sealed !== '' ? $sealed : $plain; +} + +/* A stored value as it was typed - one from before as it is; one that can't be opened '' (mailSecretUnreadable()). */ +function mailSecretOpen($stored) { + $stored = (string) $stored; + if (!mailSecretSealed($stored)) { + return $stored; + } + $plain = secretOpen($stored, 'mail'); + if ($plain === '') { + mailSecretUnreadable(true); + } + return $plain; +} + +/* Whether one couldn't be opened this request - $set true says one couldn't. */ +function mailSecretUnreadable($set = null) { + static $unreadable = false; + if ($set !== null) { + $unreadable = (bool) $set; + } + return $unreadable; +} + +/* Whether the 4.3.1 update has run - the columns are wide enough for a sealed value. */ +function mailSecretReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + $version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION + : (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0'); + $ready = version_compare($version, '4.3.1', '>='); + } + return $ready; +} + +/* SQL for $column set to $plain, sealed - for the places that save a token as it comes. */ +function mailSecretSql($column, $plain) { + global $mysqli; + $value = mailSecretReady() ? mailSecretSeal($plain) : (string) $plain; + return '`' . preg_replace('/[^a-z0-9_]/', '', $column) . "` = '" . mysqli_real_escape_string($mysqli, $value) . "'"; +} + +/* + * Seal every one still as typed - by the 4.3.1 update ($updating: its columns are made, though this request started + * before it) and the nightly job, for those saved before, or while there was no backup key. How many were sealed; -1 + * when there is no key to seal them with. + */ +function mailSecretsSealAll($updating = false) { + global $mysqli; + if (!$updating && !mailSecretReady()) { + return 0; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT " . implode(', ', MAIL_SECRET_COLUMNS) . " FROM settings WHERE company_id = 1")) ?: []; + $sets = []; + foreach (MAIL_SECRET_COLUMNS as $column) { + $value = (string) ($row[$column] ?? ''); + if ($value !== '' && !mailSecretSealed($value)) { + if (!mailSecretKeyThere()) { + return -1; + } + $sets[] = '`' . $column . "` = '" . mysqli_real_escape_string($mysqli, mailSecretSeal($value)) . "'"; + } + } + if ($sets) { + mysqli_query($mysqli, "UPDATE settings SET " . implode(', ', $sets) . " WHERE company_id = 1"); + } + return count($sets); +} + +/* + * What Admin > Settings > Mail says about them, or '' when all is well: kept as typed, as there is no backup key in + * config.php; or one saved that can't be opened, as the backup key changed. + */ +function mailSecretProblem() { + global $mysqli; + if (!mailSecretReady()) { + return ''; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT " . implode(', ', MAIL_SECRET_COLUMNS) . " FROM settings WHERE company_id = 1")) ?: []; + $plain = $unreadable = 0; + foreach (MAIL_SECRET_COLUMNS as $column) { + $value = (string) ($row[$column] ?? ''); + if ($value === '') { + continue; + } + if (!mailSecretSealed($value)) { + $plain++; + } elseif (mailSecretOpen($value) === '') { + $unreadable++; + } + } + if ($unreadable) { + return 'A saved password or token can\'t be read - the backup key in config.php isn\'t the one it was saved with. Enter it again, or put the old key back in config.php.'; + } + if ($plain && !mailSecretKeyThere()) { + return 'Passwords and tokens are kept as typed, as ITFlow couldn\'t add a backup key to config.php to encrypt them with. Make config.php writable, or open Maintenance > Backup for the line to add.'; + } + return ''; +} diff --git a/functions/print_sheet.php b/functions/print_sheet.php index 100d0a684..d92260050 100644 --- a/functions/print_sheet.php +++ b/functions/print_sheet.php @@ -180,7 +180,7 @@ function ticketWorkOrderHtml(array $ticket, $purifier, array $replies) { $replies_html .= '
' . '
' . escapeHtml($who) . '' . '' . ($from_client ? 'From the client' : 'Reply') . ' · ' . escapeHtml(formatDateTime($reply['ticket_reply_created_at'])) . '
' - . '
' . $purifier->purify($reply['ticket_reply']) . '
'; + . '
' . ticketHtmlForAgents($purifier, $reply['ticket_reply']) . '
'; } // Signing off the work, on site @@ -206,7 +206,7 @@ function ticketWorkOrderHtml(array $ticket, $purifier, array $replies) { . printSheetBoxHtml('Job', $job_html) . '
' . printSheetSectionHtml('Assets', $assets_html) - . printSheetSectionHtml('Description', '
' . $purifier->purify($ticket['ticket_details']) . '
') + . printSheetSectionHtml('Description', '
' . ticketHtmlForAgents($purifier, $ticket['ticket_details']) . '
') . printSheetSectionHtml('Details', printSheetFieldsHtml($fill_ins)) . printSheetSectionHtml('Tasks', $tasks_html, 'data-print-tasks') . printSheetSectionHtml('Conversation', $replies_html, 'data-print-replies') diff --git a/functions/settings.php b/functions/settings.php index 80fb92a1f..e127bea81 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -895,8 +895,10 @@ function settingsWrite($table, array $before, array $after) { } elseif (is_int($value) || is_float($value)) { $sets[] = "$column_sql = " . (is_float($value) ? rtrim(rtrim(sprintf('%.6F', $value), '0'), '.') : $value); } elseif (($fields[$column]['kind'] ?? '') === 'secret') { - // escapeSql() would trim it and take out anything that looks like a tag - a password can have both - $sets[] = "$column_sql = '" . mysqli_real_escape_string($mysqli, (string) $value) . "'"; + // escapeSql() would trim it and take out anything that looks like a tag - a password can have both. The mail + // passwords and OAuth secrets encrypted (functions/mail_secret.php) + $value = in_array($column, MAIL_SECRET_COLUMNS, true) && mailSecretReady() ? mailSecretSeal((string) $value) : (string) $value; + $sets[] = "$column_sql = '" . mysqli_real_escape_string($mysqli, $value) . "'"; } else { $sets[] = "$column_sql = '" . escapeSql((string) $value) . "'"; } diff --git a/functions/ticket_pictures.php b/functions/ticket_pictures.php index 15b794bf0..aab66a017 100644 --- a/functions/ticket_pictures.php +++ b/functions/ticket_pictures.php @@ -401,3 +401,62 @@ function ticketPicturesSweep($seconds = 25) { } return ['moved' => $moved, 'texts' => $texts, 'behind' => $behind, 'failed' => ticketPicturesFailed()]; } + +/* + * ---------- pictures from other sites, held back ---------- + * + * A client's email can carry pictures it loads from another site - a sender's logo, or a tracking pixel that tells + * them when the email was read, and from where. On a ticket that was each agent who opened it. On the agent's pages + * (the ticket, its quick look, its work order) such a picture is held back until someone clicks Show pictures - its + * address kept as data-remote-src, and a background picture's style as data-remote-style (js/app.js puts them back). + * Pictures kept as the ticket's files, and data ones, show as always. + */ + +/* A blank 1x1 GIF where a held-back picture goes. */ +const TICKET_REMOTE_IMAGE_BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; + +/* HTML someone wrote, made safe ($purifier) and with pictures from other sites held back - for the agent's pages. */ +function ticketHtmlForAgents($purifier, $html) { + return ticketRemoteImagesHold($purifier->purify((string) $html)); +} + +/* Whether a picture's address is another site's - http(s) or // to a host that isn't this install's. */ +function ticketRemoteImageUrl($url) { + global $config_base_url; + $url = html_entity_decode(trim((string) $url), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + if (!preg_match('#^(https?:)?//([^/?\#:]+)#i', $url, $m)) { + return false; + } + $own = strtolower((string) parse_url('https://' . preg_replace('#^https?://#i', '', (string) ($config_base_url ?? '')), PHP_URL_HOST)); + return strtolower($m[2]) !== $own; +} + +/* Purified HTML with the pictures from other sites held back (above). */ +function ticketRemoteImagesHold($html) { + $html = (string) $html; + if (stripos($html, ']*>#i', function ($m) { + $tag = $m[0]; + // A picture + if (preg_match('#^' + . 'Pictures from other sites are hidden, so their senders can\'t see when this is read, or from where.' + . ''; +} diff --git a/includes/load_global_settings.php b/includes/load_global_settings.php index 93653e530..19856cbea 100644 --- a/includes/load_global_settings.php +++ b/includes/load_global_settings.php @@ -45,7 +45,8 @@ $config_smtp_host = $row['config_smtp_host']; $config_smtp_port = intval($row['config_smtp_port']); $config_smtp_encryption = $row['config_smtp_encryption']; $config_smtp_username = $row['config_smtp_username']; -$config_smtp_password = $row['config_smtp_password']; +// Encrypted in the database (functions/mail_secret.php) +$config_smtp_password = function_exists('mailSecretOpen') ? mailSecretOpen($row['config_smtp_password']) : $row['config_smtp_password']; $config_mail_from_email = $row['config_mail_from_email']; $config_mail_from_name = $row['config_mail_from_name']; @@ -55,14 +56,14 @@ $config_imap_host = $row['config_imap_host']; $config_imap_port = intval($row['config_imap_port']); $config_imap_encryption = $row['config_imap_encryption']; $config_imap_username = $row['config_imap_username']; -$config_imap_password = $row['config_imap_password']; +$config_imap_password = function_exists('mailSecretOpen') ? mailSecretOpen($row['config_imap_password']) : $row['config_imap_password']; // Mail OAUTH2 $config_mail_oauth_client_id = $row['config_mail_oauth_client_id']; -$config_mail_oauth_client_secret = $row['config_mail_oauth_client_secret']; +$config_mail_oauth_client_secret = function_exists('mailSecretOpen') ? mailSecretOpen($row['config_mail_oauth_client_secret']) : $row['config_mail_oauth_client_secret']; $config_mail_oauth_tenant_id = $row['config_mail_oauth_tenant_id']; -$config_mail_oauth_refresh_token = $row['config_mail_oauth_refresh_token']; -$config_mail_oauth_access_token = $row['config_mail_oauth_access_token']; +$config_mail_oauth_refresh_token = function_exists('mailSecretOpen') ? mailSecretOpen($row['config_mail_oauth_refresh_token']) : $row['config_mail_oauth_refresh_token']; +$config_mail_oauth_access_token = function_exists('mailSecretOpen') ? mailSecretOpen($row['config_mail_oauth_access_token']) : $row['config_mail_oauth_access_token']; $config_mail_oauth_access_token_expires_at = $row['config_mail_oauth_access_token_expires_at']; // Defaults diff --git a/js/app.js b/js/app.js index e5257c8ad..822bb3164 100644 --- a/js/app.js +++ b/js/app.js @@ -957,6 +957,38 @@ function itflowInit() { // the document is already parsed, otherwise wait for it. itflowReady(itflowInit); +/* + * Pictures from other sites in a ticket's text are held back (functions/ticket_pictures.php) - the note above it says so + * when there are any, and Show pictures puts them back, in the page or the window it is in. + */ +function itflowRemoteImagesNotes(root) { + (root || document).querySelectorAll('[data-remote-images-note]').forEach(function (note) { + const scope = note.closest('.modal') || document; + note.classList.toggle('d-none', !scope.querySelector('[data-remote-src], [data-remote-style]')); + }); +} +itflowReady(function () { + itflowRemoteImagesNotes(document); +}); +itflowBindOnce('itflowRemoteImagesModal', 'shown.bs.modal', '.modal', function () { + itflowRemoteImagesNotes(this); +}); +itflowBindOnce('itflowRemoteImagesShow', 'click', '[data-show-remote-images]', function () { + const scope = this.closest('.modal') || document; + scope.querySelectorAll('[data-remote-src]').forEach(function (img) { + img.src = img.getAttribute('data-remote-src'); + img.removeAttribute('data-remote-src'); + img.classList.remove('itflow-remote-image'); + }); + scope.querySelectorAll('[data-remote-style]').forEach(function (el) { + el.setAttribute('style', el.getAttribute('data-remote-style')); + el.removeAttribute('data-remote-style'); + }); + scope.querySelectorAll('[data-remote-images-note]').forEach(function (note) { + note.classList.add('d-none'); + }); +}); + /* * Calendar event modals - the All day switch shows or hides the time row. * diff --git a/login.php b/login.php index 3ec60a69f..76c854c7d 100644 --- a/login.php +++ b/login.php @@ -89,12 +89,8 @@ $company_logo = $row['company_logo']; $config_start_page = escapeHtml($row['config_start_page']); $config_login_message = escapeHtml($row['config_login_message']); +// Whether mail is set up, for Forgot password - the sign-in page doesn't need the mail server's details or password $config_smtp_provider = $row['config_smtp_provider']; -$config_smtp_host = $row['config_smtp_host']; -$config_smtp_port = intval($row['config_smtp_port']); -$config_smtp_encryption = $row['config_smtp_encryption']; -$config_smtp_username = $row['config_smtp_username']; -$config_smtp_password = $row['config_smtp_password']; $config_mail_from_email = escapeSql($row['config_mail_from_email']); $config_mail_from_name = escapeSql($row['config_mail_from_name']);