diff --git a/CHANGELOG.md b/CHANGELOG.md index e2f560103..88a5e8f65 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -123,6 +123,7 @@ Update from Maintenance > Update as usual - this release has sixteen database ch - UniFi asking ITFlow to slow down (HTTP 429) - Site Manager allows 100 requests a minute for each console - is waited out when it's a few seconds and said plainly otherwise, where it was reported as consoles needing newer firmware. - Ticket timer (forum #3237): with Start the timer on opening a ticket on, a new timer started by itself the moment a reply or note was sent, as the ticket came back - so after replying and moving on, it ran in the top bar until someone threw it away. A reply or note now puts the time on it and stops the timer: the ticket comes back with it stopped, saying "Stopped with your reply", and it stays stopped until you press play, or until you next open the ticket from somewhere else, which starts it as before. - Choosing On Hold, Resolved or Closed under Status after this pauses the ticket's timer, as was meant - it checked for a status called Pending, by a name the list doesn't carry, so it never did. +- Behind a web application firewall - CrowdSec with the OWASP Core Rule Set, ModSecurity or Cloudflare's - pasting a picture into a ticket reply, a new ticket or a document got you blocked, and soon banned: the firewall took the editor's HTML for an attack - any picture, pasted or already saved, and coloured or aligned text too - and a reply's draft, saved a moment after you stop typing, sent it again and again. What you write in an editor now goes as a file beside the form, which these firewalls don't read for that: ticket replies and their drafts, new tickets, editing a reply, documents in rich text and Markdown, Knowledge Base articles, saving a reply as a canned response, AI Reword and Draft, and new tickets and replies in the client portal. ITFlow still cleans it when it arrives, as it always has. A post too big to go as files - over PHP's upload_max_filesize, in more parts than max_file_uploads - goes as before. ### Developer Updates @@ -187,6 +188,7 @@ Update from Maintenance > Update as usual - this release has sixteen database ch - RMM sync (forum #3236): rmmSync() skips the client listing when $only is given, gives it half of $max_seconds through rmmDeadline() (rmmPastDeadline() for a kind to leave out what can wait), always syncs at least one linked client, records each synced client's device count, keeps the stored count when a kind returns devices null, and marks clients gone only from a whole list (a kind returns 'partial' with what it left). rmmUnifiSites() for unifi_cloud takes counts from Site Manager's GET /v1/sites (rmmUnifiSiteManagerSites(), by hostId and meta.name = internalReference), asks a console's connector for sites only when it has sites not in rmm_clients (rmmUnifiKnownSites()), and stops asking at the deadline; unifi_os counts per site only up to UNIFI_COUNT_SITES_MAX (50). rmmHttp() waits out a 429 with Retry-After up to RMM_RETRY_WAIT (10 s) and retries once (rmmHttpOnce() is one request), with a 'rate' hint. rmmWithoutSession() closes the PHP session around the slow calls in admin/post/rmm.php and agent/post/asset.php and reopens it for the message. - Offering autopay: database 4.3.7 adds settings.config_invoice_offer_autopay and recurring_invoices.recurring_invoice_offer_autopay (both 1). functions/billing_pay.php: autopayOfferOn() reads the setting (guarded with settingsColumnExists()); autopayOfferBlocked(billingRow('recurring')) gives why a recurring invoice isn't offered, or '' - autopay on (recurring_payment_id), billingStripeProvider() null, the setting or the recurring invoice's switch off, status not 1 or archived, or billingOnlinePayAllowed() false for its amount; autopayOffer($invoice) is null for no recurring invoice, a Cancelled or Non-Billable invoice, no url key or another client's recurring invoice, else autopayOfferDetails() - number, title, amount, currency, period, fee (billingCardFeeTerms(billingCardFeeFor())), this_invoice (still owed and due after today, which the nightly autopay charges on its due date) and url (autopayOfferUrl(), guest/guest_autopay.php with the invoice's id and url key). autopayConsentText() is what the client agrees to. billingInvoiceEmail() puts billingAutopayOfferEmail() in the invoice kind only - not receipts or reminders - as emailHtml()'s new offer part (title, text, button, small; a box after the button with an outlined button). guest/guest_autopay.php checks the key with hash_equals() and guestLinkExpired(), says when autopay is on (invoiceAutopay()) or blocked, and otherwise posts name, email and agree through js/guest_autopay_stripe.js to guest_ajax.php?guest_autopay_checkout, where autopayCheckoutStart() makes the Stripe customer if the client has none (under GET_LOCK, retried once after billingStripeCustomerGone() with billingStripeCustomerForget()) and a Checkout Session - mode setup, ui_mode embedded_page, payment_method_types card, the customer, metadata itflow_autopay_invoice_id, itflow_recurring_invoice_id, itflow_client_id, itflow_consent_name, itflow_consent_email and itflow_consent - returning its client secret for stripe.initEmbeddedCheckout(). Its return_url is guest_post.php?guest_autopay_done with the invoice's id and key, where autopayCheckoutFinish() (under GET_LOCK per recurring invoice) treats a session already in an Autopay history line as done, then retrieves the session, requires mode setup, status complete, the metadata's invoice and recurring invoice and the client's own customer, retrieves its SetupIntent (succeeded) and PaymentMethod, saves the card once per payment method id in client_saved_payment_methods, replaces the recurring_payments row, writes billingLog('recurring', ..., 'Autopay') with the card, who, the invoice, the consent and the session id, logAudit(), appNotify('Autopay') and billingMailAutopayOn() (functions/billing_email.php, with autopayChangeText()). guest_view_invoice.php and client/invoice.php show [data-autopay-offer]; the portal's posts set_recurring_payment with a saved card that hasn't expired, and set_recurring_payment (client/post.php) now writes Autopay history and appNotify() when turned on. agent/recurring_invoice.php's Autopay card posts set_recurring_offer_autopay (agent/post/recurring_invoice.php, module_sales 2) while there is no autopay and Stripe is set up. guest_autopay_checkout, guest_autopay_done and set_recurring_offer_autopay are refused in demo mode. - Ticket timer (forum #3237): agent/js/ticket_time_tracking.js sets sessionStorage ticket-timer-replied- when the reply form's submit goes through (not defaultPrevented, as with Undo send holding it), beside forceResetTimer(). On load, with no time on the ticket and ticketAutoStart on, cameBackAfterReply() keeps the timer stopped and shows [data-timer-replied] while that flag is set and document.referrer is this same ticket page (its own post's redirect, a reload, another change on the ticket); a referrer from anywhere else forgets the flag and the timer starts as before. startTimer() forgets it. A pausedTime of 0 counts as no time, and the stopped start no longer writes one, so a ticket opened with autostart off doesn't keep an empty key that stopped autostart later. checkStatusAndPauseTimer() matches the reply status select's value - a status id - against its data-timer-pause (TICKET_STATUS_ON_HOLD, RESOLVED and CLOSED), on change only and only while the timer runs; it matched "Pending" and "Close" against the id and ran on load. +- Editor fields as a file: the OWASP Core Rule Set (CrowdSec's appsec-crs, ModSecurity) blocks any posted field with tag gives max_file_uploads and upload_max_filesize within post_max_size. functions/request_fields.php: requestFieldsRestore(), from the end of functions.php, joins the parts in order, json_decodes them and puts each pair back with parse_str() into $_POST and $_REQUEST (array_replace_recursive()), unsetting $_FILES['itflow_fields']; parts missing or not that JSON stop the request with a 400 (requestFieldsFailed()), so nothing goes ahead without what was written. Forms without an editor post as before. ## [26.12.2] diff --git a/agent/ajax.php b/agent/ajax.php index 321b793ed..648ad3915 100644 --- a/agent/ajax.php +++ b/agent/ajax.php @@ -2651,7 +2651,7 @@ if (isset($_GET['ai_reword'])) { exit; } - $input = json_decode(file_get_contents('php://input'), true); + $input = requestJson(); // JSON, or as a file when it holds HTML (functions/request_fields.php) $text = is_array($input) ? (string) ($input['text'] ?? '') : ''; if (trim(str_replace("\xC2\xA0", ' ', html_entity_decode(strip_tags($text), ENT_QUOTES, 'UTF-8'))) === '') { echo json_encode(['error' => 'There is nothing to reword yet - write something first.']); @@ -2778,7 +2778,7 @@ if (isset($_GET['ai_ticket_summary'])) { // The next reply, drafted - from what the agent has typed so far, for who will read it if (isset($_GET['ai_ticket_draft'])) { - $input = json_decode(file_get_contents('php://input'), true); + $input = requestJson(); // JSON, or as a file when it holds HTML (functions/request_fields.php) $input = is_array($input) ? $input : []; $row = $aiTicket($input['ticket_id'] ?? 0, 2); if (!empty($row['ticket_closed_at'])) { diff --git a/agent/js/canned_response_save.js b/agent/js/canned_response_save.js index 485c42ad5..6752618f8 100644 --- a/agent/js/canned_response_save.js +++ b/agent/js/canned_response_save.js @@ -64,6 +64,10 @@ body.append('csrf_token', form.querySelector('input[name="csrf_token"]').value); body.append('ticket_id', form.dataset.ticketId); body.append('html', written); + // As a file, past a web application firewall (js/http.js) + if (window.itflowFields) { + window.itflowFields.pack(body, ['html']); + } fetch('/agent/ajax.php?canned_response_unfill', { method: 'POST', body: body, credentials: 'same-origin' }) .then(function (response) { if (!response.ok) { diff --git a/agent/js/ticket_reply_extras.js b/agent/js/ticket_reply_extras.js index d8df83774..db93fbdfb 100644 --- a/agent/js/ticket_reply_extras.js +++ b/agent/js/ticket_reply_extras.js @@ -144,6 +144,10 @@ data.append('csrf_token', csrf); data.append('ticket_id', ticketId); data.append('html', html); + // As a file, past a web application firewall (js/http.js) + if (window.itflowFields) { + window.itflowFields.pack(data, ['html']); + } navigator.sendBeacon('ajax.php', data); }); diff --git a/client/includes/footer.php b/client/includes/footer.php index d5d50ae93..2bc2da5a2 100644 --- a/client/includes/footer.php +++ b/client/includes/footer.php @@ -23,7 +23,7 @@ - + diff --git a/functions.php b/functions.php index e42c2dd95..7b924c77a 100644 --- a/functions.php +++ b/functions.php @@ -15,6 +15,7 @@ require_once __DIR__ . '/functions/security.php'; require_once __DIR__ . '/functions/sanitize.php'; require_once __DIR__ . '/functions/format.php'; require_once __DIR__ . '/functions/request.php'; +require_once __DIR__ . '/functions/request_fields.php'; require_once __DIR__ . '/functions/files.php'; require_once __DIR__ . '/functions/text_diff.php'; require_once __DIR__ . '/functions/markdown.php'; @@ -166,3 +167,7 @@ require_once __DIR__ . '/functions/dev_mode.php'; // The connection config.php opened takes the collation the tables have, so that a string the // server makes (CAST(x AS CHAR), say) matches them - functions/database_collation.php databaseConnectionCollation(); + +// What an editor held, sent beside the form as a file so web application firewalls don't take its +// HTML for an attack - back into $_POST before anything reads it (functions/request_fields.php) +requestFieldsRestore(); diff --git a/functions/request_fields.php b/functions/request_fields.php new file mode 100644 index 000000000..e0c3f536e --- /dev/null +++ b/functions/request_fields.php @@ -0,0 +1,117 @@ + at all, a pasted picture's + * data: address, a colour or an alignment (style=) each block the post, and a few in a short + * while ban whoever sent them. A reply's draft, saved a moment after typing stops, sent it + * again and again. + * + * So the browser (js/http.js) sends what an editor holds - each rich-text editor's and Markdown + * box's field, and anything itflowPost() sends that looks like HTML - as one JSON file beside + * the form, itflow_fields[0], [1]... (split to fit upload_max_filesize), which a firewall + * doesn't read as fields. requestFieldsRestore() puts the fields back into $_POST before + * anything reads them, so every page and handler gets what was written as it always has, and + * ITFlow cleans it as it always has (HTMLPurifier). The file: + * + * {"v": 1, "fields": [["ticket_reply", "

