diff --git a/CHANGELOG b/CHANGELOG index ef5ff8e9f0..ed10bf1d00 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -244,6 +244,10 @@ Cacti CHANGELOG -issue#8370: When drilling a Site Branch into a Device Template, the Tree view Graph Templates filter now lists only the Graph Templates present on that Device Template's devices -issue#8460: Keep all four digits of an AKCP securityProbe Fahrenheit reading of 100 F or more instead of cutting it to three, and return U for a reading that is not a number -issue#8480: Keep wrapped Cacti theme titles and controls inside their titlebars and improve text-link contrast on light rows +-issue#8596: Discard stray output from Script Server functions and keep each response on one line +-issue#8596: Keep device credentials out of Script Server and cmd.php log messages that describe a script's arguments +-issue#8676: Store the first line of a script's output instead of U when the script ends its output with a newline +-issue#8676: Keep device credentials out of the warnings logged when a script exits with an error -feature#8166: Add a cross-process shared SNMP authentication cache (disabled by default) that pre-hardens SNMPv3 credential arguments once per credential change and seals them with the per-installation AES-256-GCM key, so poller, cmd and script server processes reuse them instead of rebuilding them on every request -feature#8166: Route SNMPv3 get/getnext through the in-process php-snmp extension when the running PHP version supports the configured auth/privacy protocols and no context/engine id is set, bypassing a per-request Net-SNMP binary spawn -feature#8166: Add an "Enable MD5 and DES for SNMPv3" setting (off by default) that removes the legacy MD5/DES algorithms from the Device and Automation SNMP Option pickers when disabled, and default new Devices to SHA/AES diff --git a/cmd.php b/cmd.php index 1ff6df64d9..5830b14bf8 100755 --- a/cmd.php +++ b/cmd.php @@ -320,6 +320,7 @@ if (cacti_sizeof($poller_items) && read_config_option('poller_enabled') == 'on') $itemcnt = 0; $host_start = microtime(true); $set_spike_kill = false; + $pipes = []; /* startup Cacti php polling server and include the * include file for script processing @@ -901,46 +902,22 @@ function collect_device_data(array &$item, array &$error_ds, int $script_timeout break; case POLLER_ACTION_SCRIPT: - $output = trim(exec_poll($item['arg1'], $script_timeout)); - - if ($output == 'U') { - $error_ds[$ds] = $ds; - - if (read_config_option('spine_log_level') == 2) { - cacti_log("WARNING: Invalid Response, Device[$host_id] DS[$ds] SCRIPT: " . $item['arg1'] . ', output: U', - $print_data_to_stdout, - 'POLLER'); - } - } elseif (!is_numeric($output)) { - if (prepare_validate_result($output) == false) { - $error_ds[$ds] = $ds; - - if (read_config_option('spine_log_level') == 2) { - cacti_log("WARNING: Invalid Response, Device[$host_id] DS[$ds] SCRIPT: " . $item['arg1'] . ", output: $output", - $print_data_to_stdout, - 'POLLER'); - } - } - } - - $total_time = (microtime(true) - $thread_start) * 1000; - - cacti_log("Device[$host_id] DS[$ds] TT[" . round($total_time, - 2) . '] SCRIPT: ' . $item['arg1'] . ", output: $output", - $print_data_to_stdout, - 'POLLER', - debug_level($host_id, - POLLER_VERBOSITY_MEDIUM)); - - break; case POLLER_ACTION_SCRIPT_PHP: - $output = trim(str_replace("\n", '', exec_poll_php($item['arg1'], $using_proc_function, $pipes, $cactiphp))); + if ($item['action'] == POLLER_ACTION_SCRIPT) { + $output = trim(exec_poll($item['arg1'], $script_timeout, $item)); + $type = 'SCRIPT'; + } else { + $output = trim(str_replace("\n", '', exec_poll_php($item['arg1'], $using_proc_function, $pipes, $cactiphp))); + $type = 'SERVER'; + } + + $log_arg1 = poller_redact_snmp_secrets($item['arg1'], $item); if ($output == 'U') { $error_ds[$ds] = $ds; if (read_config_option('spine_log_level') == 2) { - cacti_log("WARNING: Invalid Response, Device[$host_id] DS[$ds] SERVER: " . $item['arg1'] . ', output: U', + cacti_log("WARNING: Invalid Response, Device[$host_id] DS[$ds] $type: " . $log_arg1 . ', output: U', $print_data_to_stdout, 'POLLER'); } @@ -949,7 +926,7 @@ function collect_device_data(array &$item, array &$error_ds, int $script_timeout $error_ds[$ds] = $ds; if (read_config_option('spine_log_level') == 2) { - cacti_log("WARNING: Invalid Response, Device[$host_id] DS[$ds] SERVER: " . $item['arg1'] . ", output: $output", + cacti_log("WARNING: Invalid Response, Device[$host_id] DS[$ds] $type: " . $log_arg1 . ", output: $output", $print_data_to_stdout, 'POLLER'); } @@ -959,7 +936,7 @@ function collect_device_data(array &$item, array &$error_ds, int $script_timeout $total_time = (microtime(true) - $thread_start) * 1000; cacti_log("Device[$host_id] DS[$ds] TT[" . round($total_time, - 2) . '] SERVER: ' . $item['arg1'] . ", output: $output", + 2) . "] $type: " . $log_arg1 . ", output: $output", $print_data_to_stdout, 'POLLER', debug_level($host_id, @@ -1040,6 +1017,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : foreach ($reindex as $index_item) { $assert_fail = false; + $log_arg1 = poller_redact_snmp_secrets($index_item['arg1'], $item); switch ($index_item['action']) { case POLLER_ACTION_SNMP: @@ -1073,7 +1051,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : cacti_log("Device[$host_id] DQ[" . $index_item['data_query_id'] . '] RECACHE OID: ' . - $index_item['arg1'] . + $log_arg1 . ', (assert:' . $index_item['assert_value'] . ' ' . @@ -1088,7 +1066,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : break; case POLLER_ACTION_SCRIPT: - $output = trim(exec_poll($index_item['arg1'], $script_timeout)); + $output = trim(exec_poll($index_item['arg1'], $script_timeout, $item)); if (!is_numeric($output)) { if (prepare_validate_result($output) == false) { @@ -1112,7 +1090,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : cacti_log("Device[$host_id] DQ[" . $index_item['data_query_id'] . '] RECACHE SCRIPT: ' . - $index_item['arg1'] . + $log_arg1 . ", output: $output", $print_data_to_stdout, 'POLLER', @@ -1150,7 +1128,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : cacti_log("Device[$host_id] DQ[" . $index_item['data_query_id'] . '] RECACHE SERVER: ' . - $index_item['arg1'] . + $log_arg1 . ", output: $output", $print_data_to_stdout, 'POLLER', @@ -1170,7 +1148,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : cacti_log("Device[$host_id] DQ[" . $index_item['data_query_id'] . '] RECACHE OID COUNT: ' . - $index_item['arg1'] . + $log_arg1 . ', output: ' . $output, $print_data_to_stdout, @@ -1187,7 +1165,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : cacti_log("Device[$host_id] DQ[" . $index_item['data_query_id'] . '] RECACHE CMD COUNT: ' . - $index_item['arg1'] . + $log_arg1 . ", output: $output", $print_data_to_stdout, 'POLLER', @@ -1202,7 +1180,7 @@ function ping_and_reindex_check(array &$item, bool $mibs, int $script_timeout) : cacti_log("Device[$host_id] DQ[" . $index_item['data_query_id'] . '] RECACHE SERVER COUNT: ' . - $index_item['arg1'] . + $log_arg1 . ", output: $output", $print_data_to_stdout, 'POLLER', diff --git a/cmd_realtime.php b/cmd_realtime.php index 69fdaa306c..fdb12d5199 100644 --- a/cmd_realtime.php +++ b/cmd_realtime.php @@ -240,7 +240,7 @@ if (cacti_sizeof($idbyhost)) { break; case POLLER_ACTION_SCRIPT: // script (popen) - $output = trim(exec_poll($item['arg1'], 2)); + $output = trim(exec_poll($item['arg1'], 2, $item)); if (prepare_validate_result($output) === false) { if (strlen($output) > 20) { diff --git a/lib/poller.php b/lib/poller.php index 997560dcf2..3078c79746 100644 --- a/lib/poller.php +++ b/lib/poller.php @@ -65,10 +65,67 @@ function script_server_log_request(int $pid, int $ctr, string $include_file, str } cacti_log("DEBUG: PID[$pid] CTR[$ctr] INC: '" . basename($include_file) . - "' FUNC: '$function' PARMS: '" . implode('\', \'', $parameter_array) . + "' FUNC: '$function' PARMS: '" . implode('\', \'', script_server_redact_params($parameter_array)) . "'", false, 'PHPSVR'); } +/** + * Masks any device SNMP credential among Script Server arguments before they + * are logged. + * + * The Script Server cannot tell which argument is a credential, so every + * argument, and every colon separated field of one, is compared with the + * credentials configured on the devices. + * + * @param array $params The parsed parameters. + * @param array|null $secrets Credential values as keys, or null to load them once from the database. + * + * @return array The parameters with credentials masked. + */ +function script_server_redact_params(array $params, ?array $secrets = null) : array { + static $known = null; + + if ($secrets === null) { + if ($known === null) { + $known = []; + + $rows = db_fetch_assoc('SELECT DISTINCT snmp_community, snmp_password, snmp_priv_passphrase FROM host'); + + if (is_array($rows)) { + foreach ($rows as $row) { + foreach ($row as $value) { + if ($value != '') { + $known[$value] = true; + } + } + } + } + } + + $secrets = $known; + } + + foreach ($params as $index => $param) { + $param = (string) $param; + + if (isset($secrets[$param])) { + $params[$index] = '********'; + } elseif (strpos($param, ':') !== false) { + $fields = explode(':', $param); + + foreach ($fields as $findex => $field) { + if ($field != '' && isset($secrets[$field])) { + $fields[$findex] = '********'; + } + } + + $params[$index] = implode(':', $fields); + } + } + + return $params; +} + /** * Logs a Script Server response line at debug verbosity. * @@ -89,24 +146,84 @@ function script_server_log_response(int $pid, int $ctr, string $result) : void { cacti_log("DEBUG: PID[$pid] CTR[$ctr] RESPONSE:'$result'", false, 'PHPSVR'); } +/** + * Masks a device's SNMP credentials in a poller command before it is logged. + * + * @param string $string The command or argument string. + * @param array $item A poller_item or host row carrying the SNMP credential columns. + * + * @return string The string with each non-empty credential masked. + */ +function poller_redact_snmp_secrets(string $string, array $item) : string { + $secrets = []; + + foreach (['snmp_community', 'snmp_password', 'snmp_priv_passphrase'] as $column) { + if (!isset($item[$column]) || $item[$column] == '') { + continue; + } + + // the command line carries each credential as cacti_escapeshellarg() + // or cacti_escapeshellarg_cmd() wrote it, so mask every form either + // can produce on unix and win32, not just the stored value + $value = (string) $item[$column]; + $bases = [$value, str_replace(["\n", "\r"], '', $value)]; + $cmd = str_replace(['"', '&', '|', '^', '<', '>', '(', ')'], '', $bases[1]); + $bases[] = $cmd; + $bases[] = str_replace('%', '', $cmd); + + foreach ($bases as $base) { + $secrets[] = $base; + $secrets[] = str_replace("'", "'\\''", $base); + $secrets[] = str_replace(CACTI_ESCAPE_CHARACTER, '\\' . CACTI_ESCAPE_CHARACTER, $base); + } + } + + $secrets = array_unique(array_filter($secrets, function (string $secret) : bool { + return $secret !== ''; + })); + + if (!cacti_sizeof($secrets)) { + return $string; + } + + // longest first, so a credential that contains another is masked whole + usort($secrets, function (string $a, string $b) : int { + return strlen($b) - strlen($a); + }); + + return str_replace($secrets, '********', $string); +} + /** * exec_poll - executes a command and returns its output * * @param string $command The command to execute * @param int $timeout The command timeout + * @param array $item The poller item, whose SNMP credentials are masked when the command is logged * * @return string The output of $command after execution */ -function exec_poll(string $command, int $timeout = 5) : string { +function exec_poll(string $command, int $timeout = 5, array $item = []) : string { $output = []; $return = 0; - $data = exec_with_timeout($command, $output, $return, $timeout); + // the command, its output and its stderr can carry the device credentials, + // so they are masked, but only when a failure is logged + $redact = function (string $string) use ($item) : string { + return poller_redact_snmp_secrets($string, $item); + }; + + exec_with_timeout($command, $output, $return, $timeout, $redact); if ($return != 0) { - cacti_log(sprintf('WARNING: Script:%s, ErrorCode:%d, Output:%s', $command, $return, implode(',', $output)), false, 'POLLER'); + cacti_log($redact(sprintf('WARNING: Script:%s, ErrorCode:%d, Output:%s', $command, $return, implode(',', $output))), false, 'POLLER'); } + // the result is the first line of output, as 1.2.x reads it; the line + // exec_with_timeout() returns is the last one, which is empty when the + // script ends its output with a newline + $data = $output[0] ?? ''; + if ($data == '') { return 'U'; } else { @@ -337,14 +454,15 @@ function poller_cactid_arguments(string $base_path, bool $debug) : array { * exec_with_timeout - Execute a command and return it's output. Either wait until the * command exits or the timeout has expired. * - * @param string $cmd Command to execute. - * @param array $output A return array of output. - * @param int $return_code The return code from the script - * @param int $timeout Timeout in seconds. + * @param string $cmd Command to execute. + * @param array $output A return array of output. + * @param int $return_code The return code from the script + * @param int $timeout Timeout in seconds. + * @param callable|null $redact Masks credentials in the command and stderr before they are logged. * * @return mixed Either the last line of output or false on error */ -function exec_with_timeout(string $cmd, array &$output, int &$return_code, int $timeout = 5) : mixed { +function exec_with_timeout(string $cmd, array &$output, int &$return_code, int $timeout = 5, ?callable $redact = null) : mixed { // File descriptors passed to the process. $descriptors = [ 0 => ['pipe', 'r'], // stdin @@ -426,7 +544,9 @@ function exec_with_timeout(string $cmd, array &$output, int &$return_code, int $ // Only surface stderr noise when the command actually failed; successful // commands may write informational output to stderr that isn't actionable. if ($return_code != 0 && !empty($errors)) { - cacti_log("WARNING: Command '$cmd' exited with code $return_code, stderr: " . trim($errors), false, 'POLLER', POLLER_VERBOSITY_MEDIUM); + $message = "WARNING: Command '$cmd' exited with code $return_code, stderr: " . trim($errors); + + cacti_log($redact === null ? $message : $redact($message), false, 'POLLER', POLLER_VERBOSITY_MEDIUM); } // Kill the process in case the timeout expired and it's still running. diff --git a/remote_agent.php b/remote_agent.php index ca45cbcb52..cb836c8753 100644 --- a/remote_agent.php +++ b/remote_agent.php @@ -461,7 +461,7 @@ function poll_for_data() : mixed { break; case POLLER_ACTION_SCRIPT: // script (popen) - $output = trim(exec_poll($item['arg1'])); + $output = trim(exec_poll($item['arg1'], 5, $item)); if (prepare_validate_result($output) === false) { if (strlen($output) > 20) { diff --git a/script_server.php b/script_server.php index 6d9c41c1a2..2f83170245 100644 --- a/script_server.php +++ b/script_server.php @@ -272,7 +272,7 @@ while (1) { } if (!parseArgs($parameters, $parameter_array)) { - cacti_log("WARNING: Script Server count not parse '$parameters' for $function", false, 'PHPSVR'); + script_server_log_parse_failure($function, $parameters); fputs(STDOUT, "U\n"); fflush(STDOUT); @@ -391,28 +391,16 @@ while (1) { error_reporting(0); - if ($parameters == '') { - $result = call_user_func($function); - } else { - $result = call_user_func_array($function, $parameter_array); - } + $result = script_server_call($function, $parameters, $parameter_array); - fputs(STDOUT, trim($result) . "\n"); + fputs(STDOUT, script_server_response($result) . "\n"); fflush(STDOUT); script_server_log_response((int) $pid, $ctr, $result); $ctr++; } else { - cacti_log("WARNING: Function does not exist INC: '" . - basename($include_file) . - "' FUNC: '" . - $function . - "' PARMS: '" . - $parameters . - "'", - false, - 'PHPSVR'); + script_server_log_missing_function($include_file, $function, $parameter_array); fputs(STDOUT, "U\n"); fflush(STDOUT); } @@ -538,7 +526,11 @@ function parseArgs(string $string, array &$str_list, bool $debug = false) : bool } if (!$parse_ok) { - print 'ERROR: ' . $msg . " '" . $string . "'\n"; + // the caller answers U on STDOUT; an extra line here would be read as + // the reply to the next request + if ($debug) { + print 'ERROR: ' . $msg . " '" . $string . "'\n"; + } } elseif ($curstr != '') { $str_list[] = $curstr; } @@ -550,6 +542,103 @@ function parseArgs(string $string, array &$str_list, bool $debug = false) : bool return $parse_ok; } +/** + * script_server_log_parse_failure - logs a request whose arguments could not be parsed + * + * The arguments can carry device credentials, so only their size is logged. + * + * @param string $function The function named by the request. + * @param string $parameters The raw parameter string. + * + * @return void + */ +function script_server_log_parse_failure(string $function, string $parameters) : void { + cacti_log('WARNING: Script Server could not parse the ' . strlen($parameters) . " byte argument list for $function", false, 'PHPSVR'); +} + +/** + * script_server_log_missing_function - logs a request for a function that does not exist + * + * The arguments can carry device credentials, so device credentials are masked. + * + * @param string $include_file The script file named by the request. + * @param string $function The function named by the request. + * @param array $parameter_array The parsed parameters. + * + * @return void + */ +function script_server_log_missing_function(string $include_file, string $function, array $parameter_array) : void { + cacti_log("WARNING: Function does not exist INC: '" . + basename($include_file) . + "' FUNC: '" . + $function . + "' PARMS: '" . + implode('\', \'', script_server_redact_params($parameter_array)) . + "'", + false, + 'PHPSVR'); +} + +/** + * script_server_call - calls a script function and discards anything it prints + * + * Anything the function prints would reach the poller ahead of its result and + * be read as the reply to this request, shifting every later reply by one line. + * + * @param callable-string $function The function name, already checked to exist. + * @param string $parameters The raw parameter string. + * @param array $parameter_array The parsed parameters. + * + * @return mixed The function result. + */ +function script_server_call(string $function, string $parameters, array $parameter_array) : mixed { + $ob_level = ob_get_level(); + ob_start(); + + try { + if ($parameters == '') { + $result = call_user_func($function); + } else { + $result = call_user_func_array($function, $parameter_array); + } + } finally { + // also closes any buffer the function left open; the output can carry + // credentials, so only its size is logged + $stray = 0; + + while (ob_get_level() > $ob_level) { + $output = ob_get_clean(); + + if ($output === false) { + break; + } + + $stray += strlen($output); + } + + if ($stray > 0) { + cacti_log("DEBUG: Function '$function' wrote $stray bytes of output, discarded", false, 'PHPSVR', POLLER_VERBOSITY_DEBUG); + } + } + + return $result; +} + +/** + * script_server_response - formats a script function result as one response line + * + * The poller reads one line per request, so a line break inside the result + * would be read as the reply to the next request. Multipart results are space + * separated name:value pairs, so a line break becomes a space. + * + * @param mixed $result The function result. + * + * @return string The result without line breaks or surrounding white space. + */ +function script_server_response(mixed $result) : string { + return trim(str_replace(["\r\n", "\r", "\n"], ' ', (string) $result)); +} + /** * sig_handler - properly handle signals and shutdown * @@ -558,7 +647,10 @@ function parseArgs(string $string, array &$str_list, bool $debug = false) : bool * @return void */ function sig_handler(int $signo) : void { - global $include_file, $function, $parameters; + global $include_file, $function, $parameter_array; + + // argument values can carry device credentials, so only their count is logged + $parameters = (is_array($parameter_array) ? cacti_count($parameter_array) : 0) . ' argument(s)'; switch ($signo) { case SIGTERM: diff --git a/tests/Helpers/CmdDeviceStubs.php b/tests/Helpers/CmdDeviceStubs.php new file mode 100644 index 0000000000..db1b42bf14 --- /dev/null +++ b/tests/Helpers/CmdDeviceStubs.php @@ -0,0 +1,77 @@ + 2][$name] ?? ''; +} + +function debug_level(int $host_id, int $level) : int { + return $level; +} + +function exec_poll_php(string $command, bool $using_proc_function, array $pipes, mixed $proc_fd) : string { + return $GLOBALS['cmd_device_reply'] . "\n"; +} + +function exec_into_array(string $command) : array { + return ['1', '2', '3']; +} + +function db_fetch_row_prepared($sql, $params = []) { + return ['hostname' => 'host1', 'ping_port' => 0, 'ping_method' => 0, 'ping_retries' => 1, 'ping_timeout' => 400, 'availability_method' => 0]; +} + +function db_fetch_assoc_prepared($sql, $params = []) { + return $GLOBALS['cmd_device_reindex']; +} + +function db_execute_prepared($sql, $params = [], $log = true, $db_conn = false) { + return true; +} + +function update_host_status(...$arguments) { +} + +function update_system_mibs($host_id) { +} + +function open_snmp_session($host_id, &$item) { + return 'session'; +} + +function cacti_snmp_session_get($session, $oid, $strip_alpha = false) { + return '42'; +} + +function cacti_snmp_session_walk($session, $oid) { + return [['oid' => $oid . '.1', 'value' => '1']]; +} + +function cacti_snmp_select_uptime(...$arguments) { + return '42'; +} + +class Net_Ping { + public $host = []; + + public $port = 0; + + public function ping($avail_method, $ping_type, $timeout, $retries) { + return true; + } +} diff --git a/tests/Unit/DataCollection/Cmd/CmdLogCredentialMaskingTest.php b/tests/Unit/DataCollection/Cmd/CmdLogCredentialMaskingTest.php new file mode 100644 index 0000000000..8313f52133 --- /dev/null +++ b/tests/Unit/DataCollection/Cmd/CmdLogCredentialMaskingTest.php @@ -0,0 +1,226 @@ + 'script', POLLER_ACTION_SCRIPT_PHP => 'script server'] as $action => $label) { + foreach (['U', 'not a number', '42'] as $reply) { + test("cmd.php masks the credentials when it logs a $label reply of '$reply'", function () use ($action, $reply) { + $GLOBALS['cmd_device_reply'] = $reply; + + $item = [ + 'local_data_id' => 3, + 'host_id' => 7, + 'action' => $action, + 'snmp_community' => 'c0mm', + 'snmp_password' => "zq'xw", + 'snmp_priv_passphrase' => '', + 'arg1' => '/opt/cacti/scripts/ss_x.php ss_x ' . \cacti_escapeshellarg('c0mm') . ' ' . \cacti_escapeshellarg("zq'xw"), + ]; + $error_ds = []; + + collect_device_data($item, $error_ds, 25); + + $log = implode("\n", $GLOBALS['cmd_mask_log']); + + expect($log)->not->toContain('c0mm') + ->and($log)->not->toContain('zq') + ->and($log)->not->toContain('xw') + ->and($log)->toContain('ss_x.php ss_x ') + ->and($log)->toContain($action == POLLER_ACTION_SCRIPT ? '] SCRIPT: /opt' : '] SERVER: /opt'); + + if ($reply !== '42') { + expect($log)->toContain('DS[3] ' . ($action == POLLER_ACTION_SCRIPT ? 'SCRIPT' : 'SERVER') . ': /opt'); + } + + // a bad reply is logged twice, as a warning and with the timing + expect(substr_count($log, '********'))->toBe($reply === '42' ? 2 : 4); + }); + } +} + +test('cmd.php masks the credentials in every recache log line that names the command', function () { + $GLOBALS['cmd_device_reply'] = '42'; + $GLOBALS['poller_id'] = 1; + $GLOBALS['set_spike_kill'] = false; + + $args = ' ' . \cacti_escapeshellarg('c0mm') . ' ' . \cacti_escapeshellarg("zq'xw"); + + $GLOBALS['cmd_device_reindex'] = []; + + foreach ([ + POLLER_ACTION_SNMP => 'RECACHE OID: ', + POLLER_ACTION_SCRIPT => 'RECACHE SCRIPT: ', + POLLER_ACTION_SCRIPT_PHP => 'RECACHE SERVER: ', + POLLER_ACTION_SNMP_COUNT => 'RECACHE OID COUNT: ', + POLLER_ACTION_SCRIPT_COUNT => 'RECACHE CMD COUNT: ', + POLLER_ACTION_SCRIPT_PHP_COUNT => 'RECACHE SERVER COUNT: ', + ] as $action => $label) { + $GLOBALS['cmd_device_reindex'][] = ['data_query_id' => $action, 'action' => $action, 'op' => '=', 'assert_value' => '42', 'arg1' => '/opt/cacti/scripts/ss_q.php ss_q' . $args]; + } + + $item = ['host_id' => 7, 'hostname' => 'host1', 'snmp_community' => 'c0mm', 'snmp_password' => "zq'xw", 'snmp_priv_passphrase' => '']; + + expect(ping_and_reindex_check($item, false, 25))->toBeFalse(); + + $lines = array_values(array_filter($GLOBALS['cmd_mask_log'], function ($line) { + return strpos($line, 'ss_q.php') !== false; + })); + $log = implode("\n", $lines); + + expect($lines)->toHaveCount(6) + ->and($log)->not->toContain('c0mm') + ->and($log)->not->toContain('zq') + ->and($log)->not->toContain('xw') + ->and(substr_count($log, '********'))->toBe(12); + + foreach (['RECACHE OID: ', 'RECACHE SCRIPT: ', 'RECACHE SERVER: ', 'RECACHE OID COUNT: ', 'RECACHE CMD COUNT: ', 'RECACHE SERVER COUNT: '] as $label) { + expect($log)->toContain($label . '/opt/cacti/scripts/ss_q.php ss_q '); + } +}); + +test('cmd.php log arguments mask the item credentials', function () { + $item = ['snmp_community' => 'pub', 'snmp_password' => 'pubpass', 'snmp_priv_passphrase' => '']; + + expect(poller_redact_snmp_secrets("/x/ss.php f 'h' 'pubpass' 'pub'", $item))->toBe("/x/ss.php f 'h' '********' '********'") + ->and(poller_redact_snmp_secrets('no secrets here', []))->toBe('no secrets here'); +}); + +test('cmd.php log arguments mask a credential in its escaped forms', function (string $secret) { + $item = ['snmp_community' => '', 'snmp_password' => $secret, 'snmp_priv_passphrase' => '']; + $command = implode(' ', ['f', \cacti_escapeshellarg('host1'), \cacti_escapeshellarg($secret), \cacti_escapeshellarg_cmd($secret, true, true)]); + $masked = poller_redact_snmp_secrets($command, $item); + + expect(substr_count($masked, '********'))->toBe(2) + ->and($masked)->toContain('host1'); + + // no word of the credential survives, whatever escaping wrapped it + foreach (preg_split('/[^A-Za-z]+/', $secret, -1, PREG_SPLIT_NO_EMPTY) as $word) { + if (strlen($word) >= 4) { + expect($masked)->not->toContain($word); + } + } +})->with([ + 'apostrophe' => ["it's'secret"], + 'double quote' => ['say"secret"'], + 'backslash' => ['back\\slash\\secret'], + 'space' => ['secret with spaces'], + 'cmd metachar' => ['a&b|c^d(f)%g'], +]); + +test('cmd.php log arguments mask a credential that contains another credential whole', function () { + $item = ['snmp_community' => 'pub', 'snmp_password' => 'pubpubpass', 'snmp_priv_passphrase' => '']; + + expect(poller_redact_snmp_secrets("f 'pubpubpass' 'pub'", $item))->toBe("f '********' '********'"); +}); + +test('cmd.php log arguments ignore empty credentials', function () { + $item = ['snmp_community' => '', 'snmp_password' => '', 'snmp_priv_passphrase' => '0']; + + expect(poller_redact_snmp_secrets("f '' 'x0y'", $item))->toBe("f '' 'x********y'") + ->and(poller_redact_snmp_secrets("f '' 'xy'", ['snmp_community' => '']))->toBe("f '' 'xy'"); +}); + +/* + * CACTI_SERVER_OS is a constant, so the win32 escaping forms are built and + * masked in a separate process by tests/fixtures/PollerRedactSecretsWin32Probe.php. + */ +test('cmd.php log arguments mask a credential in its win32 escaped forms', function () { + $secrets = [ + 'apostrophe' => "it's'secret", + 'double quote' => 'say"secret"', + 'backslash' => 'back\\slash\\secret', + 'space' => 'secret with spaces', + 'cmd metachar' => 'a&b|c^d(f)%g', + 'percent' => 'pa%ss%word', + ]; + + $root = dirname(__DIR__, 4); + $process = proc_open( + [PHP_BINARY, $root . '/tests/fixtures/PollerRedactSecretsWin32Probe.php'], + [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + $root + ); + + expect(is_resource($process))->toBeTrue(); + + fwrite($pipes[0], json_encode($secrets)); + fclose($pipes[0]); + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + + expect(proc_close($process))->toBe(0, $stderr); + + $masked = json_decode($stdout, true); + + expect($masked)->toBeArray()->toHaveCount(18); + + foreach ($secrets as $label => $secret) { + foreach (['win32', 'win32 cmd', 'win32 cmd strip'] as $form) { + $command = $masked["$label/$form"]; + + // the credential argument and the colon separated SNMPv3 field + expect(substr_count($command, '********'))->toBe(2, "$label/$form: $command") + ->and($command)->toContain('"host1"') + ->and($command)->toContain(':SHA'); + + // no word of the credential survives, whatever escaping wrapped it + foreach (preg_split('/[^A-Za-z]+/', $secret, -1, PREG_SPLIT_NO_EMPTY) as $word) { + if (strlen($word) >= 4) { + expect($command)->not->toContain($word, "$label/$form: $command"); + } + } + } + } +}); diff --git a/tests/Unit/DataCollection/Poller/ExecPollLogMaskingTest.php b/tests/Unit/DataCollection/Poller/ExecPollLogMaskingTest.php new file mode 100644 index 0000000000..b1c0c7187a --- /dev/null +++ b/tests/Unit/DataCollection/Poller/ExecPollLogMaskingTest.php @@ -0,0 +1,90 @@ + 'c0mmunity', 'snmp_password' => "auth'pass", 'snmp_priv_passphrase' => '']; + + expect(exec_poll(exec_mask_failing_command(), 5, $item))->toBe('out c0mmunity'); + + $log = implode("\n", $GLOBALS['exec_mask_log']); + + expect($log)->toContain('ErrorCode:3') + ->and($log)->toContain('exited with code 3') + ->and($log)->toContain('out ********') + ->and($log)->toContain('err ********') + ->and($log)->not->toContain('c0mmunity') + ->and($log)->not->toContain('auth'); +}); + +test('exec_with_timeout logs the command as given when the caller passes no mask', function () { + $output = []; + $return = 0; + + exec_with_timeout(exec_mask_failing_command(), $output, $return, 5); + + expect($return)->toBe(3) + ->and(implode("\n", $GLOBALS['exec_mask_log']))->toContain('c0mmunity'); +}); + +test('every script data source caller passes the poller item to exec_poll', function () { + $root = dirname(__DIR__, 4); + + expect(file_get_contents($root . '/cmd.php'))->toContain('exec_poll($item[\'arg1\'], $script_timeout, $item)') + ->and(file_get_contents($root . '/cmd.php'))->toContain('exec_poll($index_item[\'arg1\'], $script_timeout, $item)') + ->and(file_get_contents($root . '/cmd_realtime.php'))->toContain('exec_poll($item[\'arg1\'], 2, $item)') + ->and(file_get_contents($root . '/remote_agent.php'))->toContain('exec_poll($item[\'arg1\'], 5, $item)'); +}); diff --git a/tests/Unit/DataCollection/Poller/ExecWithTimeoutTest.php b/tests/Unit/DataCollection/Poller/ExecWithTimeoutTest.php index a95c20548d..b541c84c35 100644 --- a/tests/Unit/DataCollection/Poller/ExecWithTimeoutTest.php +++ b/tests/Unit/DataCollection/Poller/ExecWithTimeoutTest.php @@ -161,3 +161,25 @@ test('operator precedence inline: cast-after-multiply preserves microseconds', f expect($buggy)->toBe(0) ->and($fixed)->toBe(3000); }); + +// --- issue#8596: exec_poll() returns the first line of output, as 1.2.x does --- + +test('exec_poll stores a script value that ends with a newline', function () { + expect(trim(exec_poll(PHP_BINARY . ' -r ' . escapeshellarg('print "7\n";'), 5)))->toBe('7'); +}); + +test('exec_poll stores a script value without a trailing newline', function () { + expect(trim(exec_poll(PHP_BINARY . ' -r ' . escapeshellarg('print "7";'), 5)))->toBe('7'); +}); + +test('exec_poll returns the first line of multi-line output, as 1.2.x reads it with fgets()', function (string $script) { + expect(trim(exec_poll(PHP_BINARY . ' -r ' . escapeshellarg($script), 5)))->toBe('in:1 out:2'); +})->with([ + 'trailing newline' => ['print "in:1 out:2\nextra line\n";'], + 'no trailing newline' => ['print "in:1 out:2\nextra line";'], + 'carriage returns' => ['print "in:1 out:2\r\nextra line\r\n";'], +]); + +test('exec_poll returns U for a script that prints nothing', function () { + expect(exec_poll(PHP_BINARY . ' -r ' . escapeshellarg('exit(0);'), 5))->toBe('U'); +}); diff --git a/tests/Unit/DataCollection/Poller/ScriptServerResponseTest.php b/tests/Unit/DataCollection/Poller/ScriptServerResponseTest.php new file mode 100644 index 0000000000..dc5e0fdd7f --- /dev/null +++ b/tests/Unit/DataCollection/Poller/ScriptServerResponseTest.php @@ -0,0 +1,233 @@ + 'c0mmunity', 'snmp_password' => 'authpass', 'snmp_priv_passphrase' => ''], + ]; +} + +function ss_response_fixture_echo($a) { + print "community $a\n"; + + return "value:$a"; +} + +function ss_response_fixture_multiline() { + return "a:1\nb:2"; +} + +function ss_response_fixture_echo_throws() { + print 'partial output'; + ob_start(); + print 'nested buffer left open'; + + throw new \RuntimeException('script failure'); +} + +if (!function_exists(__NAMESPACE__ . '\\script_server_call')) { + foreach (['parseArgs', 'script_server_log_parse_failure', 'script_server_log_missing_function', 'script_server_call', 'script_server_response', 'sig_handler'] as $function) { + \cacti_fixture_source_function(dirname(__DIR__, 4) . '/script_server.php', $function, __NAMESPACE__); + } + + foreach (['script_server_log_request', 'script_server_redact_params'] as $function) { + \cacti_fixture_source_function(dirname(__DIR__, 4) . '/lib/poller.php', $function, __NAMESPACE__); + } +} + +const SS_RESPONSE_PARAMS = ['host1', 'c0mmunity', '3:161:500:1:10::user:authpass:SHA']; + +function ss_response_expect_masked(string $log) : void { + expect($log)->not->toContain('c0mmunity') + ->and($log)->not->toContain('authpass') + ->and($log)->toContain("'host1', '********', '3:161:500:1:10::user:********:SHA'"); +} + +beforeEach(function () { + $GLOBALS['ss_response_log'] = []; +}); + +test('output printed by a script is discarded and only its size is logged', function () { + $level = ob_get_level(); + + ob_start(); + $result = script_server_call(__NAMESPACE__ . '\\ss_response_fixture_echo', 'secret-value', ['secret-value']); + $printed = ob_get_clean(); + + expect($printed)->toBe('') + ->and($result)->toBe('value:secret-value') + ->and(ob_get_level())->toBe($level); + + $log = implode("\n", $GLOBALS['ss_response_log']); + + expect($log)->toContain('wrote 23 bytes of output, discarded') + ->and($log)->not->toContain('community') + ->and($log)->not->toContain('secret-value'); +}); + +test('output of a script that throws is discarded with any buffer it left open', function () { + $level = ob_get_level(); + + ob_start(); + + try { + script_server_call(__NAMESPACE__ . '\\ss_response_fixture_echo_throws', '', []); + $thrown = false; + } catch (\RuntimeException $e) { + $thrown = true; + } + + $printed = ob_get_clean(); + + expect($thrown)->toBeTrue() + ->and($printed)->toBe('') + ->and(ob_get_level())->toBe($level); +}); + +test('a script that prints nothing logs nothing', function () { + expect(script_server_call(__NAMESPACE__ . '\\ss_response_fixture_multiline', '', []))->toBe("a:1\nb:2") + ->and($GLOBALS['ss_response_log'])->toBe([]); +}); + +test('a multipart result with line breaks is sent as one line', function () { + $line = script_server_response(script_server_call(__NAMESPACE__ . '\\ss_response_fixture_multiline', '', [])) . "\n"; + + expect($line)->toBe("a:1 b:2\n") + ->and(script_server_response("\r\na:1\r\nb:2\rc:3 \n"))->toBe('a:1 b:2 c:3'); +}); + +test('scalar and empty results keep their response text', function () { + expect(script_server_response(42))->toBe('42') + ->and(script_server_response(1.5))->toBe('1.5') + ->and(script_server_response(null))->toBe('') + ->and(script_server_response(' U '))->toBe('U'); +}); + +test('the main loop writes the single line response', function () { + $source = file_get_contents(dirname(__DIR__, 4) . '/script_server.php'); + + expect($source)->toContain('fputs(STDOUT, script_server_response($result) . "\n");') + ->and($source)->not->toContain('fputs(STDOUT, trim($result)'); +}); + +test('an unparsable request writes nothing ahead of the U reply', function () { + $parsed = []; + + ob_start(); + $ok = parseArgs("'open", $parsed); + $printed = ob_get_clean(); + + expect($ok)->toBeFalse() + ->and($printed)->toBe(''); +}); + +test('a parse error is still printed when debugging', function () { + $parsed = []; + + ob_start(); + $ok = parseArgs("'open", $parsed, true); + $printed = ob_get_clean(); + + expect($ok)->toBeFalse() + ->and($printed)->toContain("ERROR: Parse error attempting to parse string ''open'"); +}); + +test('an unparsable argument list is logged by size, never by content', function () { + $parameters = "'host1' 'c0mmunity"; + + script_server_log_parse_failure('ss_example', $parameters); + + $log = implode("\n", $GLOBALS['ss_response_log']); + + expect($log)->not->toContain($parameters) + ->and($log)->not->toContain('c0mmunity') + ->and($log)->toContain('could not parse the ' . strlen($parameters) . ' byte argument list for ss_example'); +}); + +test('the debug request log masks device credentials', function () { + global $config; + + $saved = $config[OPTIONS_CLI] ?? null; + + $config[OPTIONS_CLI]['selective_debug'] = ''; + $config[OPTIONS_CLI]['selective_plugin_debug'] = ''; + $config[OPTIONS_CLI]['log_verbosity'] = POLLER_VERBOSITY_DEBUG; + + try { + script_server_log_request(1234, 1, '/scripts/ss_example.php', 'ss_example', SS_RESPONSE_PARAMS); + } finally { + $config[OPTIONS_CLI] = $saved; + } + + ss_response_expect_masked(implode("\n", $GLOBALS['ss_response_log'])); +}); + +test('the missing function warning masks device credentials', function () { + script_server_log_missing_function('/scripts/ss_example.php', 'ss_missing', SS_RESPONSE_PARAMS); + + $log = implode("\n", $GLOBALS['ss_response_log']); + + ss_response_expect_masked($log); + expect($log)->toContain("FUNC: 'ss_missing'"); +}); + +test('a signal logs the argument count, never the arguments', function () { + $saved = [$GLOBALS['include_file'] ?? null, $GLOBALS['function'] ?? null, $GLOBALS['parameters'] ?? null, $GLOBALS['parameter_array'] ?? null]; + + $GLOBALS['include_file'] = '/scripts/ss_example.php'; + $GLOBALS['function'] = 'ss_example'; + $GLOBALS['parameters'] = "'host1' 'c0mmunity' '3:161:500:1:10::user:authpass:SHA'"; + $GLOBALS['parameter_array'] = SS_RESPONSE_PARAMS; + + try { + sig_handler(SIGUSR1); + } finally { + [$GLOBALS['include_file'], $GLOBALS['function'], $GLOBALS['parameters'], $GLOBALS['parameter_array']] = $saved; + } + + $log = implode("\n", $GLOBALS['ss_response_log']); + + expect($log)->not->toContain('c0mmunity') + ->and($log)->not->toContain('authpass') + ->and($log)->toContain("function:'ss_example', params:'3 argument(s)'"); +})->skip(!defined('SIGUSR1'), 'pcntl is not available'); + +test('credentials are masked whole and as colon separated fields', function () { + $secrets = ['c0mmunity' => true, 'authpass' => true]; + + expect(script_server_redact_params(['host1', 'c0mmunity', '3:161:500:1:10::user:authpass:SHA', 'index', 42], $secrets)) + ->toBe(['host1', '********', '3:161:500:1:10::user:********:SHA', 'index', 42]) + ->and(script_server_redact_params(['xc0mmunityx', ''], $secrets))->toBe(['xc0mmunityx', '']); +}); diff --git a/tests/fixtures/PollerRedactSecretsWin32Probe.php b/tests/fixtures/PollerRedactSecretsWin32Probe.php new file mode 100644 index 0000000000..fa915595b1 --- /dev/null +++ b/tests/fixtures/PollerRedactSecretsWin32Probe.php @@ -0,0 +1,68 @@ +/
". + */ + +$root = dirname(__DIR__, 2); + +define('CACTI_SERVER_OS', 'win32'); +define('SNMP_ESCAPE_CHARACTER', '"'); +define('CACTI_ESCAPE_CHARACTER', '"'); + +require_once $root . '/include/vendor/autoload.php'; +require_once $root . '/lib/functions.php'; +require_once $root . '/tests/Helpers/SourceSlice.php'; + +cacti_fixture_source_function($root . '/lib/poller.php', 'poller_redact_snmp_secrets', ''); + +$forms = [ + 'win32' => function (string $arg) : string { + return cacti_escapeshellarg($arg); + }, + 'win32 cmd' => function (string $arg) : string { + return cacti_escapeshellarg_cmd($arg); + }, + 'win32 cmd strip' => function (string $arg) : string { + return cacti_escapeshellarg_cmd($arg, true, true); + }, +]; + +$secrets = json_decode((string) stream_get_contents(STDIN), true); +$results = []; + +foreach ($secrets as $label => $secret) { + $item = ['snmp_community' => '', 'snmp_password' => $secret, 'snmp_priv_passphrase' => '']; + + foreach ($forms as $form => $escape) { + $parts = ['/opt/cacti/scripts/ss_x.php', 'ss_x']; + + foreach (['host1', $secret, "3:161:500:1:10::user:$secret:SHA"] as $arg) { + $parts[] = $escape($arg); + } + + $results["$label/$form"] = poller_redact_snmp_secrets(implode(' ', $parts), $item); + } +} + +print json_encode($results); diff --git a/tests/fixtures/ScriptServerLogMaskingCoverage.php b/tests/fixtures/ScriptServerLogMaskingCoverage.php new file mode 100644 index 0000000000..f9c89ac0da --- /dev/null +++ b/tests/fixtures/ScriptServerLogMaskingCoverage.php @@ -0,0 +1,189 @@ + 'c0mmunity', 'snmp_password' => 'authpass', 'snmp_priv_passphrase' => ''], + ]; +} + +function dsv_log(string $message, mixed $data = null, int $level = POLLER_VERBOSITY_LOW) : void { +} + +function ss_cov_echo($a) { + print "community $a\n"; + + return "value:$a"; +} + +function ss_cov_multiline() { + return "a:1\r\nb:2\nc:3"; +} + +function ss_cov_quiet() { + return '7'; +} + +function ss_cov_check(bool $passed, string $case) : void { + if (!$passed) { + throw new \RuntimeException('Script Server log masking probe failed: ' . $case); + } +} + +function ss_cov_log() : string { + $log = implode("\n", $GLOBALS['ss_cov_log']); + $GLOBALS['ss_cov_log'] = []; + + return $log; +} + +foreach (['cacti_sizeof', 'cacti_count', 'prepare_validate_result', 'is_hexadecimal', 'strip_alpha'] as $function) { + cacti_fixture_source_function($root . '/lib/functions.php', $function, __NAMESPACE__); +} + +foreach (['parseArgs', 'script_server_log_parse_failure', 'script_server_log_missing_function', 'script_server_call', 'script_server_response'] as $function) { + cacti_fixture_source_function($root . '/script_server.php', $function, __NAMESPACE__); +} + +foreach (['script_server_redact_params', 'poller_redact_snmp_secrets', 'exec_poll', 'exec_with_timeout'] as $function) { + cacti_fixture_source_function($root . '/lib/poller.php', $function, __NAMESPACE__); +} + +foreach (['collect_device_data', 'ping_and_reindex_check'] as $function) { + cacti_fixture_source_function($root . '/cmd.php', $function, __NAMESPACE__); +} + +// script_server_call(): printed output is discarded and only its size logged +ob_start(); +$result = script_server_call(__NAMESPACE__ . '\\ss_cov_echo', 'c0mmunity', ['c0mmunity']); +$printed = ob_get_clean(); +$log = ss_cov_log(); +ss_cov_check($printed === '' && $result === 'value:c0mmunity', 'printed output discarded'); +ss_cov_check(str_contains($log, 'wrote 20 bytes of output, discarded') && !str_contains($log, 'c0mmunity'), 'stray output logged by size'); + +$result = script_server_call(__NAMESPACE__ . '\\ss_cov_quiet', '', []); +ss_cov_check($result === '7' && ss_cov_log() === '', 'quiet function logs nothing'); + +// script_server_response(): one line per reply +ss_cov_check(script_server_response(script_server_call(__NAMESPACE__ . '\\ss_cov_multiline', '', [])) === 'a:1 b:2 c:3', 'multipart reply on one line'); + +// parseArgs(): a parse error is printed only when debugging +$parsed = []; +ob_start(); +$ok = parseArgs("'host1 'c0mmunity'", $parsed); +$printed = ob_get_clean(); +ss_cov_check($ok === false && $printed === '', 'parse error silent without debug'); + +ob_start(); +parseArgs("'host1 'c0mmunity'", $parsed, true); +$printed = ob_get_clean(); +ss_cov_check(str_contains($printed, 'ERROR: '), 'parse error printed when debugging'); + +// the parse failure and missing function warnings never log a credential +script_server_log_parse_failure('ss_cov_quiet', "'host1 'c0mmunity'"); +$log = ss_cov_log(); +ss_cov_check(str_contains($log, '18 byte argument list') && !str_contains($log, 'c0mmunity'), 'parse failure logged by size'); + +script_server_log_missing_function('/x/ss_cov.php', 'ss_cov_missing', ['host1', 'c0mmunity', '3:161:500:1:10::user:authpass:SHA']); +$log = ss_cov_log(); +ss_cov_check(str_contains($log, "PARMS: 'host1', '********', '3:161:500:1:10::user:********:SHA'"), 'missing function arguments masked'); + +// poller_redact_snmp_secrets(): every escaped form, longest credential first +$item = ['snmp_community' => 'pub', 'snmp_password' => "pubp'ass\"x", 'snmp_priv_passphrase' => '']; +ss_cov_check(poller_redact_snmp_secrets("f 'pub' 'pubp'\\''ass\"x' \"pubp'ass\\\"x\" pubp'assx", $item) === "f '********' '********' \"********\" ********", 'escaped forms masked'); +ss_cov_check(poller_redact_snmp_secrets('no secrets here', ['snmp_community' => '']) === 'no secrets here', 'no credentials leaves the string'); + +// exec_poll(): a failing script is logged with the device credentials masked, +// and its first line of output is the result +$failing = PHP_BINARY . ' -r ' . escapeshellarg('fwrite(STDOUT, "out " . $argv[1] . "\n"); fwrite(STDERR, "err " . $argv[1] . "\n"); exit(3);') . ' ' . escapeshellarg('c0mmunity'); +ss_cov_check(exec_poll($failing, 5, ['snmp_community' => 'c0mmunity']) === 'out c0mmunity', 'failing script first line'); +$log = ss_cov_log(); +ss_cov_check(str_contains($log, 'ErrorCode:3') && str_contains($log, 'exited with code 3') && !str_contains($log, 'c0mmunity'), 'failing script log masked'); +ss_cov_check(exec_poll(PHP_BINARY . ' -r ' . escapeshellarg('print "7\n";'), 5) === '7', 'newline terminated output'); + +// cmd.php data source and recache logs mask the device credentials +$GLOBALS['print_data_to_stdout'] = false; +$GLOBALS['using_proc_function'] = true; +$GLOBALS['pipes'] = []; +$GLOBALS['cactiphp'] = null; +$GLOBALS['poller_id'] = 1; +$GLOBALS['set_spike_kill'] = false; + +$args = " 'c0mmunity' 'authpass'"; + +foreach ([POLLER_ACTION_SCRIPT, POLLER_ACTION_SCRIPT_PHP] as $action) { + foreach (['U', 'not a number', '42'] as $reply) { + $GLOBALS['cmd_device_reply'] = $reply; + + // the script runs for real; the Script Server reply is canned + $script = PHP_BINARY . ' -r ' . escapeshellarg('print "' . $reply . '\n";') . ' /x/ss_cov.php ss_cov'; + + $item = [ + 'local_data_id' => 3, + 'host_id' => 7, + 'action' => $action, + 'snmp_community' => 'c0mmunity', + 'snmp_password' => 'authpass', + 'snmp_priv_passphrase' => '', + 'arg1' => $script . $args, + ]; + $error_ds = []; + + collect_device_data($item, $error_ds, 25); + + $log = ss_cov_log(); + ss_cov_check(!str_contains($log, 'c0mmunity') && !str_contains($log, 'authpass') && substr_count($log, '********') === ($reply === '42' ? 2 : 4), "data source log masked for action $action reply $reply"); + } +} + +$GLOBALS['cmd_device_reply'] = '42'; +$script = PHP_BINARY . ' -r ' . escapeshellarg('print "42\n";') . ' /x/ss_q.php ss_q'; + +foreach ([POLLER_ACTION_SNMP, POLLER_ACTION_SCRIPT, POLLER_ACTION_SCRIPT_PHP, POLLER_ACTION_SNMP_COUNT, POLLER_ACTION_SCRIPT_COUNT, POLLER_ACTION_SCRIPT_PHP_COUNT] as $action) { + $GLOBALS['cmd_device_reindex'][] = ['data_query_id' => $action, 'action' => $action, 'op' => '=', 'assert_value' => '42', 'arg1' => $script . $args]; +} + +$item = ['host_id' => 7, 'hostname' => 'host1', 'snmp_community' => 'c0mmunity', 'snmp_password' => 'authpass', 'snmp_priv_passphrase' => '']; +ss_cov_check(ping_and_reindex_check($item, false, 25) === false, 'device reported up'); + +$lines = array_values(array_filter($GLOBALS['ss_cov_log'], function ($line) { + return str_contains($line, 'ss_q.php'); +})); +$log = implode("\n", $lines); +ss_cov_check(count($lines) === 6 && !str_contains($log, 'c0mmunity') && !str_contains($log, 'authpass') && substr_count($log, '********') === 12, 'recache logs masked'); + +print "PASS: Script Server replies stay on one line and logged arguments mask device credentials\n"; diff --git a/tests/tools/run_request_coverage.sh b/tests/tools/run_request_coverage.sh index f28c226b04..3af03ee14c 100644 --- a/tests/tools/run_request_coverage.sh +++ b/tests/tools/run_request_coverage.sh @@ -48,6 +48,8 @@ run_php_probe tests/fixtures/SnmpAgentGlobalSettingsCoverage.php '^(lib/snmpagen run_php_probe tests/fixtures/CmdBoostFlushRedirectCoverage.php '^(cmd\.php|tests/fixtures/CmdBoostFlushRedirectCoverage\.php)' +run_php_probe tests/fixtures/ScriptServerLogMaskingCoverage.php '^(cmd\.php|script_server\.php|lib/poller\.php|tests/fixtures/ScriptServerLogMaskingCoverage\.php)' + run_php_probe tests/fixtures/UserAdministrationAuditCoverage.php '^(user_admin\.php|lib/functions\.php|tests/fixtures/UserAdministrationAudit)' run_php_probe tests/fixtures/Core/GraphViewCrossFilterCoverage.php '^(lib/html\.php|lib/html_graph\.php|tests/fixtures/Core/GraphViewCrossFilterCoverage\.php)' diff --git a/tests/tools/test_request_coverage_dispatch.py b/tests/tools/test_request_coverage_dispatch.py index 80c20e7015..d70f6213ec 100644 --- a/tests/tools/test_request_coverage_dispatch.py +++ b/tests/tools/test_request_coverage_dispatch.py @@ -45,6 +45,11 @@ class RequestDispatchTest(unittest.TestCase): def test_auth_change_runs_the_native_auth_probe(self): self.dispatch('lib/auth.php', 'BoundaryContracts.php') + def test_script_server_change_runs_the_log_masking_probe(self): + for path in ['script_server.php', 'lib/poller.php', 'tests/fixtures/ScriptServerLogMaskingCoverage.php']: + with self.subTest(path=path): + self.dispatch(path, 'ScriptServerLogMaskingCoverage.php') + def test_two_factor_change_runs_the_guard_fixture(self): self.dispatch('auth_2fa.php', 'ConstantTimeGuardMatrix.php') @@ -84,7 +89,7 @@ class RequestDispatchTest(unittest.TestCase): 'UserAdministrationAuditCoverage.php', 'Core/ScriptSubstitutionMatrix.php', 'Core/ConstantTimeGuardMatrix.php', 'Core/PackageManifestMatrix.php', 'Core/PackageSaveMatrix.php', 'Core/PackageArchive.php', - 'Installer/RetiredThemeCleanup.php']: + 'Installer/RetiredThemeCleanup.php', 'ScriptServerLogMaskingCoverage.php']: path = repository / 'tests/fixtures' / script path.parent.mkdir(parents=True, exist_ok=True) path.write_text('