diff --git a/CHANGELOG.md b/CHANGELOG.md index e4082ca2b..fd2d554e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's two database changes (3.6.6 to 3.6.8) in the same pass. They add four tables for RMM providers and their alerts, and change nothing that is there. Nothing else is required. This release has three security fixes - see Security. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's three database changes (3.6.6 to 3.6.9) in the same pass. They add four tables for RMM providers and their alerts, and a setting for device actions, and change nothing that is there. Nothing else is required. This release has three security fixes - see Security. ### Security @@ -28,7 +28,10 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - RMM Providers: bill per managed device. A recurring invoice line's Quantity from has Managed devices - the client's devices your RMM has - beside Users and Devices. Like Devices it can count only some types, Desktop and Laptop for a managed workstation, Server and Virtual Machine for a managed server, or only those with a tag. With more than one RMM it can count one of them. A device the RMM no longer has stops counting at the next invoice, and lost, stolen or retired ones never count. - RMM Providers: a product can be counted Per managed device, so it bills that way on any recurring invoice it is added to - in the product window, and as Per managed device in a product import. - RMM Providers: if the RMM provider a line counted is deleted, the line stays at the quantity it last billed, marked RMM provider gone, until another is picked. Deleting a provider says how many lines bill its devices. -- RMM Providers: the RMM Sync job is on Maintenance > Cron, and so is RMM Alerts, every minute. Turning a provider off stops its syncs, and Delete forgets its links - the assets stay as they are either way. API keys are kept like other providers' keys and never shown again. A Tactical RMM key can do whatever its Tactical user can, so make it for a user whose role can see clients and agents and no more. +- RMM Providers: device actions. Turn on Device actions in a provider's Edit, and technicians who can edit assets can reboot a device, install its patches, turn its maintenance mode on and off, and run one of the RMM's scripts on it - from Actions on the device's card on its asset, or the lightning button beside the asset on a ticket. Rebooting and installing patches ask first, and say who is signed in. Installing patches is for Windows devices, and installs what the device's patch policy approves. While maintenance mode is on, Tactical raises no alerts for the device, so none opens a ticket. +- RMM Providers: Run a script lists your RMM's scripts that run on the device's system, favorites first, and starts with the script's own arguments and timeout. The output shows in the window, and the ticket you pick - the one you started from, on a ticket - gets what was run and its output as an internal note. For a long script, turn off Wait for its output: the RMM runs it and keeps the output in the device's history there. +- RMM Providers: every device action goes in the asset's history and the audit log, and on the ticket it was done from. Device actions are off for every provider until you turn them on. Tactical does each as the API key's user, so its role needs Shutdown / Reboot Agents, Manage Windows Updates, Edit Agents for maintenance mode, and List Scripts and Run Script - give it only the ones you want, and one it hasn't got says so when tried. +- RMM Providers: the RMM Sync job is on Maintenance > Cron, and so is RMM Alerts, every minute. Turning a provider off stops its syncs, and Delete forgets its links - the assets stay as they are either way. API keys are kept like other providers' keys and never shown again. A Tactical RMM key can do whatever its Tactical user can, so make it for a user whose role can see clients and agents, and do the device actions you turn on, and no more. - API: invoices can be made with their lines, changed, emailed, marked sent, cancelled and deleted, and their lines changed or taken off. Emailing one sends it to the client's primary and billing contacts, or the contacts you name, with its link to view and pay - or a reminder of what is still owed. - API: quotes can be made with their lines - billed once, or each month, quarter or year - changed, emailed, marked sent, accepted or declined, and deleted. An accepted quote can be invoiced as Invoice does on its page: its one-time lines on a new invoice, the rest on recurring invoices. A quote's lines can be read, added, changed and taken off. - API: recurring invoices can be changed, paused or resumed, and deleted, and their lines read, added, changed and taken off - a line can count its quantity from the client's users or devices, as in the line window. @@ -65,6 +68,10 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - `rmmAlertTicketOpen()` makes the ticket the way a text does (`smsTicketOpen()`): next ticket number, `ticket_source` `RMM`, `applyTicketSla()`, the new-ticket address (`ticketMailNewTicketAddress($ticket_id, 'rmm')`) and `triggerCustomAction('ticket_create')`, but no email to the client's contacts. Its notes are internal replies with `ticket_reply_by` 0, and `rmmTicketWorked()` counts any reply by someone (`ticket_reply_by` > 0). Resolving and reopening go through `ticketResolve()` and `ticketReopen()`, so the SLA clock and history follow. `ticketSourceIcon()` and the ticket page know the `RMM` source. - Seat lines have a fourth source, `managed` (`recurringSeatSources()`): the client's assets in use that have an `rmm_devices` row not marked removed (`recurringSeatManagedSql()`). Its filter takes `types` and `tag` as `assets` does, and `rmm`, a provider id - absent for any. `recurringSeatCount()` gives null for a provider that is gone, so the line keeps its quantity as it does for a license that is gone; `recurringSeatLines()` adds `seat_gone`, the words for that. `recurringSeatOptions()` adds the managed count, types and tags, and each provider's count, once an RMM is set up. `productSeatSources()` has `managed`, and the line script, product import, AI catalog text and tag merges know it. `recurringSeatManagedLineCount($provider_id)` counts the active recurring lines that bill a provider's devices. No database change - `item_seat_source` and `product_seat_source` take the new value. - `cron/rmm_alerts.php` is the `rmm_alerts` job, every minute. It stops when cron or ticketing is off, or no provider's alerts open tickets. +- Database 3.6.9: `rmm_providers.rmm_provider_actions`, 0 for every provider until an admin turns device actions on in its Edit. Re-runnable. +- Device actions are optional kind entries: `actions` (`reboot`, `patches`, `maintenance`, `script`, each with `label`, `icon`, `needs` - the permission its key's user needs there - `about`, and `platforms` when it is only for some), `act($provider, $remote_id, $action, $options)` answering `ok`, `output`, `timed_out` and `error`, and for scripts `scripts($provider, $platform)` and `script($provider, $id)`, each script in the shape described above `rmmProviderKinds()`. `actions_help` is the provider window's text. `rmmDeviceActions($row)` is what a device offers - its provider on with actions on, the device not removed, the action for its platform - and `rmmDeviceActionsMenu($row, $ticket_id)` draws them for Modify on Support. `rmmActionTarget()` checks the device and the ticket (the asset's client's, not closed), and `rmmActionRecord()` writes the asset history, the audit log (`Asset` / `RMM`) and the ticket's internal note by the person, through the new `rmmTicketNoteHtml()` that `rmmTicketNote()` now uses. +- `agent/post/rmm.php` handles `rmm_reboot`, `rmm_install_patches`, `rmm_maintenance_on` and `rmm_maintenance_off`, each with the `rmm_devices` id and an optional `ticket_id`, and `rmm_run_script` with `script_id`, `args` (one a line), `timeout` (5 to 600) and `wait`, which answers JSON when asked for it and a flash otherwise. A script run waits up to its timeout plus 30 seconds, with `set_time_limit()` to match and the session closed first, so the person's other tabs aren't held up. The window is `agent/modals/rmm/rmm_script.php`. The request keys are in `DEMO_MODE_LOCKS`. +- Tactical: `POST /agents//reboot/`, `POST /winupdate//install/`, `PUT /agents//` with `maintenance_mode`, `GET /scripts/` and `/scripts//`, and `POST /agents//runscript/` with every key its view reads - output `wait` or `forget`, and the script's own `env_vars` as Tactical's Run Script window sends them. `rmmHttp()` takes `$text_ok` for answers that are a JSON string, reads a JSON-string error body into its message, and sends `{}` for an empty body. `rmmTacticalActError()` turns a 403 into the permission the key's role needs. - `agent/ajax.php`: the seventeen GET answers that printed JSON under PHP's default `text/html` now send `Content-Type: application/json` first - `get_credential_via_id`, `get_totp_token_via_id`, `get_readable_pass`, `get_active_clients`, `get_client_contacts`, `get_client_assets`, `get_client_locations`, `get_client_vendors`, `get_client_projects`, `get_internal_users`, `get_document_content`, `get_canned_response`, `ticket_query_views`, `client_duplicate_check`, `contact_email_check`, `network_ip_check` and `domain_check`. Their callers read the body as text (`itflowGet()`) or with `res.json()`, so nothing changes for them. A new JSON answer sets the header the same way: a value that is not escaped for HTML, as a login's username and password are not, must never go out as `text/html`. - `getFieldByIdInScope($table, $id, $field, $client_field)` (`functions/app.php`) is `getFieldById()` for a record that belongs to a client. It gives null unless `hasClientAccess()` passes for the record's client, as it does for a record that isn't there; a record with no client (0) is anyone's. Use it wherever a label is made from an id in the query string. The two labels read with their own query, on `agent/trips.php` and `agent/modals/trip/trip_export.php`, take `clientScopeSql()` instead. - `join.php` puts the login key in its sign-in link only while the invite is `pending` or `accepted` (`userInviteState()`). diff --git a/admin/database_updates/3.6.9.php b/admin/database_updates/3.6.9.php new file mode 100644 index 000000000..50901af38 --- /dev/null +++ b/admin/database_updates/3.6.9.php @@ -0,0 +1,21 @@ + $info['name'], 'alerts' => isset($info['alerts'], $info['alert']), 'alertsHelp' => (string) ($info['alerts_help'] ?? '')]; + return ['name' => $info['name'], 'alerts' => isset($info['alerts'], $info['alert']), 'alertsHelp' => (string) ($info['alerts_help'] ?? ''), + 'actions' => !empty($info['actions']), 'actionsHelp' => (string) ($info['actions_help'] ?? '')]; }, $kinds); +// Device actions - once the 3.6.9 database update is in +$actions_offered = rmmActionsReady(); + // Alerts open tickets - once the 3.6.8 database update is in, with ticketing on $alerts_offered = rmmAlertsReady() && !empty($config_module_enable_ticketing); $alert_level = (string) ($row['rmm_provider_alert_level'] ?? ''); @@ -150,6 +155,17 @@ ob_start(); + +
+
+ > + +
+
Technicians who can edit assets get them on a device's card on its asset and beside it on its tickets. Each goes in the asset's history and the audit log, and on the ticket it was done from - a script's output with it. +
+
+ + +
+ + + + + +
+ + + ['reboot', [], 'rebooted %1$s %2$s', 'couldn\'t reboot'], + 'rmm_install_patches' => ['patches', [], 'started installing the patches on %1$s %2$s', 'couldn\'t install the patches on'], + 'rmm_maintenance_on' => ['maintenance', ['on' => true], 'turned maintenance mode on for %1$s %2$s', 'couldn\'t turn maintenance mode on for'], + 'rmm_maintenance_off' => ['maintenance', ['on' => false], 'turned maintenance mode off for %1$s %2$s', 'couldn\'t turn maintenance mode off for'], + ]; + $key = (string) array_key_first(array_intersect_key($asked, $_POST)); + [$action, $options, $did, $failed] = $asked[$key]; + + [$row, $ticket, $error] = rmmActionTarget(intval($_POST[$key]), intval($_POST['ticket_id'] ?? 0), $action); + if ($row) { + $client_id = intval($row['asset_client_id']); + enforceClientAccess(); + } + if ($error !== '') { + flashAlert(escapeHtml($error), 'error'); + redirect(); + } + + $name = rmmProviderName($row); + $host = rmmActionHost($row); + $answer = rmmDeviceAct($row, $action, $options); + if (!$answer['ok']) { + flashAlert(escapeHtml("$name $failed $host. {$answer['error']}"), 'error'); + redirect(); + } + + // Maintenance mode shows straight away - the next sync says the same + if ($action === 'maintenance') { + mysqli_query($mysqli, "UPDATE rmm_devices SET rmm_device_maintenance = " . (empty($options['on']) ? 0 : 1) . " WHERE rmm_device_id = " . intval($row['rmm_device_id'])); + } + rmmActionRecord($row, $ticket, $did); + + $done = [ + 'reboot' => "$host is rebooting.", + 'patches' => "$name is installing the patches $host's patch policy approves.", + 'maintenance' => empty($options['on']) ? "Maintenance mode is off for $host." : "Maintenance mode is on for $host - $name raises no alerts for it until it's off.", + ][$action]; + flashAlert(escapeHtml($done) . ($ticket ? ' Noted on ' . escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) . '.' : '')); + + redirect(); + +} + +if (isset($_POST['rmm_run_script'])) { + + validateCSRFToken(); + + // The window asks in JSON and shows what comes back; anything else gets it as a flash + $wants_json = str_contains((string) ($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json'); + $answer_with = function (array $answer) use ($wants_json) { + if ($wants_json) { + header('Content-Type: application/json; charset=utf-8'); + echo json_encode($answer); + exit; + } + flashAlert(escapeHtml($answer['ok'] ? $answer['text'] : $answer['error']), $answer['ok'] ? 'success' : 'error'); + redirect(); + }; + + $support = intval(lookupUserPermission('module_support')); + if ($support < 2) { + $answer_with(['ok' => false, 'error' => permissionRefusedText('module_support', 2, $support)]); + } + [$row, $ticket, $error] = rmmActionTarget(intval($_POST['rmm_run_script']), intval($_POST['ticket_id'] ?? 0), 'script'); + if ($row && !hasClientAccess($row['asset_client_id'])) { + $answer_with(['ok' => false, 'error' => 'You don\'t have access to this client.']); + } + if ($error !== '') { + $answer_with(['ok' => false, 'error' => $error]); + } + + $name = rmmProviderName($row); + $host = rmmActionHost($row); + $found = rmmDeviceScript($row, (string) intval($_POST['script_id'] ?? 0)); + if (!$found['ok']) { + $answer_with(['ok' => false, 'error' => $found['error']]); + } + $script = $found['script']; + + // Its arguments, one a line, as typed - and how long to wait for it + $args = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($_POST['args'] ?? ''))), 'strlen')); + $args = array_map(function ($arg) { + return mb_substr($arg, 0, 500); + }, array_slice($args, 0, 50)); + $timeout = max(5, min(600, intval($_POST['timeout'] ?? 0) ?: $script['timeout'])); + $wait = !empty($_POST['wait']); + + // Waiting is up to the timeout, and a little more for the RMM to answer - without holding up the person's other tabs + set_time_limit($timeout + 60); + if ($wants_json) { + session_write_close(); + } + + $result = rmmDeviceAct($row, 'script', ['script' => $script, 'args' => $args, 'timeout' => $timeout, 'wait' => $wait]); + if (!$result['ok']) { + $answer_with(['ok' => false, 'error' => "$name couldn't run {$script['name']} on $host. {$result['error']}"]); + } + + // How it is kept - what was run, then its output + $ran = str_replace('%', '%%', $script['name']); + $with = $args ? ', with ' . str_replace('%', '%%', implode(' ', $args)) : ''; + $output = null; + if (!$wait) { + $what = "started the script $ran on %1\$s %2\$s$with"; + $more = '