...

"], ["items[3][description]", "..."], ...]} + * + * Field names are posted names - brackets and all - and read as PHP reads a posted form. + */ + +const REQUEST_FIELDS_FILE = 'itflow_fields'; + +/** A php.ini size - 8M, 512K, 2G - in bytes. */ +function requestIniBytes($value) { + $value = trim((string) $value); + $number = intval($value); + switch (strtolower(substr($value, -1))) { + case 'g': + return $number * 1024 * 1024 * 1024; + case 'm': + return $number * 1024 * 1024; + case 'k': + return $number * 1024; + } + return $number; +} + +/* + * What the browser can send as files, for js/http.js's - + diff --git a/js/app.js b/js/app.js index 822bb3164..2ca3fcfb8 100644 --- a/js/app.js +++ b/js/app.js @@ -235,12 +235,7 @@ function itflowAiReword(editor, ticket) { var clientId = element ? parseInt(element.getAttribute('data-ai-client-id') || '0', 10) : 0; buttonApi.setEnabled(false); editor.setProgressState(true); - fetch(ai.endpoint + '?ai_reword' + (ticket ? '&use_case=Tickets' : ''), { - method: 'POST', - credentials: 'same-origin', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ text: editor.getContent(), client_id: clientId || 0, tone: tone, language: language || '' }) - }) + fetch(ai.endpoint + '?ai_reword' + (ticket ? '&use_case=Tickets' : ''), itflowJsonPost({ text: editor.getContent(), client_id: clientId || 0, tone: tone, language: language || '' })) .then(function (response) { return response.json().catch(function () { throw new Error('HTTP ' + response.status); @@ -348,12 +343,7 @@ function itflowAiDraft(editor, ticketId, say) { var notes = editor.getContent({ format: 'text' }).trim() === '' ? '' : editor.getContent(); buttonApi.setEnabled(false); editor.setProgressState(true); - fetch(window.itflowAi.endpoint + '?ai_ticket_draft', { - method: 'POST', - credentials: 'same-origin', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ticket_id: ticketId, notes: notes, type: types[picked ? picked.value : '2'] || 'email' }) - }) + fetch(window.itflowAi.endpoint + '?ai_ticket_draft', itflowJsonPost({ ticket_id: ticketId, notes: notes, type: types[picked ? picked.value : '2'] || 'email' })) .then(function (response) { return response.json().catch(function () { throw new Error('HTTP ' + response.status); diff --git a/js/document_markdown.js b/js/document_markdown.js index 9b47c2543..3408ae95e 100644 --- a/js/document_markdown.js +++ b/js/document_markdown.js @@ -38,11 +38,13 @@ var URL_BASE = (script && script.getAttribute('data-markdown-url')) || '/agent/ajax.php'; function post(action, data) { + // What is written goes as a file, past a web application firewall (js/http.js) + var body = window.itflowFields ? window.itflowFields.body(new URLSearchParams(data), ['html', 'markdown']) : new URLSearchParams(data).toString(); return fetch(URL_BASE + '?' + action, { method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + headers: typeof body === 'string' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}, credentials: 'same-origin', - body: new URLSearchParams(data).toString() + body: body }).then(function (response) { return response.json().catch(function () { throw new Error(''); diff --git a/js/http.js b/js/http.js index a0dcfee4c..f877fad59 100644 --- a/js/http.js +++ b/js/http.js @@ -12,6 +12,155 @@ * break them. */ +/* + * What an editor holds, sent as a file. A web application firewall in front of ITFlow - + * ModSecurity, Cloudflare's, CrowdSec's with the OWASP Core Rule Set - takes a rich-text + * editor's HTML for an attack: an , a pasted picture's data: address or a colour (style=) + * blocks the post, and a few soon ban whoever sent them. So each rich-text editor's and Markdown + * box's field, and what itflowPost() sends that looks like HTML, goes as one JSON file beside the + * form - itflow_fields[0], [1]..., which a firewall doesn't read as fields - and + * functions/request_fields.php puts them back before anything reads the post. + * + * - A form posted, or read with new FormData(form): its editors' fields, on its formdata event + * - itflowPost(): any value that looks like HTML + * - itflowFields.pack(formData, names) / itflowFields.body(data, names): a post built by hand + * + * Within what the server takes - this script's data-max-files and data-max-bytes (php.ini's + * max_file_uploads, and upload_max_filesize within post_max_size): what won't fit goes as + * fields, as before. + */ +var itflowFields = window.itflowFields || (function () { + 'use strict'; + + var script = document.currentScript; + var attr = function (name, fallback) { + var value = script ? parseInt(script.getAttribute(name) || '', 10) : NaN; + return isNaN(value) ? fallback : value; + }; + var maxFiles = attr('data-max-files', 20); + var maxBytes = attr('data-max-bytes', 2 * 1024 * 1024); + var FIELD = 'itflow_fields'; + + // What a firewall takes for HTML or script - a tag, a data: or javascript: address + var LOOKS_RICH = /<[a-z!\/?]|data:[a-z]|javascript:/i; + + function rich(value) { + return typeof value === 'string' && LOOKS_RICH.test(value); + } + + /* + * names' values taken out of formData into the JSON file - every value each has, in order - + * true when they were. A name with a file among its values stays, and so does everything + * when it won't fit. + */ + function pack(formData, names) { + if (!formData || typeof TextEncoder !== 'function' || typeof Blob !== 'function' || maxFiles < 1) { + return false; + } + var fields = []; + var moving = []; + names.forEach(function (name) { + if (!name || moving.indexOf(name) !== -1 || !formData.has(name)) { + return; + } + var values = formData.getAll(name); + if (values.some(function (value) { return typeof value !== 'string'; })) { + return; + } + moving.push(name); + values.forEach(function (value) { + fields.push([name, value]); + }); + }); + if (!moving.length) { + return false; + } + + var bytes = new TextEncoder().encode(JSON.stringify({ v: 1, fields: fields })); + var size = Math.max(16 * 1024, maxBytes - 8 * 1024); // room for each part's headers + var parts = Math.ceil(bytes.length / size); + var files = 0; + formData.forEach(function (value) { + if (typeof value !== 'string' && value.name) { + files++; // a file input left empty doesn't count against max_file_uploads + } + }); + if (files + parts > maxFiles || maxBytes < 16 * 1024) { + return false; + } + + moving.forEach(function (name) { + formData.delete(name); + }); + for (var i = 0; i < parts; i++) { + formData.append(FIELD + '[' + i + ']', new Blob([bytes.subarray(i * size, (i + 1) * size)], { type: 'application/json' }), 'fields-' + i + '.json'); + } + return true; + } + + /* + * A body to post: FormData with names' values - and any other that looks like HTML - in + * the file, or a URL-encoded string when there is nothing to move. data is an object, as + * itflowSerialize() takes, or URLSearchParams. + */ + function body(data, names) { + var params = data instanceof URLSearchParams ? data : new URLSearchParams(itflowSerialize(data)); + var moving = (names || []).slice(); + params.forEach(function (value, name) { + if (rich(value)) { + moving.push(name); + } + }); + if (!moving.length || typeof FormData !== 'function') { + return params.toString(); + } + var formData = new FormData(); + params.forEach(function (value, name) { + formData.append(name, value); + }); + return pack(formData, moving) ? formData : params.toString(); + } + + // A form's editors - the fields of its rich-text editors and Markdown boxes - when it posts + function editorNames(form) { + var names = []; + if (form && form.tagName === 'FORM' && (form.getAttribute('method') || '').toLowerCase() === 'post') { + form.querySelectorAll('textarea[name]').forEach(function (field) { + if (field.hasAttribute('data-markdown-input') || /(^|\s)tinymce/.test(field.className) + || (window.tinymce && field.id && window.tinymce.get(field.id))) { + names.push(field.name); + } + }); + } + return names; + } + + /* + * A form with an editor posts as multipart/form-data, so the file can go with it - set as it + * is sent, before the browser reads how (and by js/tinymce_defaults.js as each editor starts, + * for a form a script sends with submit()) + */ + function multipart(form) { + if (editorNames(form).length) { + form.enctype = 'multipart/form-data'; + } + } + document.addEventListener('submit', function (e) { + multipart(e.target); + }, true); + + // Its editors' fields into the file - as it posts, or is read with new FormData(form) + document.addEventListener('formdata', function (e) { + var names = editorNames(e.target); + if (names.length) { + pack(e.formData, names); + } + }, true); + + return { pack: pack, body: body, rich: rich, multipart: multipart }; +})(); +window.itflowFields = itflowFields; + /** Serialise to PHP-style bracket params, the way jQuery did. */ function itflowSerialize(data) { const params = new URLSearchParams(); @@ -63,11 +212,13 @@ function itflowGet(url, data, success, error) { } function itflowPost(url, data, success, error) { + // What looks like HTML goes as a file, past a web application firewall (itflowFields above) + const body = itflowFields.body(data); return fetch(url, { method: 'POST', - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + headers: typeof body === 'string' ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}, credentials: 'same-origin', - body: itflowSerialize(data) + body: body }) .then(function (res) { if (!res.ok) { @@ -90,6 +241,23 @@ function itflowPost(url, data, success, error) { }); } +/* + * fetch() options posting payload as JSON, to an endpoint that reads it with requestJson() + * (functions/request_fields.php) - in itflowFields' file when it holds HTML, so a web + * application firewall doesn't read it, else as the JSON body it always was. + */ +function itflowJsonPost(payload) { + const json = JSON.stringify(payload); + if (itflowFields.rich(json) && typeof FormData === 'function') { + const formData = new FormData(); + formData.append('itflow_json', json); + if (itflowFields.pack(formData, ['itflow_json'])) { + return { method: 'POST', credentials: 'same-origin', body: formData }; + } + } + return { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: json }; +} + /** Kept for the kanban and invoice item-order callers, which use this name. */ function itflowPostForm(url, data) { return itflowPost(url, data); diff --git a/js/tinymce_defaults.js b/js/tinymce_defaults.js index cfb4cc9fc..b67fc6a15 100644 --- a/js/tinymce_defaults.js +++ b/js/tinymce_defaults.js @@ -74,6 +74,12 @@ tinymce.on('AddEditor', function (added) { var editor = added.editor; + // Its form posts as multipart, so what is written can go as a file (itflowFields, js/http.js) + var element = editor.getElement(); + if (window.itflowFields && element && element.form) { + window.itflowFields.multipart(element.form); + } + // Ahead of TinyMCE's own paste handling, which leaves a paste that was already dealt with alone editor.on('paste', function (event) { if (event.isDefaultPrevented() || !editor.options.get('paste_data_images')) {