Files
cacti/cmd_realtime.php
T
Thomas Vincent df569d630b fix(script-server): keep each response on one line and mask logged credentials (#8675)
* fix(script-server): keep each response on one line

script_server.php buffered only the include of a script file, so a data
source function that printed anything wrote it to the poller ahead of its
result, and a result containing a line break was written as several
lines. spine and cmd.php read one line per request, so either case
shifted every later reply on that server by one.

Buffer the function call and discard its output, closing the buffer even
when the function throws and logging only the size of what was dropped at
debug verbosity, since the output can carry credentials. Replace line
breaks in the result with spaces before writing it, which keeps a
multipart name:value result intact.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(script-server): print parse errors only when debugging

parseArgs() printed an ERROR line to STDOUT when a request could not be
parsed, and the caller then answered U, so the poller read the error as
the reply to that request and the U as the reply to the next one. Print
the error only when debugging, as 1.2.x already does.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(script-server): log an unparsable argument list by size only

When a request could not be parsed, the warning logged the raw argument
string, which can carry device credentials. Log its size instead, as
1.2.x already does.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(script-server): mask device credentials in logged arguments

The debug request log and the missing function warning wrote the script
arguments as given, and the signal handler logged the raw argument
string, so device SNMP credentials passed to a script reached the log.
Mask every argument, and every colon separated field of one, that
matches a configured device credential, and log only the argument count
from the signal handler, as 1.2.x already does.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(poller): mask device credentials in cmd.php script logs

cmd.php logged script and Script Server commands as given, and those
commands carry the device SNMP credentials. Mask each credential, in
every form cacti_escapeshellarg() and cacti_escapeshellarg_cmd() can
write it, before the command is logged, as 1.2.x already does.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(poller): define the Script Server pipes before cmd.php uses them

$pipes was only ever set by proc_open(), so PHPStan reported it as
possibly undefined where cmd.php closes the Script Server pipes. Start
it as an empty array, which is what every path that does not open the
Script Server already relies on.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(poller): mask device credentials in cmd.php recache logs

The recache checks logged each reindex command as given, and a data
query script or Script Server command carries the device SNMP
credentials. Mask them with the device's credentials before logging,
as the data source logs already do.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* docs(changelog): note the Script Server response and logging fixes

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(poller): cover the win32 forms of masked cmd.php credentials

CACTI_SERVER_OS is a constant, so the unit suite only ever builds the
unix forms of cacti_escapeshellarg() and cacti_escapeshellarg_cmd().
Build the win32 forms in a separate process and check that
poller_redact_snmp_secrets() masks each one, including the colon
separated SNMPv3 field, as the 1.2.x tests do.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* docs(changelog): number the Script Server entries with issue#8596

The CHANGELOG check requires every new entry to carry an issue or
pull-request number. Both entries come from issue#8596, which sorts
after issue#8480 at the end of the issue group.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(poller): give the changed-line coverage gate the masking evidence

The unit tests load the Script Server, poller and cmd.php functions
from temporary source slices, which the unit coverage report cannot
attribute to the real files, so the 80 percent changed-line gate saw
13 of 96 lines. Add a request-coverage probe that runs the same
functions at their original line numbers with checked results, and
dispatch it when cmd.php, script_server.php or lib/poller.php change.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(poller): store the first line of script output, as 1.2.x does

exec_poll() returned the line exec_with_timeout() reports, which is
the last one. A script that ends its output with a newline, as most
do, left that line empty, so cmd.php stored U for every such data
source and recache check. Return the first line instead, which is
what 1.2.x reads with fgets() and what every caller trims and stores.
exec_with_timeout() keeps its contract for its other caller.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(poller): mask device credentials when a failing script is logged

When a script exits with an error, exec_poll() logs the command and
its output, and exec_with_timeout() logs the command and its stderr. A
script data source command carries the device SNMP credentials, and
the script can echo them. exec_poll() now takes the poller item and
masks its credentials in both warnings; exec_with_timeout() takes an
optional mask for its warning, so lib/reports.php logs as before. The
masking runs only when a failure is logged. cmd.php, cmd_realtime.php
and remote_agent.php pass the item.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* docs(changelog): note the script output and failure warning fixes

Add issue#8676 entries for the first-line script output fix and the
masking of credentials in failing-script warnings, after the
issue#8596 entries at the end of the issue group.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(poller): share the cmd.php device stand-ins between test and fixture

The cmd.php log masking test and its request-coverage fixture each
declared the same database, ping, SNMP and Script Server stand-ins.
Move them into tests/Helpers/CmdDeviceStubs.php and load both in its
namespace. The test also checks that each reply is logged with its
SCRIPT or SERVER label.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* refactor(poller): share one cmd.php path for script and Script Server replies

The script and Script Server cases of collect_device_data() repeated
the same validation and logging, differing only in how the reply is
read and in the SCRIPT or SERVER log label. Read the reply per action
and run the shared validation and logging once. The log lines and the
error data sources are unchanged.

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
2026-11-09 16:31:12 -05:00

302 lines
9.1 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
require_once(__DIR__ . '/include/cli_check.php');
require_once(CACTI_PATH_LIBRARY . '/snmp.php');
require_once(CACTI_PATH_LIBRARY . '/poller.php');
require_once(CACTI_PATH_LIBRARY . '/rrd.php');
require_once(CACTI_PATH_LIBRARY . '/ping.php');
ini_set('max_execution_time', '0');
$start = date('Y-m-d H:i:s'); // for runtime measurement
// correct for a windows PHP bug. fixed in 5.2.0
if (cacti_count($_SERVER['argv']) < 4) {
print "No graph_id, interval, pollerid specified.\n\n";
print "Usage: cmd_realtime.php POLLER_ID GRAPH_ID INTERVAL\n\n";
exit(-1);
}
$poller_id = $_SERVER['argv'][1];
$graph_id = (int)$_SERVER['argv'][2];
$interval = (int)$_SERVER['argv'][3];
if (!preg_match('/^(?:[0-9]+|[A-Fa-f0-9]{64})$/', $poller_id)) {
print "Invalid poller_id specified.\n\n";
exit(-1);
}
if ($graph_id <= 0) {
print "Invalid graph_id specified.\n\n";
exit(-1);
}
if ($interval <= 0) {
print "Invalid interval specified.\n\n";
exit(-1);
}
// record the start time
$start = microtime(true);
// initialize the polling items
$polling_items = [];
// get poller_item for graph_id
$local_data_ids = db_fetch_assoc_prepared('SELECT DISTINCT dtr.local_data_id, dl.host_id
FROM graph_templates_item AS gti
INNER JOIN data_template_rrd AS dtr
ON gti.task_item_id=dtr.id
INNER JOIN data_local AS dl
ON dl.id=dtr.local_data_id
WHERE gti.local_graph_id = ?
AND dtr.local_data_id > 0',
[$graph_id]);
if (!cacti_count($local_data_ids)) {
print "No local_graph_id found\n\n";
exit(-1);
}
$ids = [];
$hosts = [];
$idbyhost = [];
foreach ($local_data_ids as $row) {
if ($row['local_data_id'] > 0 && $row['host_id'] != '') {
$ids[$row['local_data_id']] = $row['local_data_id'];
$hosts[$row['host_id']] = $row['host_id'];
$idbyhost[$row['host_id']][] = $row['local_data_id'];
}
}
$print_data_to_stdout = true;
if (cacti_sizeof($idbyhost)) {
$polling_items = db_fetch_assoc('SELECT *
FROM poller_item
WHERE local_data_id IN (' . implode(',', $ids) . ')
AND host_id IN (' . implode(',', $hosts) . ')
ORDER BY host_id');
$script_server_calls = db_fetch_cell('SELECT count(*)
FROM poller_item
WHERE action=2
AND host_id IN (' . implode(',', $hosts) . ')
AND local_data_id IN (' . implode(',', $ids) . ')');
$cactiphp = false;
// startup Cacti php polling server and include the include file for script processing
if ($script_server_calls > 0) {
$cactides = [
0 => ['pipe', 'r'], // stdin is a pipe that the child will read from
1 => ['pipe', 'w'], // stdout is a pipe that the child will write to
2 => ['pipe', 'w'] // stderr is a pipe to write to
];
if (function_exists('proc_open')) {
$cactiphp = proc_open(read_config_option('path_php_binary') . ' -q ' . CACTI_PATH_BASE . '/script_server.php realtime ' . cacti_escapeshellarg($poller_id), $cactides, $pipes);
// proc_open returns false if the child could not be spawned; fall back to
// the non-proc path rather than reading from non-existent pipes
if (!is_resource($cactiphp)) {
cacti_log('WARNING: Unable to start PHP Script Server, falling back to direct execution',
false,
'POLLER',
POLLER_VERBOSITY_LOW);
$using_proc_function = false;
$pipes = false;
} else {
$output = fgets($pipes[1], 1024);
$using_proc_function = true;
}
} else {
$using_proc_function = false;
$pipes = false;
}
} else {
$using_proc_function = false;
$pipes = false;
}
// all polled items need the same insert time
$host_update_time = date('Y-m-d H:i:s');
foreach ($idbyhost as $host_id => $local_data_ids) {
$col_poller_id = db_fetch_cell_prepared('SELECT poller_id
FROM host
WHERE id = ?', [$host_id]);
$local_data_ids = [
'local_data_ids' => $local_data_ids
];
if ($col_poller_id > 1) {
$hostname = db_fetch_cell_prepared('SELECT hostname
FROM poller
WHERE id = ?',
[$col_poller_id]);
$url = CACTI_PATH_URL . '/remote_agent.php' .
'?action=polldata' .
'&host_id=' . $host_id .
'&' . http_build_query($local_data_ids) .
'&poller_id=' . $poller_id;
$output = json_decode(call_remote_data_collector($col_poller_id, $url, 'REALTIME'), true);
if (cacti_sizeof($output)) {
$sql = '';
foreach ($output as $item) {
$sql .= ($sql != '' ? ', ' : '') . '(' .
db_qstr($item['local_data_id']) . ', ' .
db_qstr($item['rrd_name']) . ', ' .
db_qstr($host_update_time) . ', ' .
db_qstr($poller_id) . ', ' .
db_qstr($item['value']) . ')';
}
db_execute("INSERT INTO poller_output_realtime
(local_data_id, rrd_name, time, poller_id, output)
VALUES $sql");
}
} else {
$poller_items = db_fetch_assoc_prepared('SELECT *
FROM poller_item
WHERE host_id = ?
AND local_data_id IN(' . implode(',', $local_data_ids['local_data_ids']) . ')',
[$host_id]);
if (cacti_sizeof($poller_items)) {
foreach ($poller_items as $item) {
switch ($item['action']) {
case POLLER_ACTION_SNMP: // snmp
if (($item['snmp_version'] == 0) || (($item['snmp_community'] == '') && ($item['snmp_version'] != 3))) {
$output = 'U';
} else {
$host = db_fetch_row_prepared('SELECT ping_retries, max_oids
FROM host
WHERE id = ?',
[$host_id]);
if (!cacti_sizeof($host)) {
$host['ping_retries'] = 1;
$host['max_oids'] = 1;
}
$session = cacti_snmp_session($item['hostname'], $item['snmp_community'], $item['snmp_version'],
$item['snmp_username'], $item['snmp_password'], $item['snmp_auth_protocol'], $item['snmp_priv_passphrase'],
$item['snmp_priv_protocol'], $item['snmp_context'], $item['snmp_engine_id'], $item['snmp_port'],
$item['snmp_timeout'], $host['ping_retries'], $host['max_oids']);
if ($session === false) {
$output = 'U';
} else {
$output = cacti_snmp_session_get($session, $item['arg1']);
$session->close();
}
if (prepare_validate_result($output) === false) {
if (strlen($output) > 20) {
$strout = 20;
} else {
$strout = strlen($output);
}
$output = 'U';
}
}
break;
case POLLER_ACTION_SCRIPT: // script (popen)
$output = trim(exec_poll($item['arg1'], 2, $item));
if (prepare_validate_result($output) === false) {
if (strlen($output) > 20) {
$strout = 20;
} else {
$strout = strlen($output);
}
$output = 'U';
}
break;
case POLLER_ACTION_SCRIPT_PHP: // script (php script server)
if ($using_proc_function == true) {
$output = trim(str_replace("\n", '', exec_poll_php($item['arg1'], $using_proc_function, $pipes, $cactiphp)));
if (prepare_validate_result($output) === false) {
if (strlen($output) > 20) {
$strout = 20;
} else {
$strout = strlen($output);
}
$output = 'U';
}
} else {
$output = 'U';
}
break;
}
if (isset($output)) {
db_execute_prepared('INSERT INTO poller_output_realtime
(local_data_id, rrd_name, time, poller_id, output)
VALUES
(?, ?, ?, ?, ?)',
[$item['local_data_id'], $item['rrd_name'], $host_update_time, $poller_id, $output]);
}
}
}
}
}
if (($using_proc_function == true) && ($script_server_calls > 0)) {
if ($cactiphp) {
// close php server process
if (cacti_sizeof($pipes)) {
fwrite($pipes[0], "quit\r\n");
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
}
$return_value = proc_close($cactiphp);
}
}
}