' . escapeHtml("Its output is in the device's history in $name.") . '

'; + $text = "$name is running {$script['name']} on $host - its output will be in the device's history there."; + } elseif ($result['timed_out']) { + $what = "ran the script $ran on %1\$s %2\$s$with - it didn't finish within $timeout seconds"; + $more = '

' . escapeHtml("If it finishes, its output is in the device's history in $name.") . '

'; + $text = "{$script['name']} didn't finish on $host within $timeout seconds. If it finishes, its output is in the device's history in $name."; + } else { + $output = (string) $result['output']; + // A long one keeps its end, where the errors are + if (mb_strlen($output) > 60000) { + $output = '... (the first ' . number_format(mb_strlen($output) - 60000) . " characters left out)\n" . mb_substr($output, -60000); + } + $what = "ran the script $ran on %1\$s %2\$s$with"; + $more = '
' . escapeHtml(trim($output) !== '' ? $output : '(no output)') . '
'; + $text = "Ran {$script['name']} on $host."; + } + rmmActionRecord($row, $ticket, $what, $more); + + $answer_with([ + 'ok' => true, + 'text' => $text . ($ticket ? ' Noted on ' . $ticket['ticket_prefix'] . $ticket['ticket_number'] . '.' : ''), + 'output' => $output, + 'timed_out' => $wait && $result['timed_out'], + ]); + +} diff --git a/agent/ticket.php b/agent/ticket.php index 20ae861ed..29c971ac0 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -1666,14 +1666,21 @@ if (isset($_GET['ticket_id'])) {
Nothing linked yet. Use to add an asset, vendor, project, service or watcher.
- + -
- + - &id=" title=""> + diff --git a/db.sql b/db.sql index d19e8e006..ea3475a2c 100644 --- a/db.sql +++ b/db.sql @@ -3050,6 +3050,7 @@ CREATE TABLE `rmm_providers` ( `rmm_provider_alerts_since` datetime DEFAULT NULL, `rmm_provider_alerts_at` datetime DEFAULT NULL, `rmm_provider_alerts_note` varchar(500) DEFAULT NULL, + `rmm_provider_actions` tinyint(1) NOT NULL DEFAULT 0, `rmm_provider_created_at` datetime NOT NULL DEFAULT current_timestamp(), `rmm_provider_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), PRIMARY KEY (`rmm_provider_id`) diff --git a/functions/demo.php b/functions/demo.php index 17a2b557c..16706e2ad 100644 --- a/functions/demo.php +++ b/functions/demo.php @@ -102,6 +102,10 @@ const DEMO_MODE_LOCKS = [ 'keys' => ['add_rmm_provider', 'check_rmm_provider', 'edit_rmm_provider', 'delete_rmm_provider', 'test_rmm_provider', 'sync_rmm', 'turn_rmm_provider_off', 'turn_rmm_provider_on', 'link_rmm_client', 'link_rmm_suggested', 'unlink_rmm_client', 'rmm_bring_back'], ], + [ + 'message' => "Devices can't be rebooted or have scripts run on them in the demo.", + 'keys' => ['rmm_reboot', 'rmm_install_patches', 'rmm_maintenance_on', 'rmm_maintenance_off', 'rmm_run_script'], + ], [ 'message' => "Managed instances are turned off in the demo.", 'keys' => ['managed_checkin_now', 'managed_connect', 'managed_disconnect', 'add_managed_instance', 'delete_managed_instance', 'edit_managed_instance', diff --git a/functions/rmm.php b/functions/rmm.php index 3a2135df1..97e27b48d 100644 --- a/functions/rmm.php +++ b/functions/rmm.php @@ -27,6 +27,10 @@ * A device the RMM no longer has keeps its asset, marked as gone from it. An asset deleted in * ITFlow isn't brought back by the next sync - its row stays, with no asset, until Bring back * on the Clients page lets the sync make it again. + * + * A provider with device actions on (rmm_provider_actions) lets technicians reboot a device, + * install its patches, turn its maintenance mode on and off and run one of the RMM's scripts on + * it, from its asset or a ticket it is on - see Device actions below. */ /* @@ -52,6 +56,19 @@ * the open ones, 'error'], and fn(provider, alert's id there): ['ok', * 'alert' => it, or null when the RMM no longer has it, 'error'] - each * alert as described under Alerts below + * actions, act - optional, for device actions: action => [label, icon, needs (what its + * key's user needs there to do it), platforms (only on these, when set), + * about (what it does)] of reboot, patches, maintenance and script; and + * fn(provider, device's id there, action, options): ['ok', 'output' => a + * script's when it was waited for, else null, 'timed_out' => it wasn't + * done in time, 'error'] - options are on (maintenance), and script (as + * script gives it), args, timeout and wait for a script + * scripts, script - with the script action: fn(provider, platform): ['ok', 'scripts', 'error'], + * the ones that run there; and fn(provider, script's id): ['ok', 'script' + * => it, or null when the RMM no longer has it, 'error'] - each script + * [id, name, category, description, args, env_vars, platforms, timeout + * (seconds), favorite, hidden] + * actions_help - what its key's user needs for them, for the provider window */ /** The RMMs ITFlow can bring devices in from - kind => what it is. */ @@ -179,9 +196,10 @@ function rmmDeviceUrls(array $row): array /** * Ask an RMM's API - ['ok', 'code', 'json', 'error']: error is what to tell a person when it - * didn't work, with the kind's hints. The kind's file says where and how to sign in. + * didn't work, with the kind's hints. The kind's file says where and how to sign in. An answer + * that is only text in JSON - "ok", a script's output - is one only when $text_ok. */ -function rmmHttp(array $provider, string $method, string $url, array $headers = [], ?array $body = null, int $timeout = 30): array +function rmmHttp(array $provider, string $method, string $url, array $headers = [], ?array $body = null, int $timeout = 30, bool $text_ok = false): array { $name = rmmProviderName($provider); $hints = rmmKind($provider)['hints'] ?? []; @@ -201,7 +219,7 @@ function rmmHttp(array $provider, string $method, string $url, array $headers = CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, ]; if ($body !== null) { - $options[CURLOPT_POSTFIELDS] = json_encode($body); + $options[CURLOPT_POSTFIELDS] = $body === [] ? '{}' : json_encode($body); } curl_setopt_array($ch, $options); $raw = curl_exec($ch); @@ -226,10 +244,10 @@ function rmmHttp(array $provider, string $method, string $url, array $headers = return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "Nothing at $path on $host (HTTP 404)" . $hint('not_found')]; } if ($code < 200 || $code > 299) { - $detail = is_array($json) ? rmmText($json['detail'] ?? $json['error'] ?? $json['message'] ?? '', 300) : ''; + $detail = is_array($json) ? rmmText($json['detail'] ?? $json['error'] ?? $json['message'] ?? '', 300) : rmmText(is_string($json) ? $json : '', 300); return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "$name answered HTTP $code" . ($detail !== '' ? " - $detail" : '')]; } - if (!is_array($json)) { + if (!is_array($json) && !($text_ok && is_string($json))) { return ['ok' => false, 'code' => $code, 'json' => null, 'error' => "$host answered, but not as $name's API" . $hint('not_json')]; } return ['ok' => true, 'code' => $code, 'json' => $json, 'error' => '']; @@ -996,11 +1014,17 @@ function rmmAlertInsert(int $provider_id, array $device, array $alert, int $tick /** An internal note on a ticket, written by ITFlow - $text is plain. */ function rmmTicketNote(int $ticket_id, string $text): void +{ + rmmTicketNoteHtml($ticket_id, '

' . nl2br(escapeHtml($text)) . '

', 0); +} + +/** An internal note on a ticket from HTML made safe already - by a user, or by ITFlow (0). */ +function rmmTicketNoteHtml(int $ticket_id, string $html, int $by): void { global $mysqli; - // HTML, escaped as itself - escapeSql() would take the tags out - $html = mysqli_real_escape_string($mysqli, '

' . nl2br(escapeHtml($text)) . '

'); - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$html', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id"); + // Escaped as itself - escapeSql() would take the tags out + $html = mysqli_real_escape_string($mysqli, $html); + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$html', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $by, ticket_reply_ticket_id = $ticket_id"); mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); } @@ -1406,6 +1430,243 @@ function rmmListLabel(): string return count($providers) === 1 ? rmmProviderName($providers[0]) : 'an RMM'; } +/* + * ------------------------------------------------------------------ Device actions + * + * A provider with device actions on (rmm_provider_actions, from the 3.6.9 database update) lets + * a device that is still in its RMM be rebooted, have its patches installed, have maintenance + * mode turned on and off, and have one of the RMM's scripts run on it - by someone who can edit + * assets (Modify on Support) and see its client. They are on the device's card on its asset + * and beside it on a ticket it is on (rmmDeviceActionsMenu()), and done by agent/post/rmm.php. + * The RMM does each as its key's user, so that user's role there limits them too. Each goes in + * the asset's history and the audit log, and on the ticket it was done from as a note by whoever + * did it - a script's output with it. + */ + +/** Whether device actions can be turned on - the column arrives with the 3.6.9 database update. */ +function rmmActionsReady(): bool +{ + global $mysqli; + static $ready = null; + if ($ready === null) { + try { + mysqli_query($mysqli, "SELECT rmm_provider_actions FROM rmm_providers LIMIT 1"); + $ready = true; + } catch (Throwable $e) { + $ready = false; + } + } + return $ready; +} + +/** One device by its id, with its provider's columns, its RMM client and its asset's name and client - raw, or null when it or its asset is gone. */ +function rmmDeviceById(int $device_id): ?array +{ + global $mysqli; + if (!$device_id || !rmmTablesReady()) { + return null; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT rmm_devices.*, rmm_providers.*, rmm_client_name, rmm_client_client_id, asset_name, asset_client_id FROM rmm_devices + JOIN rmm_providers ON rmm_provider_id = rmm_device_provider_id + JOIN assets ON asset_id = rmm_device_asset_id + LEFT JOIN rmm_clients ON rmm_clients.rmm_client_id = rmm_device_rmm_client_id + WHERE rmm_device_id = $device_id LIMIT 1")); + return $row ?: null; +} + +/** + * What can be done to a device from here - action => as its kind has it. None when its provider + * hasn't device actions on, is off, or no longer has it; only the ones for its platform. + */ +function rmmDeviceActions(array $row): array +{ + $kind = rmmKind($row); + if (!$kind || empty($kind['actions']) || !isset($kind['act']) || !intval($row['rmm_provider_actions'] ?? 0) || !rmmProviderUsable($row) + || $row['rmm_device_removed_at'] !== null || (string) $row['rmm_device_remote_id'] === '' || !intval($row['rmm_device_asset_id'])) { + return []; + } + $actions = []; + foreach ($kind['actions'] as $action => $about) { + if ($action === 'script' && !isset($kind['scripts'], $kind['script'])) { + continue; + } + if (!empty($about['platforms']) && !in_array((string) $row['rmm_device_platform'], $about['platforms'], true)) { + continue; + } + $actions[$action] = $about; + } + return $actions; +} + +/** A device's platform as people call it - Windows, Linux, macOS. */ +function rmmPlatformName(string $platform): string +{ + return ['windows' => 'Windows', 'linux' => 'Linux', 'darwin' => 'macOS'][$platform] ?? ($platform !== '' ? ucfirst($platform) : 'its system'); +} + +/** What a device is called when an action is spoken of - its name in the RMM, or its asset's. */ +function rmmActionHost(array $row): string +{ + $host = trim((string) ($row['rmm_device_hostname'] ?? '')); + return $host !== '' ? $host : (trim((string) ($row['asset_name'] ?? '')) ?: 'the device'); +} + +/** + * The device and ticket an action is asked for, checked - [$row, $ticket, $error]: $row as + * rmmDeviceById() gives it, $ticket the ticket's row or null, and $error what to say when it + * can't be done. Whether the person may do it is the handler's to check, with the asset's client. + */ +function rmmActionTarget(int $device_id, int $ticket_id, string $action): array +{ + global $mysqli; + $row = rmmDeviceById($device_id); + if (!$row) { + return [null, null, 'That device, or its asset, is no longer in ITFlow.']; + } + if (!isset(rmmDeviceActions($row)[$action])) { + $name = rmmProviderName($row); + return [$row, null, rmmActionHost($row) . " can't have that done from ITFlow now - $name may be off, have its device actions off, or no longer have it."]; + } + $ticket = null; + if ($ticket_id) { + $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number FROM tickets + WHERE ticket_id = $ticket_id AND ticket_client_id = " . intval($row['asset_client_id']) . " AND ticket_closed_at IS NULL LIMIT 1")) ?: null; + if (!$ticket) { + return [$row, null, 'That ticket is closed, or isn\'t this client\'s - nothing was done.']; + } + } + return [$row, $ticket, '']; +} + +/** Do an action to a device - ['ok', 'output', 'timed_out', 'error'] as its kind's act says. */ +function rmmDeviceAct(array $row, string $action, array $options = []): array +{ + if (!isset(rmmDeviceActions($row)[$action])) { + return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => rmmActionHost($row) . ' can\'t have that done from ITFlow now.']; + } + return call_user_func(rmmKind($row)['act'], $row, (string) $row['rmm_device_remote_id'], $action, $options); +} + +/** The RMM's scripts that run on a device - ['ok', 'scripts', 'error'], each as its kind's scripts gives them. */ +function rmmDeviceScripts(array $row): array +{ + if (!isset(rmmDeviceActions($row)['script'])) { + return ['ok' => false, 'scripts' => [], 'error' => rmmActionHost($row) . ' can\'t have scripts run from ITFlow now.']; + } + return call_user_func(rmmKind($row)['scripts'], $row, (string) $row['rmm_device_platform']); +} + +/** + * One of the RMM's scripts, to run on a device - ['ok', 'script', 'error']: refused when the RMM + * no longer has it, has hidden it, or it doesn't run on the device's platform. + */ +function rmmDeviceScript(array $row, string $script_id): array +{ + if (!isset(rmmDeviceActions($row)['script'])) { + return ['ok' => false, 'script' => null, 'error' => rmmActionHost($row) . ' can\'t have scripts run from ITFlow now.']; + } + $answer = call_user_func(rmmKind($row)['script'], $row, $script_id); + if (!$answer['ok']) { + return $answer; + } + $script = $answer['script']; + $name = rmmProviderName($row); + if (!$script || $script['hidden']) { + return ['ok' => false, 'script' => null, 'error' => "$name no longer has that script - pick another."]; + } + if ($script['platforms'] && !in_array((string) $row['rmm_device_platform'], $script['platforms'], true)) { + return ['ok' => false, 'script' => null, 'error' => "{$script['name']} doesn't run on " . rmmPlatformName((string) $row['rmm_device_platform']) . ', so not on ' . rmmActionHost($row) . ' - pick another.']; + } + return ['ok' => true, 'script' => $script, 'error' => '']; +} + +/** + * The tickets an action on an asset can go on as a note - its tickets that aren't closed, newest + * first, and $also when that is one of its client's. [ticket_id => row with prefix, number, subject]. + */ +function rmmActionTickets(int $asset_id, int $client_id, int $also = 0): array +{ + global $mysqli; + $tickets = []; + $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject FROM tickets + WHERE ticket_client_id = $client_id AND ticket_closed_at IS NULL AND ticket_archived_at IS NULL + AND (ticket_asset_id = $asset_id OR ticket_id IN (SELECT ticket_id FROM ticket_assets WHERE asset_id = $asset_id) OR ticket_id = $also) + ORDER BY ticket_id = $also DESC, ticket_created_at DESC, ticket_id DESC LIMIT 25"); + while ($ticket = mysqli_fetch_assoc($sql)) { + $tickets[intval($ticket['ticket_id'])] = $ticket; + } + return $tickets; +} + +/** + * An action done to a device, kept - in its asset's history, the audit log and, when it was done + * from one, on the ticket as an internal note by whoever did it, with $html_more after (made + * safe already - a script's output). $what is plain, with %1$s for the device and %2$s for + * "through" its RMM: "rebooted %1$s %2$s". + */ +function rmmActionRecord(array $row, ?array $ticket, string $what, string $html_more = ''): void +{ + global $session_name, $session_user_id; + $through = 'through ' . rmmProviderName($row); + $asset_id = intval($row['rmm_device_asset_id']); + rmmAssetHistory($asset_id, stripslashes((string) $session_name), sprintf($what, 'it', $through)); + logAudit('Asset', 'RMM', "$session_name " . escapeSql(sprintf($what, "asset {$row['asset_name']}", $through) + . ($ticket ? " - on ticket {$ticket['ticket_prefix']}{$ticket['ticket_number']}" : '')), intval($row['asset_client_id']), $asset_id); + if ($ticket) { + rmmTicketNoteHtml(intval($ticket['ticket_id']), '

' . escapeHtml(ucfirst(sprintf($what, rmmActionHost($row), $through)) . '.') . '

' . $html_more, intval($session_user_id)); + } +} + +/** + * A device's actions as a menu - '' when it has none, or the person can't do them (Modify on + * Support). From a ticket, $ticket_id has them go on it as notes. Reboot and patches ask first, + * maintenance mode goes at once, and Run a script opens its window (modals/rmm/rmm_script.php). + * $label '' makes the button just its icon. + */ +function rmmDeviceActionsMenu(array $row, int $ticket_id = 0, string $toggle = 'btn btn-sm btn-outline-secondary', string $label = 'Actions'): string +{ + $actions = lookupUserPermission('module_support') >= 2 ? rmmDeviceActions($row) : []; + if (!$actions) { + return ''; + } + $device_id = intval($row['rmm_device_id']); + $name = rmmProviderName($row); + $host = rmmActionHost($row); + $items = ''; + foreach ($actions as $action => $about) { + $icon = ''; + $title = ' title="' . escapeHtml((string) ($about['about'] ?? '')) . '"'; + if ($action === 'script') { + $items .= '
' + . $icon . escapeHtml($about['label']) . '...'; + } elseif ($action === 'maintenance') { + $on = !intval($row['rmm_device_maintenance']); + $items .= ''; + } else { + $text = (string) ($about['about'] ?? ''); + if ($action === 'reboot' && $row['rmm_device_status'] === 'online' && (string) $row['rmm_device_logged_user'] !== '') { + $text .= ' ' . $row['rmm_device_logged_user'] . ' is signed in, and loses anything not saved.'; + } + $confirm = $action === 'reboot' ? ["Reboot $host now?", 'Reboot'] : ["Install $host's patches now?", 'Install']; + $items .= ''; + } + } + $toggle_html = $label !== '' + ? '' . escapeHtml($label) + : 'Actions in ' . escapeHtml($name) . ''; + return ''; +} + /* * ------------------------------------------------------------------ Linking clients */ @@ -1531,6 +1792,11 @@ function rmmProviderCheck(array $in, ?array $before): array $after['rmm_provider_alerts_restart'] = $level !== '' && ($level !== (string) ($before['rmm_provider_alert_level'] ?? '') || ($before && !intval($before['rmm_provider_active']) && $after['rmm_provider_active'])); } + + // Device actions - only for a kind that has them, and off until turned on + if (rmmActionsReady()) { + $after['rmm_provider_actions'] = !empty($kind['actions']) && !empty($in['actions']) ? 1 : 0; + } return [$after, $errors]; } @@ -1556,6 +1822,9 @@ function rmmProviderWrite(array $after, int $provider_id = 0): int $set[] = 'rmm_provider_alerts_since = NULL, rmm_provider_alerts_note = NULL'; } } + if (array_key_exists('rmm_provider_actions', $after)) { + $set[] = 'rmm_provider_actions = ' . intval($after['rmm_provider_actions']); + } if ($provider_id) { mysqli_query($mysqli, "UPDATE rmm_providers SET " . implode(', ', $set) . " WHERE rmm_provider_id = $provider_id"); return $provider_id; @@ -1595,5 +1864,8 @@ function rmmProviderChangeLines(array $before, array $after): array $category = intval($after['rmm_provider_alert_category_id']) ? (string) getFieldById('categories', intval($after['rmm_provider_alert_category_id']), 'category_name') : ''; $lines[] = $category === '' ? 'alert tickets not categorized' : "alert tickets in $category"; } + if (array_key_exists('rmm_provider_actions', $after) && intval($before['rmm_provider_actions'] ?? 0) !== intval($after['rmm_provider_actions'])) { + $lines[] = intval($after['rmm_provider_actions']) ? 'device actions turned on' : 'device actions turned off'; + } return $lines; } diff --git a/functions/rmm_tactical.php b/functions/rmm_tactical.php index 617d8f468..cc18270f9 100644 --- a/functions/rmm_tactical.php +++ b/functions/rmm_tactical.php @@ -12,6 +12,14 @@ * Its alerts: PATCH /alerts/ with resolvedFilter false lists the open ones its dashboard shows * (a check's or agent's dashboard alert setting decides which those are), and GET /alerts// * says whether one has cleared. The key's role needs to be able to list alerts. + * + * Its device actions, each needing its own permission in the key's role: POST + * /agents//reboot/ (Shutdown / Reboot Agents), POST /winupdate//install/ (Manage Windows + * Updates - it installs what the agent's patch policy approves, and reboots after if that policy + * says to), PUT /agents// with maintenance_mode (Edit Agents), and POST + * /agents//runscript/ (Run Script) with a script from GET /scripts/ (List Scripts). Most + * answer with text in JSON - "ok", or what went wrong with a 400; a script run with output + * "wait" answers with its output, or "timeout" when the agent didn't finish in time. */ /** What Tactical RMM is, as rmmProviderKinds() describes a kind. */ @@ -53,11 +61,28 @@ function rmmTacticalKind(): array 'alerts' => 'rmmTacticalAlerts', 'alert' => 'rmmTacticalAlert', 'alerts_help' => 'These are the alerts Tactical\'s dashboard shows - a check\'s or agent\'s Dashboard alert setting, or its alert template, decides which those are. The API key\'s user needs to be able to list alerts.', + 'actions' => [ + 'reboot' => ['label' => 'Reboot now', 'icon' => 'fa-redo-alt', 'needs' => 'Shutdown / Reboot Agents', + 'about' => 'It restarts straight away.'], + 'patches' => ['label' => 'Install patches now', 'icon' => 'fa-download', 'needs' => 'Manage Windows Updates', 'platforms' => ['windows'], + 'about' => 'Tactical installs the ones its patch policy approves, and restarts it afterwards if that policy says to.'], + 'maintenance' => ['label' => 'Maintenance mode', 'icon' => 'fa-tools', 'needs' => 'Edit Agents', + 'about' => 'While it is on, Tactical raises no alerts for it - so none opens a ticket.'], + 'script' => ['label' => 'Run a script', 'icon' => 'fa-scroll', 'needs' => 'List Scripts and Run Script', + 'about' => 'One of the scripts in Tactical\'s library, with its output back here.'], + ], + 'act' => 'rmmTacticalAct', + 'scripts' => 'rmmTacticalScripts', + 'script' => 'rmmTacticalScript', + 'actions_help' => 'Tactical does each as the API key\'s user, so its role needs Shutdown / Reboot Agents, Manage Windows Updates, Edit Agents (for maintenance mode), and List Scripts and Run Script - give it only the ones you want done from ITFlow.', ]; } -/** Ask Tactical's API. $path is Tactical's, with its trailing slash (/agents/) - it matters there. */ -function rmmTacticalRequest(array $provider, string $method, string $path, array $query = [], ?array $body = null, int $timeout = 30): array +/** + * Ask Tactical's API. $path is Tactical's, with its trailing slash (/agents/) - it matters there. + * $text_ok for the answers that are only text. + */ +function rmmTacticalRequest(array $provider, string $method, string $path, array $query = [], ?array $body = null, int $timeout = 30, bool $text_ok = false): array { $base = rmmUrlClean($provider['rmm_provider_api_url'] ?? ''); $key = trim((string) ($provider['rmm_provider_api_key'] ?? '')); @@ -65,7 +90,7 @@ function rmmTacticalRequest(array $provider, string $method, string $path, array return ['ok' => false, 'code' => 0, 'json' => null, 'error' => 'Its API address and key aren\'t set.']; } $url = $base . '/' . ltrim($path, '/') . ($query ? '?' . http_build_query($query, '', '&') : ''); - return rmmHttp($provider, $method, $url, ['X-API-KEY: ' . $key], $body, $timeout); + return rmmHttp($provider, $method, $url, ['X-API-KEY: ' . $key], $body, $timeout, $text_ok); } /** Tactical's clients - ['ok', 'clients' => [id, name, sites, devices], 'error']. */ @@ -228,6 +253,138 @@ function rmmTacticalDeviceUrls(array $provider, string $remote_id): array ]; } +/** + * Do an action to one of Tactical's agents - ['ok', 'output', 'timed_out', 'error'] (functions/rmm.php, + * Device actions). A script waited for has its output; timed_out when it didn't finish in time. + */ +function rmmTacticalAct(array $provider, string $remote_id, string $action, array $options = []): array +{ + $id = rawurlencode($remote_id); + $timeout = 30; + if ($action === 'reboot') { + $answer = rmmTacticalRequest($provider, 'POST', "/agents/$id/reboot/", [], [], 30, true); + } elseif ($action === 'patches') { + $answer = rmmTacticalRequest($provider, 'POST', "/winupdate/$id/install/", [], [], 30, true); + } elseif ($action === 'maintenance') { + $answer = rmmTacticalRequest($provider, 'PUT', "/agents/$id/", [], ['maintenance_mode' => !empty($options['on'])], 30, true); + } elseif ($action === 'script') { + $timeout = max(5, min(600, intval($options['timeout'] ?? 90))); + $wait = !empty($options['wait']); + // Every key its run_script view reads, with the script's own environment variables as Tactical's Run Script window sends them + $answer = rmmTacticalRequest($provider, 'POST', "/agents/$id/runscript/", [], [ + 'script' => intval($options['script']['id'] ?? 0), + 'output' => $wait ? 'wait' : 'forget', + 'args' => array_values(array_map('strval', (array) ($options['args'] ?? []))), + 'env_vars' => array_values(array_map('strval', (array) ($options['script']['env_vars'] ?? []))), + 'timeout' => $timeout, + 'run_as_user' => false, + 'emails' => [], + 'emailMode' => 'default', + 'custom_field' => null, + 'save_all_output' => false, + ], $timeout + 30, true); + if ($answer['ok'] && $wait) { + $output = is_string($answer['json']) ? $answer['json'] : json_encode($answer['json'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); + if (trim($output) === 'timeout') { + return ['ok' => true, 'output' => null, 'timed_out' => true, 'error' => '']; + } + return ['ok' => true, 'output' => $output, 'timed_out' => false, 'error' => '']; + } + } else { + return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => rmmProviderName($provider) . ' can\'t do that.']; + } + if (!$answer['ok']) { + return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => rmmTacticalActError($provider, $answer, $action)]; + } + return ['ok' => true, 'output' => null, 'timed_out' => false, 'error' => '']; +} + +/** What went wrong with an action, in words - what the key's role needs for it, or Tactical's own reason. */ +function rmmTacticalActError(array $provider, array $answer, string $action): string +{ + $name = rmmProviderName($provider); + if ($answer['code'] === 401 || $answer['code'] === 403) { + $needs = rmmTacticalKind()['actions'][$action]['needs'] ?? ''; + return "$name didn't let the API key do that" . ($needs !== '' ? " - its user's role needs $needs" : '') . '.'; + } + if ($answer['code'] === 404) { + return "$name no longer has that " . ($action === 'script' ? 'device or script' : 'device') . '.'; + } + if ($answer['code'] === 400 && is_string($answer['json']) && trim($answer['json']) !== '') { + $reason = rmmText($answer['json'], 300); + return "$name said: $reason" . (stripos($reason, 'unable to contact') !== false ? ' - is it online?' : ''); + } + return $answer['error']; +} + +/** Tactical's scripts that run on $platform - its favorites first, then by category and name. */ +function rmmTacticalScripts(array $provider, string $platform): array +{ + $answer = rmmTacticalRequest($provider, 'GET', '/scripts/'); + if (!$answer['ok']) { + if ($answer['code'] === 401 || $answer['code'] === 403) { + $answer['error'] = rmmProviderName($provider) . ' didn\'t let the API key see its scripts - its user\'s role needs List Scripts.'; + } + return ['ok' => false, 'scripts' => [], 'error' => $answer['error']]; + } + $scripts = []; + foreach ($answer['json'] as $script) { + if (!is_array($script) || !isset($script['id'], $script['name']) || !empty($script['hidden'])) { + continue; + } + $platforms = array_map('strval', (array) ($script['supported_platforms'] ?? [])); + if ($platforms && !in_array($platform, $platforms, true)) { + continue; + } + $scripts[] = rmmTacticalScriptShape($script); + } + usort($scripts, function ($a, $b) { + if ($a['favorite'] !== $b['favorite']) { + return $a['favorite'] ? -1 : 1; + } + if (($a['category'] === '') !== ($b['category'] === '')) { + return $a['category'] === '' ? 1 : -1; + } + return strcasecmp($a['category'], $b['category']) ?: strcasecmp($a['name'], $b['name']); + }); + return ['ok' => true, 'scripts' => $scripts, 'error' => '']; +} + +/** One of Tactical's scripts by its id - null when Tactical no longer has it. */ +function rmmTacticalScript(array $provider, string $script_id): array +{ + $answer = rmmTacticalRequest($provider, 'GET', '/scripts/' . intval($script_id) . '/'); + if (!$answer['ok']) { + if ($answer['code'] === 404) { + return ['ok' => true, 'script' => null, 'error' => '']; + } + return ['ok' => false, 'script' => null, 'error' => rmmTacticalActError($provider, $answer, 'script')]; + } + return ['ok' => true, 'script' => rmmTacticalScriptShape($answer['json']), 'error' => '']; +} + +/** One of Tactical's scripts as a script (functions/rmm.php, Device actions). */ +function rmmTacticalScriptShape(array $script): array +{ + $list = function ($values) { + return array_values(array_filter(array_map(function ($value) { + return is_scalar($value) ? mb_substr((string) $value, 0, 500) : ''; + }, (array) $values), 'strlen')); + }; + return [ + 'id' => (string) intval($script['id'] ?? 0), + 'name' => rmmText($script['name'] ?? '', 255) ?: 'Script ' . intval($script['id'] ?? 0), + 'category' => rmmText($script['category'] ?? '', 100), + 'description' => rmmText($script['description'] ?? '', 500), + 'args' => $list($script['args'] ?? []), + 'env_vars' => $list($script['env_vars'] ?? []), + 'platforms' => array_map('strval', (array) ($script['supported_platforms'] ?? [])), + 'timeout' => max(5, min(600, intval($script['default_timeout'] ?? 90) ?: 90)), + 'favorite' => !empty($script['favorite']), + 'hidden' => !empty($script['hidden']), + ]; +} + /** Tactical's one "make model" string, as ITFlow's make and model. */ function rmmTacticalMakeModel($make_model): array {