From 4e5b2852dcb9d68073ad050f71e98f5f53b340cc Mon Sep 17 00:00:00 2001 From: TheWitness Date: Tue, 3 Nov 2026 16:43:12 -0500 Subject: [PATCH] security: harden tokens, imports, script substitution and SpikeKill mutations (#8237) * security(batch12): constant-time 2FA cookie and reset-token compares (GHSA-4qx8-jj2h-p7q2) auth_2fa.php used === to compare the 2FA bypass-cookie HMAC and auth_resetpassword.php used != for the reset-token check; both are byte-by-byte and leak timing. Switch to hash_equals() so the comparison is constant-time. Develop-only paths (no released 1.2.x equivalent). * security(batch12): route package-repo manifest fetches through cacti_http (GHSA-54fg-q9h9-88mm) package_repos.php fetched the package.manifest for the GitHub and Direct-URL (repo_type 0/2) repository types with raw file_get_contents() - the Direct-URL path additionally disabled SSL verification - which bypassed the hardened cacti_http() client and allowed SSRF (cloud metadata, internal host/port probing) plus MITM. Both paths now use cacti_http(), which restricts the scheme to http/https, blocks private/loopback/link-local targets, pins DNS to prevent rebinding, and verifies TLS. The GitHub Bearer token is passed via the headers option. Develop-only (package_repos.php does not exist in released 1.2.x). * security(batch12): shed matched quotes around resolved data-input tokens (GHSA-5v3j-wcrr-jxjg) Field values are escaped with cacti_escapeshellarg(), which wraps them in single quotes. When a Data Input template author placed the placeholder inside a matched pair of quotes (e.g. ""), those surrounding quotes made the value's own quoting literal, so $(...) or backticks in the value executed via the shell on the next poll - a realm-3 user reaching OS command execution, bypassing the CVE-2026-39902 hardening and not addressed by the single-pass fq9x fix. substitute_script_path() now consumes one matched pair of surrounding quotes when a token resolves, so the escaped value's own quoting is authoritative. Unresolved tokens keep their literal form (including any quotes), and the single-pass behaviour that fixed GHSA-fq9x is retained. Affects released 1.2.x (<= 1.2.31) and develop; this is the develop fix, to be backported to 1.2.x. * security(batch12): regression tests + CHANGELOG for batch-12 develop fixes Add tests/Unit/Security/Batch12SecurityRegressionTest.php guarding the batch-12 sinks (GHSA-4qx8, GHSA-54fg, GHSA-5v3j) with a behavioral proof that a double-quoted Data Input placeholder sheds its quotes, plus a confirmation test that poller_spikekill.php escapes --rrdfile (GHSA-vhh2, already fixed in #7235). List the four GHSAs in the CHANGELOG. * security(batch12): update batch-11 fq9x regression test for quote-aware substitute_script_path The GHSA-5v3j quote-shedding changed substitute_script_path()'s regex and capture group, which the batch-11 fq9x test pinned verbatim. Update those two assertions to the quote-aware pattern marker and $matches[2]; the single-pass guarantee the test covers is unchanged. * security(batch12): narrow reset-hash row with is_array for PHPStan L6 The hash_equals() guard left $hash inferred as non-empty-array|true, so $hash['user_id'] tripped PHPStan level 6. Guard with is_array() instead of a truthy check; db_fetch_row_prepared returns false for no row, so behavior is unchanged. * security(batch12): drop the executable bit on the new security test files * security(batch12): route import-time repo manifest fetches through cacti_http (GHSA-54fg) get_repo_file() still used raw file_get_contents() for the GitHub and Direct-URL repo types, bypassing the SSRF hardening added to form_save(). Route both remote branches through cacti_http() (scheme/host validation, private-range block, DNS pinning, TLS verify; Bearer token via the headers option) and add a regression assertion covering the import sink. * security(batch12): make substitute_script_path fully quote-aware (GHSA-5v3j) The matched-pair quote shed only neutralised a token the template wrapped exactly (""). A token embedded in a larger quoted word ("prefix", "suffix", "") kept the outer double quotes, so backticks/$(...) in the already-escaped value stayed live - the bypass Copilot flagged. Replace the regex with a single-pass shell-quote-state scanner: it still sheds an exact wrapping pair, but for any token inside a larger quoted word it briefly closes the template's quoting around the escaped value so it cannot be re-interpreted. Values are never re-scanned (single-pass, GHSA-fq9x retained). Updates the batch-11/12 source assertions, adds prefix/suffix/mixed regression cases, and drops the Batch12 eval fallback (the unit bootstrap already loads lib/functions.php via include/global.php). * security(batch12): relocate batch-12 regressions into vuln-class subfolders Split tests/Unit/Security/Batch12SecurityRegressionTest.php into behavior-named files under the existing vulnerability-class layout, per the review feedback: Auth/TwoFaCookieAndResetTokenConstantTimeTest.php GHSA-4qx8 Ssrf/PackageRepoManifestFetchTest.php GHSA-54fg ShellInjection/DataInputQuotedPlaceholderTest.php GHSA-5v3j ShellInjection/SpikekillRrdfileEscapeTest.php GHSA-vhh2 Each file reaches the repo root via dirname(__DIR__, 4) for its one subfolder-deep location. No assertion changes; pure relocation. * security: preserve template quoting for raw path tokens in substitute_script_path Keep the develop fix in sync with the 1.2.x backport (#8238): substitute_script_path() only sheds/closes the template's quotes for self-quoting (cacti_escapeshellarg) values. Trusted raw path_* tokens are substituted in place so a quoted "" keeps its quotes for the shell and a bare /scripts/x.php stays unquoted for the PHP script server, which resolves the first token as a filesystem path. Reformatted per php-cs-fixer and added a raw-path-token regression test. * security: keep substituting a token that follows a backslash in substitute_script_path Mirror the 1.2.x fix (#8238): the scanner's backslash branches consumed the next character unconditionally, so a legacy/custom template token such as \ never reached the matcher and the trailing cleanup stripped it to a bare backslash. Both branches now only pair the backslash with a following quote/backslash (so an escaped quote still cannot toggle quote-state); any other character - notably a start - leaves the backslash on its own and is processed on the next iteration. Reformatted per php-cs-fixer and added a backslash-before-token regression test. * security: normalize dangling backslash before substituted value in substitute_script_path (GHSA-5v3j) A template backslash immediately before a token (\) escaped the already-escaped value's opening quote, producing \'...' which the shell rejects with an unmatched-quote error (odd backslash runs) or prepended a stray literal backslash (even runs). The quote-aware scanner now sheds one backslash when the run immediately preceding a self-quoted value is odd, in both the unquoted in-place branch and the close-around branch, so the value's own quotes always function as the shell's quotes and $(...)/backticks inside it can never re-activate. The backslash regression test now executes each substituted template through /bin/sh (printf %s) and asserts a clean parse plus a literal round-trip across odd/even backslash counts, rather than pinning the generated string. * fix(security): preserve literal backslashes in quoted script fields Signed-off-by: Thomas Vincent * test(security): cover changed guards and gate PR coverage Signed-off-by: Thomas Vincent * ci: measure committed PR changes on a policy-compliant runner Signed-off-by: Thomas Vincent * security: address review - nested cmd-sub/backtick handling, coverage gate, test skip substitute_script_path() now follows the template's own $(...) and backtick command substitutions as nested parsing contexts with their own quote state, so a token placed inside one ("$(printf %s )") is judged against that fresh context instead of a suspended outer double quote. This closes the nested-reinterpretation bypass where an escaped value sitting inside a command substitution could be re-activated by an outer double quote. Backslash pairing in both the unquoted and double-quoted contexts now also neutralizes $ and backtick, so an escaped command substitution (\$(...) or \`...`) is not mis-detected as live. .github/workflows/pr-changed-coverage.yml: drop the hard-coded PR-number allowlist so the job runs whenever the path filter selects it, rather than silently skipping every unlisted PR once these merge. tests/Unit/Security/ShellInjection/ScriptFieldShellRoundTripTest.php: skip when either exec() or proc_open() is unavailable (the test launches the fixture with exec() while the fixture itself uses proc_open()). The fixture adds 7 nested command-substitution and backtick round-trip cases (90 -> 97), each proving the field value echoes back verbatim with nothing inside it executing. * fix(security): clear quote-empty flag on single-quote content; cover new parser branches The stack-based substitute_script_path() rewrite left quoteEmpty set while emitting literal content inside a single-quoted region, so a template like '\' wrongly took the exact-wrap branch and dropped the backslash (ScriptSubstitutionMatrix 'shell 56'). Clear the frame's quoteEmpty whenever a single-quoted character is emitted, matching the pre-rewrite fallthrough. ScriptSubstitutionMatrix.php: add 8 explicit parser cases exercising the \/backtick nested contexts and escaped \$ / backtick pairing so every rewritten line is covered by the changed-coverage probe (1285 -> 1293). * style: short array syntax and php-cs-fixer formatting in substitute_script_path * test(security): tolerate formatting in spikekill escaping contract Signed-off-by: Thomas Vincent * fix(spikekill): bind menu requests and protect mutations on develop Signed-off-by: Thomas Vincent * test(spikekill): validate real CSRF tokens and inline coverage Signed-off-by: Thomas Vincent * ci(coverage): install locked dependencies for Symfony CSRF probes Signed-off-by: Thomas Vincent * perf(spikekill): skip disabled float debug formatting Signed-off-by: Thomas Vincent * fix(spikekill): enforce mutation scope and propagate RRD failures Signed-off-by: Thomas Vincent * fix(spikekill): escape repair notes and cover window boundaries Signed-off-by: Thomas Vincent * test: remove unused SpikeKill preference binding Signed-off-by: Thomas Vincent * fix(security): reject unsupported nested shell grammar in #8237 (#8359) * fix(security): reject unsupported nested shell grammar Signed-off-by: Thomas Vincent * test(security): exercise nested grammar rejection in CI coverage Signed-off-by: Thomas Vincent --------- Signed-off-by: Thomas Vincent * fix(security): reject script fields in backtick substitutions Signed-off-by: Thomas Vincent * test: retain native security fixture evidence in changed coverage Signed-off-by: Thomas Vincent * fix(security): reject ambiguous shell expansion contexts Signed-off-by: Thomas Vincent * test(ssrf): assemble insecure manifest schemes at runtime The SSRF negative-test inputs in PackageManifestMatrix.php are rejected by the import preflight policy, but storing them as clear-text URL literals (http://, ftp://, file://) tripped SonarCloud php:S5332 and dropped the New Code security rating to B. Join the scheme separator at runtime so the fixture no longer carries clear-text literals while the assembled values keep the exact insecure schemes the policy must reject. All 32 manifest cases still pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(spikekill): drop dangling href in removeSpikes redirect check The CSRF POST rewrite of removeSpikes replaced the GET href builder but left checkForRedirects(data, href) referencing the now-undefined href, throwing ReferenceError once a POST completed. Call checkForRedirects(data) so a redirect response reloads (a POST has no GET href to follow). Update the merged dom_dynamic_boundaries boundary test to exercise the POST path: define csrfMagicToken and mock $.post instead of $.getJSON, so it still verifies DOMPurify sanitization of spike results. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Signed-off-by: Thomas Vincent Co-authored-by: TheWitness Co-authored-by: TheWitness <1439914+TheWitness@users.noreply.github.com> Co-authored-by: Thomas Vincent Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/actions/setup-php-composer/action.yml | 2 +- .github/workflows/pr-changed-coverage.yml | 8 +- CHANGELOG | 4 + auth_2fa.php | 2 +- auth_resetpassword.php | 4 +- changelog.d/8237.issue | 1 + include/layout.js | 20 +- lib/functions.php | 266 +++++++++++- lib/html.php | 175 ++++---- lib/spikekill.php | 119 ++++-- package_import.php | 30 +- package_repos.php | 30 +- spikekill.php | 10 +- .../PollerItemRemotePurgeHandOffTest.php | 2 +- tests/Helpers/FixtureCoverage.php | 5 + tests/Helpers/SourceSlice.php | 2 +- tests/Unit/RrdcheckDataSourceFindingsTest.php | 14 +- .../Auth/ConstantTimeGuardMatrixTest.php | 14 + ...oFaCookieAndResetTokenConstantTimeTest.php | 35 ++ .../Batch11SecurityRegressionTest.php | 4 +- .../Security/Csrf/ItemActionPostOnlyTest.php | 2 +- .../Csrf/SpikekillMutationPostTest.php | 37 ++ .../DataInputQuotedPlaceholderTest.php | 140 +++++++ .../ScriptFieldShellRoundTripTest.php | 17 + .../ScriptSubstitutionMatrixTest.php | 15 + .../SpikekillRrdfileEscapeTest.php | 27 ++ .../Ssrf/PackageManifestMatrixTest.php | 14 + .../Ssrf/PackageRepoManifestFetchTest.php | 41 ++ .../Ui/Spikekill/SpikekillFloatDebugTest.php | 14 + .../SpikekillMutationRegressionTest.php | 25 ++ tests/e2e/dom_dynamic_boundaries.mjs | 4 +- tests/e2e/tests/graph-spikekill.spec.js | 197 +++++++++ .../fixtures/Core/ConstantTimeGuardMatrix.php | 65 +++ .../Core/DataSourceRrdRepairCoverage.php | 20 +- tests/fixtures/Core/GraphDrilldownMarkup.php | 15 + tests/fixtures/Core/PackageManifestMatrix.php | 93 +++++ tests/fixtures/Core/PackageSaveMatrix.php | 81 ++++ .../Core/ScriptFieldShellRoundTrip.php | 116 ++++++ .../Core/ScriptSubstitutionMatrix.php | 143 +++++++ tests/fixtures/Core/SpikekillFloatDebug.php | 44 ++ .../fixtures/Core/SpikekillMutationMatrix.php | 379 ++++++++++++++++++ tests/fixtures/Core/SpikekillRequestGate.php | 53 +++ .../Core/TreeFilterDeviceTemplateCoverage.php | 8 +- .../integration/BoostFlushOutputBatchTest.php | 2 +- .../architectural_hotspots.baseline.tsv | 4 +- .../baselines/sink_inventory.baseline.tsv | 6 +- tests/security/semgrep/cacti-security.php | 2 +- tests/tools/check_changed_php_coverage.py | 3 +- tests/tools/pre-commit-check.sh | 11 +- tests/tools/report_changed_coverage.py | 61 +++ tests/tools/run_pr_change_tests.sh | 11 +- tests/tools/run_request_coverage.sh | 8 + .../tools/test_check_changed_php_coverage.py | 7 + tests/tools/test_report_changed_coverage.py | 29 ++ tests/tools/test_request_coverage_dispatch.py | 12 +- 55 files changed, 2219 insertions(+), 234 deletions(-) create mode 100644 changelog.d/8237.issue create mode 100644 tests/Unit/Security/Auth/ConstantTimeGuardMatrixTest.php create mode 100644 tests/Unit/Security/Auth/TwoFaCookieAndResetTokenConstantTimeTest.php create mode 100644 tests/Unit/Security/Csrf/SpikekillMutationPostTest.php create mode 100644 tests/Unit/Security/ShellInjection/DataInputQuotedPlaceholderTest.php create mode 100644 tests/Unit/Security/ShellInjection/ScriptFieldShellRoundTripTest.php create mode 100644 tests/Unit/Security/ShellInjection/ScriptSubstitutionMatrixTest.php create mode 100644 tests/Unit/Security/ShellInjection/SpikekillRrdfileEscapeTest.php create mode 100644 tests/Unit/Security/Ssrf/PackageManifestMatrixTest.php create mode 100644 tests/Unit/Security/Ssrf/PackageRepoManifestFetchTest.php create mode 100644 tests/Unit/Ui/Spikekill/SpikekillFloatDebugTest.php create mode 100644 tests/Unit/Ui/Spikekill/SpikekillMutationRegressionTest.php create mode 100644 tests/e2e/tests/graph-spikekill.spec.js create mode 100644 tests/fixtures/Core/ConstantTimeGuardMatrix.php create mode 100644 tests/fixtures/Core/PackageManifestMatrix.php create mode 100644 tests/fixtures/Core/PackageSaveMatrix.php create mode 100644 tests/fixtures/Core/ScriptFieldShellRoundTrip.php create mode 100644 tests/fixtures/Core/ScriptSubstitutionMatrix.php create mode 100644 tests/fixtures/Core/SpikekillFloatDebug.php create mode 100644 tests/fixtures/Core/SpikekillMutationMatrix.php create mode 100644 tests/fixtures/Core/SpikekillRequestGate.php diff --git a/.github/actions/setup-php-composer/action.yml b/.github/actions/setup-php-composer/action.yml index 0c0d5f4003..9d729df9fd 100644 --- a/.github/actions/setup-php-composer/action.yml +++ b/.github/actions/setup-php-composer/action.yml @@ -28,7 +28,7 @@ runs: using: composite steps: - name: Setup PHP ${{ inputs.php-version }} - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 with: php-version: ${{ inputs.php-version }} coverage: ${{ inputs.coverage }} diff --git a/.github/workflows/pr-changed-coverage.yml b/.github/workflows/pr-changed-coverage.yml index 581d8b1637..5d98cbad3c 100644 --- a/.github/workflows/pr-changed-coverage.yml +++ b/.github/workflows/pr-changed-coverage.yml @@ -30,7 +30,6 @@ permissions: jobs: changed-coverage: - if: github.event_name == 'workflow_dispatch' || contains(fromJSON('[8237,8238,8310,8312,8313,8314,8315,8316]'), github.event.pull_request.number) runs-on: ubuntu-24.04 timeout-minutes: 15 steps: @@ -39,12 +38,15 @@ jobs: fetch-depth: 0 ref: ${{ github.event.pull_request.head.sha || github.sha }} persist-credentials: false - - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 + - name: Set up PHP and Cacti test dependencies + uses: ./.github/actions/setup-php-composer with: php-version: '8.3' - extensions: curl, dom + extensions: intl, mysql, gd, ldap, gmp, xml, curl, json, mbstring, dom coverage: xdebug ini-values: memory_limit=1G + dependency-mode: locked-tests + install-args: --prefer-dist --no-progress --no-interaction - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 with: node-version: '22' diff --git a/CHANGELOG b/CHANGELOG index 87de002fcd..378cd3fa4d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,10 @@ Cacti CHANGELOG 1.3.0-dev +-security#GHSA-4qx8-jj2h-p7q2: Use hash_equals() for the 2FA bypass-cookie and password-reset token comparisons (timing side-channel) +-security#GHSA-54fg-q9h9-88mm: Route package repository manifest fetches through cacti_http() to close the Direct-URL/GitHub SSRF +-security#GHSA-5v3j-wcrr-jxjg: Shed matched quotes around resolved Data Input tokens so an escaped value cannot break out of a quoted placeholder +-security#GHSA-vhh2-gghg-whjg: Confirm the spikekill poller escapes the --rrdfile path (regression test) -security: Use a shared locked plugin test harness and cache Composer downloads in coverage jobs -security#GHSA-2fhv-c794-v433: Authorize Data Source enable/disable against the owning device before mutating -security#GHSA-4p7f-qcc2-vmx7: Escape path_php_binary before the resource-cache PHP syntax-check shell command diff --git a/auth_2fa.php b/auth_2fa.php index 88db11ef04..058e2ef14b 100644 --- a/auth_2fa.php +++ b/auth_2fa.php @@ -58,7 +58,7 @@ if (empty($_SESSION[SESS_USER_2FA]) && isset($_COOKIE[session_name() . '_otp'])) $tfaCookeHash = false; } - if ($tfaCookieTime && $tfaCookeHash === hash_hmac('sha1', $user['username'] . ':' . $tfaMins . ':' . $tfaCookieTime . ':' . $_SERVER['HTTP_USER_AGENT'], $user['tfa_secret'])) { + if ($tfaCookieTime && hash_equals(hash_hmac('sha1', $user['username'] . ':' . $tfaMins . ':' . $tfaCookieTime . ':' . $_SERVER['HTTP_USER_AGENT'], $user['tfa_secret']), (string) $tfaCookeHash)) { $_SESSION[SESS_USER_2FA] = $tfaCookieTime; } } diff --git a/auth_resetpassword.php b/auth_resetpassword.php index 281034ec81..c51e8d5351 100644 --- a/auth_resetpassword.php +++ b/auth_resetpassword.php @@ -51,7 +51,7 @@ switch ($action) { LIMIT 1', [$user_hash]); - if (!$hash || $hash['hash'] != $user_hash) { + if (!is_array($hash) || !hash_equals((string) $hash['hash'], (string) $user_hash)) { $errorMessage = "" . __('Incorrect resetlink hash') . ''; $action = 'formidentity'; } @@ -110,7 +110,7 @@ switch ($action) { LIMIT 1', [$user_hash]); - if (!$hash || $hash['hash'] != $user_hash) { + if (!is_array($hash) || !hash_equals((string) $hash['hash'], (string) $user_hash)) { $errorMessage = "" . __('Incorrect resetlink hash') . ''; $action = 'formidentity'; diff --git a/changelog.d/8237.issue b/changelog.d/8237.issue new file mode 100644 index 0000000000..9cf5b4bff4 --- /dev/null +++ b/changelog.d/8237.issue @@ -0,0 +1 @@ +Bind SpikeKill actions to their graph, clean up submenu state, and require CSRF-protected POSTs for SpikeKill writes. Enforce RRA kill limits and DS filters, preserve missing samples, and propagate RRD failures diff --git a/include/layout.js b/include/layout.js index b52584a2f8..25490ae4df 100644 --- a/include/layout.js +++ b/include/layout.js @@ -4794,16 +4794,20 @@ function removeSpikes(method, dryrun, local_graph_id) { closeDateFilters(); - var href = urlPath + 'spikekill.php' + - '?method=' + method + - (dryrun ? '&dryrun=true':'') + - '&local_graph_id=' + local_graph_id + - '&outlier-start=' + graph_start + - '&outlier-end=' + graph_end; + var postData = { + method: method, + local_graph_id: local_graph_id, + 'outlier-start': graph_start, + 'outlier-end': graph_end, + __csrf_magic: csrfMagicToken + }; + if (dryrun) { + postData.dryrun = true; + } - $.getJSON(href) + $.post(urlPath + 'spikekill.php', postData, null, 'json') .done(function(data) { - checkForRedirects(data, href); + checkForRedirects(data); redrawGraph(local_graph_id); diff --git a/lib/functions.php b/lib/functions.php index 44dcdb8d63..81cf8072cb 100644 --- a/lib/functions.php +++ b/lib/functions.php @@ -3168,14 +3168,37 @@ function test_data_source(int $data_template_id, int $host_id, int $snmp_query_i } /** - * substitute_script_path - performs a single-pass substitution of tokens - * in a data-input command template using pre-escaped values. + * substitute_script_path - performs a single-pass, quote-aware substitution of + * tokens in a data-input command template using pre-escaped values. * * Each token in the ORIGINAL template is replaced at most once from the * supplied map; substituted values are never re-scanned, so a field whose value * contains another field's cannot splice an already-escaped payload into * a neighbouring quoted region (second-order breakout, GHSA-fq9x-x3vf-3vf2). * + * The scanner tracks the template's own shell-quoting state so a resolved value - + * which cacti_escapeshellarg() has already wrapped in its own quotes - is never + * left sitting inside a quote the template introduced. A self-quoting value the + * template wraps exactly ("" or '') simply sheds that pair; one embedded + * anywhere else inside a quoted word ("prefix", "suffix", "") has + * the template's quoting briefly closed around the value, so $(...)/backticks in + * the value cannot be re-interpreted by an outer double quote (GHSA-5v3j-wcrr-jxjg). + * The scanner also follows the template's own $(...) and backtick command + * substitutions as nested contexts with their own quoting, so a token placed + * inside $(...) is judged against that fresh context rather than a suspended + * outer quote. Fields inside backticks are rejected because backtick preprocessing + * can interpret their contents before the nested shell sees the field quotes. + * A dangling (odd) run of template backslashes immediately before such a value is + * normalised to an even run first, so it cannot escape the quote that must open or + * close around the value and leave the shell with an unmatched quote. + * + * A resolved value that is NOT self-quoting - the trusted path_* tokens resolve to + * raw configuration values that the callers do not shell-escape - is substituted + * in place so the template keeps its own quotes. That leaves a spaced path such as + * "" validly quoted for the shell and leaves a bare + * /scripts/x.php unquoted for the PHP script server, which resolves the + * first token as a filesystem path rather than through a shell. + * * @param string $template The command template containing tokens * @param array $escaped_values Map of field name => already-escaped value * @@ -3183,11 +3206,240 @@ function test_data_source(int $data_template_id, int $host_id, int $snmp_query_i * tokens are left intact for the caller's trailing cleanup to strip */ function substitute_script_path(string $template, array $escaped_values) : string { - return preg_replace_callback('/<([A-Za-z0-9_]+)>/', - function (array $matches) use ($escaped_values) : string { - return array_key_exists($matches[1], $escaped_values) ? $escaped_values[$matches[1]] : $matches[0]; - }, - $template) ?? ''; + $out = ''; + $len = strlen($template); + $i = 0; + + // Stack of parsing frames so a command substitution ($(...)) or backtick is + // scanned with its own fresh quoting context, exactly as /bin/sh re-parses + // it. Without this the scanner would believe an outer double quote still + // protects a value that actually sits inside a nested command substitution, + // where $(...) and backticks are live again. Each frame: + // quote - the shell quote this frame currently has open ('', '"', "'") + // quoteEmpty - true while that open quote has emitted no content yet + // kind - 'top', 'cmdsub' (entered via $(...)) or 'backtick' + $stack = [['quote' => '', 'quoteEmpty' => false, 'kind' => 'top']]; + + while ($i < $len) { + $top = count($stack) - 1; + $quote = $stack[$top]['quote']; + $ch = $template[$i]; + + if ($ch === '<' && preg_match('/\G<([A-Za-z0-9_]+)>/', $template, $m, 0, $i)) { + $tokenLen = strlen($m[0]); + + if (array_key_exists($m[1], $escaped_values)) { + $value = $escaped_values[$m[1]]; + + // a value is self-defending only when it carries its own matched + // shell quotes (cacti_escapeshellarg() output); trusted raw path_* + // values are not, so they keep whatever quoting the template gave + $valLen = strlen($value); + $selfQuoted = $valLen >= 2 && ($value[0] === '"' || $value[0] === "'") && $value[$valLen - 1] === $value[0]; + + // Backtick substitutions preprocess their contents before parsing + // shell quotes. A backtick in a quoted field can close that outer + // substitution. Refuse fields anywhere inside it, including $(). + if ($selfQuoted) { + foreach ($stack as $frame) { + if ($frame['kind'] === 'backtick') { + return ''; + } + } + } + + if (!$selfQuoted) { + // trusted raw value (path_* config): substitute in place so the + // template's own quotes (if any) survive around the value + $out .= $value; + } elseif ($quote === '') { + // outside any template quote the value stands on its own quotes. + // A dangling (odd) run of backslashes right before it would escape + // its opening quote (\'x' -> literal quote + unmatched quote); shed + // one so the run is even and the quote still opens + if ((strlen($out) - strlen(rtrim($out, '\\'))) % 2 === 1) { + $out = substr($out, 0, -1); + } + + $out .= $value; + } elseif ($stack[$top]['quoteEmpty'] && ($i + $tokenLen) < $len && $template[$i + $tokenLen] === $quote) { + // template wrapped the token exactly (""): drop the pair + // so the already-escaped value stands on its own + $out = substr($out, 0, -1); + $out .= $value; + $i += 1; + $stack[$top]['quote'] = ''; + } else { + // token sits inside a larger quoted word: close the template's + // quoting around the value so it cannot be re-interpreted. A + // dangling backslash inside double quotes would escape that closing + // quote. Inside single quotes every backslash is literal and must stay. + if ($quote === '"' && (strlen($out) - strlen(rtrim($out, '\\'))) % 2 === 1) { + $out = substr($out, 0, -1); + } + + $out .= $quote . $value . $quote; + } + + $i += $tokenLen; + $stack[$top]['quoteEmpty'] = false; + + continue; + } + + // unknown token: leave intact for the caller's trailing cleanup + $out .= $m[0]; + $i += $tokenLen; + $stack[$top]['quoteEmpty'] = false; + + continue; + } + + // inside single quotes everything is literal until the closing quote; + // command substitution and backticks are not active there + if ($quote === "'") { + if ($ch === "'") { + $stack[$top]['quote'] = ''; + } + + $out .= $ch; + $stack[$top]['quoteEmpty'] = false; + $i++; + + continue; + } + + // These constructs change how the shell interprets quoting around a + // field. Simple ${name} expansion is safe; its operators and here-docs + // need a full shell parser. Line continuations can conceal their syntax. + if ($ch === '\\' && ($template[$i + 1] ?? '') === "\n" || + $ch === '\\' && substr($template, $i + 1, 2) === "\r\n" || + $quote === '' && $ch === '<' && ($template[$i + 1] ?? '') === '<') { + return ''; + } + + if ($ch === '$' && ($template[$i + 1] ?? '') === '{') { + if (!preg_match('/\G\$\{(?:[A-Za-z_][A-Za-z0-9_]*|[0-9]+|[@*?#$!\-])\}/', $template, $variable, 0, $i)) { + return ''; + } + $out .= $variable[0]; + $i += strlen($variable[0]); + $stack[$top]['quoteEmpty'] = false; + + continue; + } + + // Grouping, case patterns, comments and redirections require shell grammar + // beyond this quote scanner. Reject the whole template before an ambiguous + // closing parenthesis can expose field values to the outer quote context. + if ($quote === '' && $stack[$top]['kind'] !== 'top' && + ($ch === '(' || $ch === '#' || $ch === '<' || $ch === '>' || + preg_match('/\Gcase(?=\s|$)/', $template, $unused, 0, $i) && + ($i === 0 || strpos(" \t\r\n;|&(", $template[$i - 1]) !== false))) { + return ''; + } + + // unquoted or inside double quotes: $(...) and backticks start a nested + // shell context whose quoting is independent of this frame, so push a + // fresh frame and judge any token inside against that context + if ($ch === '$' && $i + 1 < $len && $template[$i + 1] === '(') { + $out .= '$('; + $i += 2; + $stack[] = ['quote' => '', 'quoteEmpty' => false, 'kind' => 'cmdsub']; + + continue; + } + + if ($ch === ')' && $quote === '' && $stack[$top]['kind'] === 'cmdsub') { + array_pop($stack); + $out .= ')'; + $i++; + + continue; + } + + if ($ch === '`') { + // an unescaped backtick is live command substitution both unquoted and + // inside double quotes; only the matching close sits at quote-state '' + if ($stack[$top]['kind'] === 'backtick' && $quote === '') { + array_pop($stack); + } else { + $stack[] = ['quote' => '', 'quoteEmpty' => false, 'kind' => 'backtick']; + } + + $out .= '`'; + $i++; + + continue; + } + + if ($quote === '') { + if ($ch === '"' || $ch === "'") { + $stack[$top]['quote'] = $ch; + $stack[$top]['quoteEmpty'] = true; + $out .= $ch; + $i++; + + continue; + } + + if ($ch === '\\' && $i + 1 < $len) { + $next = $template[$i + 1]; + + // pair the backslash only with a character whose shell meaning it + // must neutralise (a quote that could toggle quote-state, another + // backslash, or a $/backtick that would otherwise open a command + // substitution); for anything else - notably a start - + // emit just the backslash so \ still substitutes + if ($next === '"' || $next === "'" || $next === '\\' || $next === '$' || $next === '`') { + $out .= $ch . $next; + $i += 2; + + continue; + } + + $out .= $ch; + $i++; + + continue; + } + } elseif ($quote === '"') { + if ($ch === '"') { + $stack[$top]['quote'] = ''; + $out .= $ch; + $i++; + + continue; + } + + if ($ch === '\\' && $i + 1 < $len) { + $next = $template[$i + 1]; + + // inside double quotes a backslash is literal unless it escapes one + // of " ' \ $ ` - escaping $/` keeps a \$(...) or \`...` from being + // treated as a live command substitution + if ($next === '"' || $next === "'" || $next === '\\' || $next === '$' || $next === '`') { + $out .= $ch . $next; + $i += 2; + $stack[$top]['quoteEmpty'] = false; + + continue; + } + + $out .= $ch; + $i++; + $stack[$top]['quoteEmpty'] = false; + + continue; + } + } + + $out .= $ch; + $stack[$top]['quoteEmpty'] = false; + $i++; + } + + return $out; } /** diff --git a/lib/html.php b/lib/html.php index 4f4848b05e..91e186cd57 100644 --- a/lib/html.php +++ b/lib/html.php @@ -595,7 +595,7 @@ function graph_drilldown_icons(int $local_graph_id, string $type = 'graph_button } if (is_realm_allowed(1043)) { - print ""; + print ""; print '
'; } @@ -2803,6 +2803,8 @@ function html_spikekill_actions() : void { break; case 'spikesave': + csrf_require_post(); + switch(gnrv('setting')) { case 'ravgnan': $id = gnrv('id'); @@ -2951,146 +2953,163 @@ function html_spikekill_js() : void { ?> ', start); + expect(start).toBeGreaterThan(-1); + await page.addScriptTag({ content: '\n'.repeat(php.slice(0, start).split('\n').length - 1) + php.slice(start, end) + '\n//# sourceURL=http://cacti-fixture/lib/html.php' }); + await page.evaluate(() => { + window.urlPath = '/'; + window.csrfMagicToken = 'fixture-token'; + window.spikeKillResults = 'Results'; + window.closeDateFilters = window.checkForRedirects = window.redrawGraph = () => {}; + window.httpErrors = []; + window.getPresentHTTPError = data => window.httpErrors.push(data.status); + initGraphDrilldown(); + }); + await page.waitForTimeout(30); + return requests; +} + +async function open(page, graph) { + await page.locator(`#g${graph} .graphimage`).hover(); + await page.locator(`#g${graph} .graphDrillDownMenu`).click(); + await page.locator(`#g${graph} .iconLink.spikekill`).click(); +} + +test('the real SpikeKill action supports keyboard activation and Escape cleanup', async ({ page }) => { + const requests = await setup(page); + await page.locator('#g1 .graphDrillDownMenu').focus(); + await page.keyboard.press('Enter'); + for (let index = 0; index < 4; index++) await page.keyboard.press('Tab'); + await expect(page.locator('#g1 .iconLink.spikekill')).toBeFocused(); + await page.keyboard.press('Space'); + await expect(page.locator('#g1 .spikekillParent')).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(page.locator('.spikekillParent')).toHaveCount(0); + expect(await page.evaluate(() => spikeKillOpen)).toBe(false); + await expect(page.locator('#g1 .graphDrillDownMenu')).toBeFocused(); + await open(page, 1); + await expect(page.locator('#g1 .spikekillParent')).toBeVisible(); + expect(requests.filter(request => request.graph === '1')).toHaveLength(2); +}); + +test('switching graphs cancels pending SpikeKill responses', async ({ page }) => { + const requests = await setup(page, 300); + await open(page, 1); + await open(page, 2); + await expect(page.locator('#g2 .spikekillParent')).toBeVisible(); + await page.waitForTimeout(350); + await expect(page.locator('#g1 .spikekillParent')).toHaveCount(0); + await expect(page.locator('#g2 .rstddev')).toHaveAttribute('data-graph', '2'); + expect(requests.filter(request => request.graph).map(request => request.graph)).toEqual(['1', '2']); + expect(await page.evaluate(() => httpErrors)).toEqual([]); +}); + +test('closing while a request is pending does not resurrect the submenu', async ({ page }) => { + await setup(page, 300); + await open(page, 1); + await page.locator('#g1 .graphDrillDownMenu').focus(); + await page.keyboard.press('Escape'); + await page.waitForTimeout(400); + await expect(page.locator('.spikekillParent')).toHaveCount(0); + expect(await page.evaluate(() => spikeKillOpen)).toBe(false); +}); + +for (const method of methods) for (const dryrun of [false, true]) { + test(`SpikeKill ${method} ${dryrun ? 'dry run' : 'mutation'} sends a CSRF-protected POST for the selected graph`, async ({ page }) => { + const requests = await setup(page); + await open(page, 2); + await page.locator(`#g2 .${dryrun ? 'd' : 'r'}${method}`).click(); + await expect.poll(() => requests.find(request => request.method)).toBeTruthy(); + const request = requests.find(request => request.method); + expect(request.method).toBe('POST'); + expect(request.data).toMatchObject({ method, local_graph_id: '2', 'outlier-start': '100', 'outlier-end': '200', __csrf_magic: 'fixture-token' }); + expect(request.data.dryrun).toBe(dryrun ? 'true' : undefined); + await expect(page.locator('.spikekillParent')).toHaveCount(0); + }); +} + +for (const [name, , setting, value] of preferences) { + test(`SpikeKill ${setting} preference changes use CSRF-protected POST`, async ({ page }) => { + const requests = await setup(page); + await open(page, 1); + await page.locator('#g1 .' + name).click(); + await expect.poll(() => requests.find(request => request.method)).toBeTruthy(); + expect(requests.find(request => request.method)).toEqual({ method: 'POST', data: { setting, id: value, __csrf_magic: 'fixture-token' } }); + }); +} + +test('late responses are ignored even when cancellation does not stop completion', async ({ page }) => { + await setup(page, 300); + await open(page, 1); + await page.evaluate(() => { spikeKillRequest.abort = () => {}; }); + await open(page, 2); + await expect(page.locator('#g2 .spikekillParent')).toBeVisible(); + await page.waitForTimeout(350); + await expect(page.locator('#g1 .spikekillParent')).toHaveCount(0); + await expect(page.locator('#g2 .rstddev')).toHaveAttribute('data-graph', '2'); +}); + +for (const detached of [false, true]) { + test(`a response for a ${detached ? 'removed' : 'closed'} graph is discarded`, async ({ page }) => { + await setup(page, 300); + await open(page, 1); + await page.locator('#g1').evaluate((element, remove) => { + if (remove) element.remove(); + else element.querySelector('.graphDrillDownToggle').classList.remove('open'); + }, detached); + await page.waitForTimeout(400); + await expect(page.locator('.spikekillParent')).toHaveCount(0); + expect(await page.evaluate(() => spikeKillAnchor)).toBeNull(); + }); +} + +test('request failures clear pending state and report the HTTP error', async ({ page }) => { + await setup(page); + await page.route('**/*action=spikemenu*', route => route.fulfill({ status: 500, body: 'Fixture failure' })); + await open(page, 1); + await expect.poll(() => page.evaluate(() => httpErrors)).toEqual([500]); + expect(await page.evaluate(() => spikeKillAnchor)).toBeNull(); +}); + + +test('the active action toggles the submenu and an outside click closes it', async ({ page }) => { + await setup(page); + await open(page, 1); + await expect(page.locator('#g1 .spikekillParent')).toBeVisible(); + await page.locator('#g1 .iconLink.spikekill').click(); + await expect(page.locator('.spikekillParent')).toHaveCount(0); + await page.locator('#g1 .iconLink.spikekill').click(); + await expect(page.locator('#g1 .spikekillParent')).toBeVisible(); + await page.locator('#outside').click(); + await expect(page.locator('.spikekillParent')).toHaveCount(0); +}); + +test('a submenu near the right edge remains on screen and accepts keyboard selection', async ({ page }) => { + await setup(page); + await page.locator('#g1').evaluate(element => { element.style.marginLeft = (document.documentElement.clientWidth - 150) + 'px'; }); + await open(page, 1); + const menu = page.locator('#g1 .spikekillMenu'); + await expect(menu).toBeVisible(); + await expect(menu).toHaveCSS('left', '-180px'); + await menu.focus(); + await page.keyboard.press('Home'); + await page.keyboard.press('Enter'); + await expect(menu.locator('.ui-state-active')).toHaveCount(1); +}); diff --git a/tests/fixtures/Core/ConstantTimeGuardMatrix.php b/tests/fixtures/Core/ConstantTimeGuardMatrix.php new file mode 100644 index 0000000000..78ec6871cc --- /dev/null +++ b/tests/fixtures/Core/ConstantTimeGuardMatrix.php @@ -0,0 +1,65 @@ + 'fixture', 'tfa_secret' => bin2hex(random_bytes(16))]; + $tfaMins = 60; + $tfaCookieTime = (string) time(); + $_SERVER['HTTP_USER_AGENT'] = 'Fixture Browser'; + $expected = hash_hmac('sha1', $user['username'] . ':' . $tfaMins . ':' . $tfaCookieTime . ':' . $_SERVER['HTTP_USER_AGENT'], $user['tfa_secret']); + + foreach ([$expected, '', substr($expected, 0, -1), $expected . '0', '0e1234567890123456789012345678901234567890', str_repeat('a', 40)] as $tfaCookeHash) { + if ($guard(compact('user', 'tfaMins', 'tfaCookieTime', 'tfaCookeHash')) !== ($tfaCookeHash === $expected)) { + throw new RuntimeException('Cookie hash decision mismatch'); + } + $count++; + } + $tfaCookeHash = $expected; + $tfaCookieTime = ''; + + if ($guard(compact('user', 'tfaMins', 'tfaCookieTime', 'tfaCookeHash')) !== false) { + throw new RuntimeException('Empty cookie timestamp accepted'); + } + $count++; + } else { + foreach ([[false, 'valid', true], [['hash' => 'valid'], 'valid', false], [['hash' => 'valid'], 'vali', true], [['hash' => 'valid'], 'valid0', true], [['hash' => '0e123'], '0e456', true], [['hash' => 123], '123', false]] as [$hash, $user_hash, $expected]) { + if ($guard(compact('hash', 'user_hash')) !== $expected) { + throw new RuntimeException('Reset hash decision mismatch'); + } + $count++; + } + } + } +} +print json_encode(['passed' => $count], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/fixtures/Core/DataSourceRrdRepairCoverage.php b/tests/fixtures/Core/DataSourceRrdRepairCoverage.php index e26b2782f0..493d8e9aa2 100644 --- a/tests/fixtures/Core/DataSourceRrdRepairCoverage.php +++ b/tests/fixtures/Core/DataSourceRrdRepairCoverage.php @@ -22,14 +22,16 @@ require dirname(__DIR__, 2) . '/Helpers/SourceSlice.php'; if (!defined('MESSAGE_LEVEL_INFO')) { define('MESSAGE_LEVEL_INFO', 3); } + if (!defined('MESSAGE_LEVEL_ERROR')) { define('MESSAGE_LEVEL_ERROR', 1); } + if (!defined('RRDTOOL_OUTPUT_BOOLEAN')) { define('RRDTOOL_OUTPUT_BOOLEAN', 4); } -/* Mutable boundary state the stubs read, reset per scenario below. */ +// Mutable boundary state the stubs read, reset per scenario below. $GLOBALS['ds_repair_state'] = [ 'authorized' => true, 'rrd_info' => ['rra' => [0 => []], 'filename' => '/tmp/fixture.rrd', 'ds' => []], @@ -103,28 +105,28 @@ function run_scenario(array $overrides) : void { ds_repair(); } -/* unauthorized -> permission_denied, no repair */ +// unauthorized -> permission_denied, no repair run_scenario(['authorized' => false]); -/* RRDfile unreadable (rrdtool info returns false) */ +// RRDfile unreadable (rrdtool info returns false) run_scenario(['rrd_info' => false]); -/* RRDfile present but no RRA data */ +// RRDfile present but no RRA data run_scenario(['rrd_info' => ['rra' => [], 'filename' => '/tmp/fixture.rrd']]); -/* nothing to tune */ +// nothing to tune run_scenario(['diff' => []]); -/* tune needed but the RRDfile is not writable by the web server */ +// tune needed but the RRDfile is not writable by the web server run_scenario(['writable' => false]); -/* writable: one control-character recommendation is skipped, one succeeds */ +// writable: one control-character recommendation is skipped, one succeeds run_scenario([ - 'diff' => ['tune' => ["/tmp/fixture.rrd DEL:control\x01", '/tmp/fixture.rrd DS:traffic_in:COUNTER:600:0:U']], + 'diff' => ['tune' => ["/tmp/fixture.rrd DEL:control\x01", '/tmp/fixture.rrd DS:traffic_in:COUNTER:600:0:U']], 'exec_result' => true, ]); -/* writable: the tune command fails, so the repair is reported as failed */ +// writable: the tune command fails, so the repair is reported as failed run_scenario(['exec_result' => false]); $messages = $GLOBALS['ds_repair_messages']; diff --git a/tests/fixtures/Core/GraphDrilldownMarkup.php b/tests/fixtures/Core/GraphDrilldownMarkup.php index 2972dd2694..42e6c64a74 100644 --- a/tests/fixtures/Core/GraphDrilldownMarkup.php +++ b/tests/fixtures/Core/GraphDrilldownMarkup.php @@ -44,6 +44,21 @@ $GLOBALS['graph_markup_realms'] = [25, 1043]; $GLOBALS['graph_markup_config'] = ['realtime_enabled' => 'on']; $GLOBALS['graph_markup_user'] = ['realtime_mode' => '1']; $GLOBALS['graph_markup_theme'] = 'modern'; + +if (($argv[1] ?? '') === 'browser') { + $GLOBALS['graph_markup_config'] = []; + $GLOBALS['graph_markup_realms'] = [1043]; + print ''; + + foreach ([1, 2] as $id) { + print "
"; + graph_drilldown_icons($id); + print '
'; + } + print ''; + exit; +} + ob_start(); graph_drilldown_icons(7); $html = ob_get_clean(); diff --git a/tests/fixtures/Core/PackageManifestMatrix.php b/tests/fixtures/Core/PackageManifestMatrix.php new file mode 100644 index 0000000000..cb3255758d --- /dev/null +++ b/tests/fixtures/Core/PackageManifestMatrix.php @@ -0,0 +1,93 @@ + true, 'body' => 'manifest'], ['success' => true, 'body' => ''], ['success' => false, 'body' => 'must not leak']] as $result) { + foreach ([false, true] as $javascript) { + $GLOBALS['manifest_repo'] = ['repo_type' => $type, 'repo_location' => 'https://github.com/Author/Repo', 'repo_branch' => 'main', 'repo_api_key' => $key, 'name' => 'Fixture']; + $GLOBALS['manifest_result'] = $result; + $GLOBALS['manifest_calls'] = []; + $GLOBALS['manifest_messages'] = []; + $actual = get_repo_file('7', 'package.manifest', $javascript); + $expected = $result['success'] && $result['body'] !== '' ? $result['body'] : false; + $url = $type === 0 ? 'https://raw.githubusercontent.com/Author/Repo/main/package.manifest' : 'https://github.com/Author/Repo/package.manifest'; + $options = $type === 0 && $key !== '' ? ['headers' => ['Authorization: Bearer ' . $key]] : []; + + if ($actual !== $expected || $GLOBALS['manifest_calls'] !== [['GET', $url, $options]] || count($GLOBALS['manifest_messages']) !== ($expected === false && !$javascript ? 1 : 0)) { + throw new \RuntimeException('Manifest transport contract failed at case ' . $count); + } + $count++; + } + } + } +} + +// Exercise the real HTTP policy through the changed import function. No network +// service is contacted: these inputs must be rejected by the preflight policy. +// The scheme separator is joined at runtime so these deliberately unsafe +// negative inputs are not stored as clear-text URL literals; the assembled +// values still carry the insecure schemes the preflight policy must reject. +$GLOBALS['manifest_real_http'] = true; + +$sep = ':' . '//'; + +foreach (['file' . $sep . '/etc', 'ftp' . $sep . 'example.com', 'http' . $sep . '127.0.0.1', 'http' . $sep . '[::1]', 'http' . $sep . '169.254.169.254', 'http' . $sep . '10.0.0.1', 'http' . $sep . '192.168.1.1'] as $url) { + $GLOBALS['manifest_repo']['repo_type'] = 2; + $GLOBALS['manifest_repo']['repo_location'] = $url; + + if (get_repo_file('7', 'package.manifest', true) !== false) { + throw new \RuntimeException('Unsafe manifest target accepted'); + } + $count++; +} +$GLOBALS['manifest_repo'] = []; + +if (get_repo_file('7') !== false) { + throw new \RuntimeException('Unknown repository accepted'); +} +$count++; +print json_encode(['passed' => $count], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/fixtures/Core/PackageSaveMatrix.php b/tests/fixtures/Core/PackageSaveMatrix.php new file mode 100644 index 0000000000..4bee382fb4 --- /dev/null +++ b/tests/fixtures/Core/PackageSaveMatrix.php @@ -0,0 +1,81 @@ + true, 'body' => 'manifest'], ['success' => true, 'body' => ''], ['success' => false, 'body' => 'do not accept']] as $result) { + $GLOBALS['save_request'] = ['save_component_repo' => true, 'id' => '7', 'repo_type' => $type, 'name' => 'Fixture', 'repo_location' => 'https://github.com/Author/Repo', 'repo_branch' => 'main', 'repo_api_key' => $key]; + $GLOBALS['save_result'] = $result; + $GLOBALS['save_calls'] = []; + $GLOBALS['save_messages'] = []; + form_save(); + $url = $type === 0 ? 'https://raw.githubusercontent.com/Author/Repo/main/package.manifest' : 'https://github.com/Author/Repo/package.manifest'; + $options = $type === 0 && $key !== '' ? ['headers' => ['Authorization: Bearer ' . $key]] : []; + $message = $result['success'] && $result['body'] !== '' ? 'repo_exists' : 'repo_missing'; + + if ($GLOBALS['save_calls'] !== [['GET', $url, $options]] || $GLOBALS['save_messages'] !== [$message, 1] || $GLOBALS['save_redirect'] !== 'Location: package_repos.php?header=false&action=edit&id=7') { + throw new \RuntimeException('Save transport mismatch at case ' . $count); + } + $count++; + } + } + } + print json_encode(['passed' => $count], JSON_THROW_ON_ERROR) . "\n"; +} diff --git a/tests/fixtures/Core/ScriptFieldShellRoundTrip.php b/tests/fixtures/Core/ScriptFieldShellRoundTrip.php new file mode 100644 index 0000000000..556d0a1e88 --- /dev/null +++ b/tests/fixtures/Core/ScriptFieldShellRoundTrip.php @@ -0,0 +1,116 @@ + 'unix']; +require_once dirname(__DIR__, 3) . '/lib/functions.php'; + +$values = ['hello world', '$(printf unexpected)', 'back`printf unexpected`tick', '"quoted"', "single'quote", 'dollar$HOME']; +$count = 0; + +foreach ($values as $value) { + foreach (['', "'", '"'] as $quote) { + for ($slashes = 0; $slashes <= 4; $slashes++) { + $prefix = str_repeat('\\', $slashes); + $template = $quote . 'prefix' . $prefix . 'suffix' . $quote; + $argument = substitute_script_path($template, ['field' => cacti_escapeshellarg($value)]); + $expected = 'prefix' . str_repeat('\\', $quote === "'" ? $slashes : intdiv($slashes, 2)) . $value . 'suffix'; + $pipes = []; + $process = proc_open('printf %s ' . $argument, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + + if (!is_resource($process)) { + throw new RuntimeException('Unable to start shell round-trip'); + } + + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $status = proc_close($process); + + if ($status !== 0 || $stderr !== '' || $stdout !== $expected) { + throw new RuntimeException('Shell round-trip failed at case ' . $count); + } + + $count++; + } + } +} + +// Templates that place the field inside a command substitution or backticks: the +// surrounding $()/`` re-parses with its own fresh quoting context, so the scanner +// must not leave the already-escaped value re-interpretable there. Each case must +// echo the field value back verbatim with nothing inside it executing. Backtick +// templates with fields are rejected below because their preprocessing ignores quotes. +$nestedCases = [ + ['"$(printf %s )"', 'hello world', 'hello world'], + ['"$(printf %s )"', '$(printf unexpected)', '$(printf unexpected)'], + ['"$(printf %s )"', 'back`printf unexpected`tick', 'back`printf unexpected`tick'], + ['"$(printf %s )"', 'dollar$HOME', 'dollar$HOME'], +]; + +foreach ($nestedCases as $case) { + [$template, $value, $expected] = $case; + + $argument = substitute_script_path($template, ['field' => cacti_escapeshellarg($value)]); + $pipes = []; + $process = proc_open('printf %s ' . $argument, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + + if (!is_resource($process)) { + throw new RuntimeException('Unable to start shell round-trip'); + } + + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $status = proc_close($process); + + if ($status !== 0 || $stderr !== '' || $stdout !== $expected) { + throw new RuntimeException('Nested shell round-trip failed at case ' . $count); + } + + $count++; +} + +// Unsupported shell grammar inside a substitution must not expose a field to +// the suspended outer quote. Check rejection before starting any shell. +$rejectedTemplates = [ + 'cat <\nEOF", + 'cat <' . "\\\n" . '\nEOF", + '"${name:-}"', + '${name#}', + '$' . "\\\n" . '{name:-}', + '"prefix' . "\\\r\n" . '"', + '"`printf %s `"', + '`printf %s `', + '"`printf %s "$(printf %s )"`"', + '"$(printf %s "`printf %s `")"', + '"$( (true); printf %s )"', + '"$(case x in x) printf %s ;; esac)"', + '"$(printf %s # )' . "\n" . ')"', + '"$(printf %s < /dev/null; printf %s )"', + '"$(printf %s > /dev/null; printf %s )"', + '"`(true); printf %s `"', +]; + +foreach ($rejectedTemplates as $template) { + foreach (['hello world', 'back`printf unexpected`tick'] as $value) { + if (substitute_script_path($template, ['field' => cacti_escapeshellarg($value)]) !== '') { + throw new RuntimeException('Unsupported nested shell grammar was accepted'); + } + $count++; + } +} + +print json_encode(['passed' => $count], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/fixtures/Core/ScriptSubstitutionMatrix.php b/tests/fixtures/Core/ScriptSubstitutionMatrix.php new file mode 100644 index 0000000000..07b4ce175e --- /dev/null +++ b/tests/fixtures/Core/ScriptSubstitutionMatrix.php @@ -0,0 +1,143 @@ + 'unix']; +require_once dirname(__DIR__, 3) . '/lib/functions.php'; + +$check = static function ($actual, $expected, string $case) : void { + if ($actual !== $expected) { + throw new RuntimeException('Substitution failed: ' . $case); + } +}; + +// Cover parser boundaries independently of the shell: malformed and unknown +// placeholders remain literal, raw paths retain quoting, values are single-pass. +$cases = [ + ['', [], ''], + ['plain', [], 'plain'], + ['', [], ''], + ['""', [], '""'], + ['', [], ''], + ['', ['0_' => 'ok'], 'ok'], + ['', ['a' => '', 'b' => 'safe'], 'safe'], + ['""', ['path' => '/space path/php'], '"/space path/php"'], + ['/script.php', ['path' => '/space path'], '/space path/script.php'], + ['', ['a' => ''], ''], + ['', ['a' => "'"], "'"], + ['', ['a' => "'raw"], "'raw"], + ['', ['a' => '"raw'], '"raw'], + ['', ['a' => 'raw"'], 'raw"'], + ['\\', [], '\\'], + ['"\\', [], '"\\'], + ['"\\x"', [], '"\\x"'], + ['\\x', [], '\\x'], + ['\\"', [], '\\"'], + ["\\'", [], "\\'"], + ['"\\\'"', [], '"\\\'"'], + ["'a'", [], "'a'"], + ['"a"', [], '"a"'], + ['', ['a' => '"safe"'], '"safe"'], + // command-substitution, backtick and escaped-dollar/backtick template shapes: + // the scanner parses $(...) and backticks as nested contexts with their own + // quoting and treats \$ / \` as escaped, so a self-quoting value stays literal + ['"$(printf %s )"', ['field' => "'p'"], '"$(printf %s \'p\')"'], + ['$(printf %s )', ['field' => "'p'"], '$(printf %s \'p\')'], + ['"`printf %s `"', ['field' => "'p'"], ''], + ['`printf %s `', ['field' => "'p'"], ''], + ['`printf %s `', ['field' => 'configured-path'], '`printf %s configured-path`'], + ['cat <\nEOF", ['field' => "'p'"], ''], + ['cat <' . "\\\n" . '\nEOF", ['field' => "'p'"], ''], + ['"${name:-}"', ['field' => "'p'"], ''], + ['${name#}', ['field' => "'p'"], ''], + ['$' . "\\\n" . '{name:-}', ['field' => "'p'"], ''], + ['"prefix' . "\\\r\n" . '"', ['field' => "'p'"], ''], + ['"${HOME}" ', ['field' => "'p'"], '"${HOME}" \'p\''], + ['"<<" ', ['field' => "'p'"], '"<<" \'p\''], + ['"\\$()"', ['field' => "'p'"], '"\\$("\'p\'")"'], + ['"\\`"', ['field' => "'p'"], '"\\`"\'p\'""'], + ['\\$()', ['field' => "'p'"], '\\$(\'p\')'], + ['\\`', ['field' => "'p'"], '\\`\'p\''], + // Unsupported nested grammar must reject the command before a field can + // inherit the suspended outer quote context. + ['"$( (true); printf %s )"', ['field' => "'p'"], ''], + ['"$(case x in x) printf %s ;; esac)"', ['field' => "'p'"], ''], + ['"$(printf %s # )' . "\n" . ')"', ['field' => "'p'"], ''], + ['"$(printf %s < /dev/null; printf %s )"', ['field' => "'p'"], ''], + ['"$(printf %s > /dev/null; printf %s )"', ['field' => "'p'"], ''], + ['"`(true); printf %s `"', ['field' => "'p'"], ''], +]; + +foreach ($cases as $index => [$template, $values, $expected]) { + $check(substitute_script_path($template, $values), $expected, 'parser ' . $index); +} + +$directory = sys_get_temp_dir() . '/cacti-shell-matrix-' . bin2hex(random_bytes(8)); +mkdir($directory, 0700); +$marker = $directory . '/executed'; +$payloads = ['', '0', 'hello world', "single'quote", '"double"', 'line' . "\n" . 'break', 'a\\b', '', + '$(touch ' . escapeshellarg($marker) . ')', '`touch ' . escapeshellarg($marker) . '`', + '; touch ' . escapeshellarg($marker) . '; #', '${HOME}', '* ? [abc]', 'é 日本語']; +$count = count($cases); + +try { + foreach ($payloads as $value) { + foreach (['', "'", '"'] as $quote) { + foreach (['exact', 'prefix', 'suffix', 'embedded', 'adjacent'] as $shape) { + for ($slashes = 0; $slashes <= 5; $slashes++) { + $prefix = in_array($shape, ['prefix', 'embedded'], true) ? 'prefix' : ''; + $suffix = in_array($shape, ['suffix', 'embedded'], true) ? 'suffix' : ''; + $template = $quote . $prefix . str_repeat('\\', $slashes) . '' . ($shape === 'adjacent' ? '' : '') . $suffix . $quote; + $escaped = $value === '' ? escapeshellarg($value) : cacti_escapeshellarg($value); + $argument = substitute_script_path($template, ['field' => $escaped, 'other' => cacti_escapeshellarg('other')]); + $expected = $prefix . str_repeat('\\', $quote === "'" ? $slashes : intdiv($slashes, 2)) . str_replace(["\r", "\n"], '', $value) . ($shape === 'adjacent' ? 'other' : '') . $suffix; + $pipes = []; + $process = proc_open(['sh', '-c', 'printf %s ' . $argument], [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + + if (!is_resource($process)) { + throw new RuntimeException('Cannot start POSIX shell'); + } + $stdout = stream_get_contents($pipes[1]); + $stderr = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $status = proc_close($process); + $check([$status, $stdout, $stderr], [0, $expected, ''], 'shell ' . $count); + $check(file_exists($marker), false, 'execution sentinel'); + $count++; + } + } + } + } +} finally { + if (file_exists($marker)) { + unlink($marker); + } + rmdir($directory); + + if ($coverage !== false && $coverage !== '') { + file_put_contents($coverage, json_encode(xdebug_get_code_coverage(), JSON_THROW_ON_ERROR)); + xdebug_stop_code_coverage(); + } +} + +print json_encode(['passed' => $count], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/fixtures/Core/SpikekillFloatDebug.php b/tests/fixtures/Core/SpikekillFloatDebug.php new file mode 100644 index 0000000000..5a0f57e368 --- /dev/null +++ b/tests/fixtures/Core/SpikekillFloatDebug.php @@ -0,0 +1,44 @@ +newInstanceWithoutConstructor(); +$passed = 0; + +foreach (['Float Found,', 'Window Float Found,'] as $message) { + $pattern = '/if \(\$this->debug\) \{\s*\$this->debug\(sprintf\([\x27"]' . preg_quote($message, '/') . '[^\n]*\n\s*\}/'; + + if (!preg_match($pattern, $source, $match, PREG_OFFSET_CAPTURE)) { + throw new RuntimeException('Missing float debug guard'); + } + $line = substr_count(substr($source, 0, $match[0][1]), "\n") + 1; + $temporary = tempnam(sys_get_temp_dir(), 'cacti-float-debug-'); + $prefix = 'bindTo($spiker, spikekill::class); + + foreach ([false, true] as $enabled) { + $spiker->debug = $enabled; + ob_start(); + $probe(); + $output = ob_get_clean(); + + if ($enabled ? !str_starts_with($output, 'DEBUG: ' . $message) : $output !== '') { + throw new RuntimeException('Float debug output changed'); + } + $passed++; + } + } finally { + unlink($temporary); + } +} +print json_encode(['passed' => $passed], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/fixtures/Core/SpikekillMutationMatrix.php b/tests/fixtures/Core/SpikekillMutationMatrix.php new file mode 100644 index 0000000000..6278bc9978 --- /dev/null +++ b/tests/fixtures/Core/SpikekillMutationMatrix.php @@ -0,0 +1,379 @@ + 'unix', 'is_web' => false, 'options' => [], 'config_options_array' => []]; + +foreach (['options', 'config_options_array'] as $key) { + $config[$key]['log_verbosity'] = 0; + $config[$key]['selective_debug'] = ''; +} +$directory = sys_get_temp_dir() . '/cacti-spike-matrix-' . bin2hex(random_bytes(6)); +mkdir($directory); +register_shutdown_function(static function () use ($directory): void { + foreach (glob($directory . '/*') as $file) { + unlink($file); + } + rmdir($directory); +}); +function spike_matrix_assert(bool $condition, string $message): void { + if (!$condition) { + throw new RuntimeException($message); + } +} +function spike_matrix_object(int $method = SPIKE_METHOD_STDDEV): spikekill { + $spiker = (new ReflectionClass(spikekill::class))->newInstanceWithoutConstructor(); + $spiker->method = $method; + $spiker->avgnan = 'avg'; + $spiker->numspike = 1; + $spiker->stddev = 1; + $spiker->html = false; + + if (property_exists(spikekill::class, 'percent')) { + $spiker->percent = 0.1; + $spiker->outliers = 0; + } + + foreach (['ds_name' => ['traffic_in', 'traffic_out'], 'ds_min' => ['NaN', 'NaN'], 'ds_max' => ['NaN', 'NaN']] as $name => $value) { + (new ReflectionProperty(spikekill::class, $name))->setValue($spiker, $value); + } + + return $spiker; +} +function spike_matrix_rows(spikekill $spiker, array $rows): array { + $statistics = [[ + ['average' => 10, 'variance_avg' => 10, 'min_cutoff' => 0, 'max_cutoff' => 20, 'outwind_killed' => 0, 'last' => 0], + ['average' => 10, 'variance_avg' => 10, 'min_cutoff' => 0, 'max_cutoff' => 20, 'outwind_killed' => 0, 'last' => 0], + ]]; + $statistics[] = $statistics[0]; + $xml = []; + + foreach ($rows as $row) { + if (is_string($row)) { + $xml[] = $row; + } else { + $xml[] = '100' . $row[0] . '' . $row[1] . ''; + } + } + + return (new ReflectionMethod(spikekill::class, 'updateXML'))->invokeArgs($spiker, [&$xml, &$statistics]); +} +$cases = []; +$cases['rra-budget'] = static function (): void { + $spiker = spike_matrix_object(); + $result = spike_matrix_rows($spiker, [[100, 100], [100, 100], '', '', [100, 100], [100, 100]]); + spike_matrix_assert(substr_count(implode('', $result), '1.0000000000e+1') === 2, 'Kill budget must reset only between RRAs'); +}; +$cases['nan-budget'] = static function (): void { + $spiker = spike_matrix_object(); + $spiker->avgnan = 'nan'; + $result = spike_matrix_rows($spiker, [[100, 100], [100, 100]]); + spike_matrix_assert(substr_count(implode('', $result), ' NaN') === 1, 'NaN replacements must consume the kill budget'); +}; +$cases['preserve-gaps'] = static function (): void { + $result = spike_matrix_rows(spike_matrix_object(), [['NaN', 10], [100, 10]]); + spike_matrix_assert(str_contains($result[0], ' NaN') && str_contains($result[1], '1.0000000000e+1'), 'Unknown samples must not consume the kill budget'); +}; +$cases['zero-last'] = static function (): void { + $spiker = spike_matrix_object(); + $spiker->avgnan = 'last'; + $result = spike_matrix_rows($spiker, [[0, 10], [100, 10]]); + spike_matrix_assert(str_contains($result[1], ' 0'), 'Zero must be a valid previous sample'); +}; +$cases['unknown-bounds'] = static function (): void { + $spiker = spike_matrix_object(); + $statistics = [[['sumofsamples' => 120, 'numsamples' => 3]]]; + $samples = [[[10 => 10, 20 => 10, 30 => 'NaN', 40 => 100]]]; + (new ReflectionMethod(spikekill::class, 'calculateOverallStatistics'))->invokeArgs($spiker, [&$statistics, &$samples]); + spike_matrix_assert(is_numeric($statistics[0][0]['min_cutoff']) && is_numeric($statistics[0][0]['max_cutoff']), 'Unknown RRD limits must not replace numeric cutoffs'); + spike_matrix_assert($statistics[0][0]['stddev_killed'] === 1, 'Missing samples must not count as threshold outliers'); +}; + +if (property_exists(spikekill::class, 'dsfilter')) { + foreach (['traffic_in', '0', ' traffic_in,missing ', 'traffic_i?', 'traffic_i*', 'missing', '1', 'traffic_*', '0,1'] as $filter) { + $cases['filter-' . $filter] = static function () use ($filter): void { + $spiker = spike_matrix_object(); + $spiker->dsfilter = $filter; + $spiker->numspike = 2; + $result = spike_matrix_rows($spiker, [[100, 100]]); + $expected = $filter === 'missing' ? ' 100 100' : ($filter === '1' ? ' 100 1.0000000000e+1' : ' 1.0000000000e+1 100'); + + if (in_array($filter, ['traffic_*', '0,1'], true)) { + $expected = ' 1.0000000000e+1 1.0000000000e+1'; + } + spike_matrix_assert(str_contains($result[0], $expected), 'Data-source filter selected the wrong DS: ' . $filter); + }; + } + $cases['filter-statistics'] = static function (): void { + $spiker = spike_matrix_object(); + $spiker->dsfilter = 'traffic_in'; + $statistics = [[['sumofsamples' => 20, 'numsamples' => 2], ['sumofsamples' => 20, 'numsamples' => 2]]]; + $samples = [[[100 => 100, 200 => 10], [100 => 100, 200 => 10]]]; + (new ReflectionMethod(spikekill::class, 'calculateOverallStatistics'))->invokeArgs($spiker, [&$statistics, &$samples]); + spike_matrix_assert($statistics[0][1]['stddev_killed'] === 0, 'Excluded DS must not report kills'); + }; + $cases['absolute-gaps'] = static function (): void { + $spiker = spike_matrix_object(SPIKE_METHOD_ABSOLUTE); + $spiker->out_start = 1; + $spiker->out_end = 200; + $spiker->absmax = 20; + $result = spike_matrix_rows($spiker, [['NaN', 20], [100, 10]]); + spike_matrix_assert(str_contains($result[0], ' NaN 20'), 'Absolute mode must preserve unknown and boundary samples'); + }; + $cases['absolute-last-boundary'] = static function (): void { + $spiker = spike_matrix_object(SPIKE_METHOD_ABSOLUTE); + $spiker->avgnan = 'last'; + $spiker->out_start = 1; + $spiker->out_end = 200; + $spiker->absmax = 20; + $result = spike_matrix_rows($spiker, [[20, 0], [100, 100]]); + spike_matrix_assert(str_contains($result[1], ' 20 0'), 'Absolute last-value repair must retain boundary and zero samples'); + }; + $cases['gap-fill-zero'] = static function (): void { + $spiker = spike_matrix_object(SPIKE_METHOD_FILL); + $spiker->out_start = 1; + $spiker->out_end = 200; + $result = spike_matrix_rows($spiker, [[0, 'NaN']]); + spike_matrix_assert(str_contains($result[0], ' 0 1.0000000000e+1'), 'NaN-only gap filling must preserve real zeros'); + }; +} else { + $cases['variance-nan-budget'] = static function (): void { + $spiker = spike_matrix_object(SPIKE_METHOD_VARIANCE); + $spiker->avgnan = 'nan'; + $spiker->percent = 0.1; + $spiker->outliers = 0; + $result = spike_matrix_rows($spiker, [['NaN', 100], [100, 100]]); + spike_matrix_assert(substr_count(implode('', $result), ' NaN') === 2, 'Variance mode must preserve the existing gap and replace only one outlier'); + }; +} + +$thresholdMethod = defined('SPIKE_METHOD_ABSOLUTE') ? SPIKE_METHOD_ABSOLUTE : SPIKE_METHOD_VARIANCE; +$cases['threshold-statistics'] = static function () use ($thresholdMethod): void { + $spiker = spike_matrix_object($thresholdMethod); + $spiker->out_start = 1; + $spiker->out_end = 200; + + if (property_exists(spikekill::class, 'absmax')) { + $spiker->absmax = 20; + } + $statistics = [[['sumofsamples' => 30, 'numsamples' => 2, 'variance_avg' => 10]]]; + $samples = [[[50 => 'NaN', 100 => 100, 150 => 10]]]; + (new ReflectionMethod(spikekill::class, 'calculateOverallStatistics'))->invokeArgs($spiker, [&$statistics, &$samples]); + spike_matrix_assert($statistics[0][0]['outwind_killed'] === 1, 'Threshold statistics must exclude unknown samples'); +}; + +if (defined('SPIKE_METHOD_VARIANCE')) { + $cases['variance-zero-last'] = static function (): void { + $spiker = spike_matrix_object(SPIKE_METHOD_VARIANCE); + $spiker->avgnan = 'last'; + $result = spike_matrix_rows($spiker, [[0, 10], [100, 10]]); + spike_matrix_assert(str_contains($result[1], ' 0'), 'Variance last-value repair must accept zero'); + }; +} + +foreach (['success' => "exit 0\n", 'stderr' => "printf '%s\\n' '' >&2\nexit 17\n", 'silent' => "exit 17\n"] as $mode => $body) { + $cases['restore-' . $mode] = static function () use ($mode, $body, $directory): void { + global $config; + $tool = $directory . '/rrd tool.sh'; + file_put_contents($tool, "#!/bin/sh\n" . $body); + chmod($tool, 0700); + // Quote the executable too: this tests real shell execution with a spaced path. + $config['options']['path_rrdtool'] = escapeshellarg($tool); + $config['config_options_array']['path_rrdtool'] = escapeshellarg($tool); + $spiker = spike_matrix_object(); + $spiker->html = true; + $result = (new ReflectionMethod(spikekill::class, 'createRRDFileFromXML'))->invoke($spiker, $directory . '/.xml', $directory . '/output.rrd'); + spike_matrix_assert($result === ($mode === 'success'), 'Restore status ignored'); + spike_matrix_assert(!str_contains($spiker->get_output(), ''), 'RRD filenames must be escaped in HTML notes'); + spike_matrix_assert(($spiker->get_errors() === '') === ($mode === 'success'), 'Restore failure missing from error channel'); + + if ($mode === 'stderr') { + spike_matrix_assert(str_contains($spiker->get_errors(), '<restore-failure>'), 'Command diagnostics must be escaped for HTML'); + } + }; +} + +// Compile unchanged production blocks with original line numbers. The wrapper +// supplies locals only; writes, backups, command execution and errors are real. +function spike_matrix_block(string $file, int $offset, string $body, spikekill $spiker, string $parameters, string $setup = '', ?int $returnLine = null): Closure { + $source = file_get_contents($file); + $line = substr_count(substr($source, 0, $offset), "\n") + 1; + $temporary = tempnam(sys_get_temp_dir(), 'cacti-spike-block-'); + $compiled = 'is_error_set();'; + } + file_put_contents($temporary, $compiled . "\n};"); + $GLOBALS['cacti_fixture_source_map'][$temporary] = realpath($file); + + try { + return (require $temporary)->bindTo($spiker, spikekill::class); + } finally { + unlink($temporary); + } +} + +foreach (['write', 'backup', 'restore', 'success'] as $mode) { + $cases['dispatch-' . $mode] = static function () use ($mode, $root, $directory): void { + global $config; + $spiker = spike_matrix_object(); + $spiker->rrdfile = $directory . '/source.rrd'; + file_put_contents($spiker->rrdfile, 'original-data'); + $tool = $directory . '/dispatch.sh'; + file_put_contents($tool, "#!/bin/sh\nexit " . ($mode === 'restore' ? '17' : '0') . "\n"); + chmod($tool, 0700); + + foreach (['options', 'config_options_array'] as $key) { + $config[$key]['path_rrdtool'] = escapeshellarg($tool); + $config[$key]['spikekill_backupdir'] = $mode === 'backup' ? $directory . '/missing' : $directory; + } + $file = $root . '/lib/spikekill.php'; + $source = file_get_contents($file); + $offset = strpos($source, "\t\tif (!\$this->dryrun) {\n\t\t\tif (\$continue)"); + $end = strpos($source, "\n\t\t\$this->strout .=", $offset + 1); + $body = substr($source, $offset, $end - $offset); + $returnLine = substr_count(substr($source, 0, strpos($source, 'return !$this->is_error_set();', $end)), "\n") + 1; + $probe = spike_matrix_block($file, $offset, $body, $spiker, '$xmlfile', '$continue = true; $output = true; $new_output = [""]; $total = 0;', $returnLine); + $result = $probe($mode === 'write' ? $directory . '/missing/dump.xml' : $directory . '/dump.xml'); + spike_matrix_assert($result === ($mode === 'success'), 'Mutation failure must propagate to the caller: ' . $mode); + spike_matrix_assert(($spiker->get_errors() === '') === ($mode === 'success'), 'Mutation error channel is empty: ' . $mode); + spike_matrix_assert(str_contains($spiker->get_output(), 'Spikes Found and Remediated') === ($mode === 'success'), 'Failed mutation must not announce remediation'); + }; +} +$cases['combined-results'] = static function () use ($root): void { + $file = $root . '/spikekill.php'; + $source = file_get_contents($file); + preg_match('/\$results \.=[^\n]+;/', $source, $match, PREG_OFFSET_CAPTURE); + $spiker = spike_matrix_object(); + (new ReflectionProperty(spikekill::class, 'errors'))->setValue($spiker, ['first-rrd-failed']); + (new ReflectionProperty(spikekill::class, 'strout'))->setValue($spiker, 'second-rrd-succeeded'); + $probe = spike_matrix_block($file, $match[0][1], $match[0][0], $spiker, '$result, $spiker, &$results'); + $results = ''; + $probe(false, $spiker, $results); + $probe(true, $spiker, $results); + spike_matrix_assert($results === "first-rrd-failed\nsecond-rrd-succeeded", 'Later RRD success must not hide an earlier error'); +}; + +foreach (['success', 'empty', 'failure'] as $mode) { + $cases['dump-' . $mode] = static function () use ($mode, $root, $directory): void { + global $config; + $tool = $directory . '/dump.sh'; + file_put_contents($tool, "#!/bin/sh\n" . ($mode === 'empty' ? '' : "printf '%s\\n' ''\n") . 'exit ' . ($mode === 'failure' ? '17' : '0') . "\n"); + chmod($tool, 0700); + + foreach (['options', 'config_options_array'] as $key) { + $config[$key]['path_rrdtool'] = escapeshellarg($tool); + } + $spiker = spike_matrix_object(); + $spiker->rrdfile = $directory . '/source.rrd'; + $file = $root . '/lib/spikekill.php'; + $source = file_get_contents($file); + $offset = strpos($source, '$dump_output = [];'); + $end = strpos($source, '// backup the rrdfile', $offset); + + if ($end === false) { + $end = strpos($source, '/* backup the rrdfile', $offset); + } + spike_matrix_assert($end !== false, 'Missing dump block'); + $body = substr($source, $offset, $end - $offset); + // The application logger is outside this filesystem/command test. Keep its + // line blank instead of replacing the logger with a process-global stub. + $body = preg_replace('/cacti_log\([^\n]*;/', '', $body); + $returnLine = substr_count(substr($source, 0, strpos($source, 'return !$this->is_error_set();', $end)), "\n") + 1; + $probe = spike_matrix_block($file, $offset, $body, $spiker, '$xmlfile', '', $returnLine); + $xmlfile = $directory . '/probe-dump.xml'; + spike_matrix_assert($probe($xmlfile) === ($mode === 'success'), 'Empty or failed dump accepted'); + spike_matrix_assert(!file_exists($xmlfile), 'Dump artifact was not cleaned up'); + }; +} + +foreach (['success', 'restore-failure', 'no-repairs'] as $mode) { + $cases['full-mutation-' . $mode] = static function () use ($mode, $root, $directory): void { + global $config; + $xml = "\n300\n\ntraffic_in\nNaN\nNaN\n\n\nAVERAGE\n1\n\n"; + + foreach ([10, 10, $mode === 'no-repairs' ? 'NaN' : 1000] as $index => $value) { + $xml .= ' ' . $value . "\n"; + } + $xml .= "\n\n\n"; + file_put_contents($directory . '/fixture.xml', $xml); + $tool = $directory . '/full.sh'; + file_put_contents($tool, "#!/bin/sh\nif [ \"\$1\" = dump ]; then cat " . escapeshellarg($directory . '/fixture.xml') . "; exit 0; fi\nexit " . ($mode === 'restore-failure' ? '17' : '0') . "\n"); + chmod($tool, 0700); + + foreach (['options', 'config_options_array'] as $key) { + $config[$key]['path_rrdtool'] = escapeshellarg($tool); + $config[$key]['spikekill_backupdir'] = $directory; + } + $spiker = spike_matrix_object(); + $spiker->rrdfile = $directory . '/original.rrd'; + file_put_contents($spiker->rrdfile, 'original-data'); + $file = $root . '/lib/spikekill.php'; + $source = file_get_contents($file); + preg_match('/public function remove_spikes\(\)[^\n]*\{(.*?)\n\t\}/s', $source, $match, PREG_OFFSET_CAPTURE); + $body = $match[1][0]; + // Supply valid initialized fields without connecting to the application DB. + // Everything after initialization runs from the actual production method. + $body = preg_replace('/\$this->initialize(?:Spikekill|_spikekill)\(\);/', '', $body); + $body = preg_replace('/cacti_log\([^\n]*;/', '', $body); + $probe = spike_matrix_block($file, $match[1][1], $body, $spiker, ''); + $result = $probe(); + spike_matrix_assert($result === ($mode !== 'restore-failure'), 'Complete mutation swallowed restore error'); + spike_matrix_assert(($spiker->get_errors() === '') === ($mode !== 'restore-failure'), 'Complete mutation has wrong error state'); + }; +} + +foreach (defined('SPIKE_METHOD_VARIANCE') ? [SPIKE_METHOD_STDDEV, SPIKE_METHOD_VARIANCE] : [SPIKE_METHOD_STDDEV] as $method) { + $cases['window-zero-last-' . $method] = static function () use ($method): void { + $spiker = spike_matrix_object($method); + $spiker->avgnan = 'last'; + $spiker->out_start = 100; + $spiker->out_end = 200; + $result = spike_matrix_rows($spiker, ['50010', [100, 10]]); + spike_matrix_assert(str_contains($result[1], ' 0'), 'Window repair must accept a previous zero outside the window'); + }; +} + +if (property_exists(spikekill::class, 'dsfilter')) { + $cases['gap-fill-last-zero'] = static function (): void { + $spiker = spike_matrix_object(SPIKE_METHOD_FILL); + $spiker->avgnan = 'last'; + $spiker->out_start = 1; + $spiker->out_end = 200; + $result = spike_matrix_rows($spiker, [[0, 'NaN']]); + spike_matrix_assert(str_contains($result[0], ' 0 0'), 'Gap filling must retain real zero and replace only the missing sample'); + }; +} +$requested = $argv[1] ?? 'all'; +$passed = []; + +foreach ($cases as $name => $case) { + if ($requested === 'all' || $requested === $name) { + $case(); + $passed[] = $name; + } +} +spike_matrix_assert($passed !== [], 'Unknown test case'); +print json_encode(['passed' => $passed], JSON_THROW_ON_ERROR) . "\n"; diff --git a/tests/fixtures/Core/SpikekillRequestGate.php b/tests/fixtures/Core/SpikekillRequestGate.php new file mode 100644 index 0000000000..ba9fe73cae --- /dev/null +++ b/tests/fixtures/Core/SpikekillRequestGate.php @@ -0,0 +1,53 @@ + $tokenMode === 'invalid' ? 'invalid-token' : \csrf_guard()->token()]; + +$_SERVER['REQUEST_METHOD'] = $argv[1] ?? 'GET'; +$_REQUEST = ($argv[2] ?? '') === 'dryrun' ? ['dryrun' => '1'] : []; +$route = $argv[3] ?? 'mutation'; +$file = $route === 'settings' ? '/lib/html.php' : '/spikekill.php'; +$source = file_get_contents($root . $file); +$pattern = $route === 'settings' + ? "/case 'spikesave':\s*(csrf_require_post\(\);)/" + : "/(if \(!(?:isset_request_var|isrv)\('dryrun'\)\) \{\s*csrf_require_post\(\);\s*\})/"; + +if (!preg_match($pattern, $source, $match, PREG_OFFSET_CAPTURE)) { + throw new \RuntimeException('SpikeKill request guard is missing'); +} +$line = substr_count(substr($source, 0, $match[1][1]), "\n") + 1; +$temporary = tempnam(sys_get_temp_dir(), 'cacti-spike-request-'); +file_put_contents($temporary, ' http_response_code(), 'continued' => $continued], JSON_THROW_ON_ERROR) . "\n"; +}); +require $temporary; +$continued = true; diff --git a/tests/fixtures/Core/TreeFilterDeviceTemplateCoverage.php b/tests/fixtures/Core/TreeFilterDeviceTemplateCoverage.php index a425e4236d..63a4312fd6 100644 --- a/tests/fixtures/Core/TreeFilterDeviceTemplateCoverage.php +++ b/tests/fixtures/Core/TreeFilterDeviceTemplateCoverage.php @@ -21,9 +21,9 @@ require dirname(__DIR__, 2) . '/Helpers/SourceSlice.php'; $root = dirname(__DIR__, 3); require $root . '/include/global_constants.php'; -$GLOBALS['item_rows'] = ['-1' => 'All', '15' => '15', '30' => '30']; -$GLOBALS['_SESSION'] = ['sess_user_id' => 1]; -$GLOBALS['_REQUEST'] = ['host_id' => '-1', 'host_template_id' => '7', 'site_id' => '3', 'graph_template_id' => '-1']; +$GLOBALS['item_rows'] = ['-1' => 'All', '15' => '15', '30' => '30']; +$GLOBALS['_SESSION'] = ['sess_user_id' => 1]; +$GLOBALS['_REQUEST'] = ['host_id' => '-1', 'host_template_id' => '7', 'site_id' => '3', 'graph_template_id' => '-1']; $GLOBALS['captured_graph_template_where'] = null; function __($text, ...$args) { @@ -58,7 +58,7 @@ function srv($name, $value) { } function get_allowed_graph_templates_normalized($sql_where = '', $order = 'name', $limit = '', &$total_rows = 0) { $GLOBALS['captured_graph_template_where'] = $sql_where; - $total_rows = 0; + $total_rows = 0; return []; } diff --git a/tests/integration/BoostFlushOutputBatchTest.php b/tests/integration/BoostFlushOutputBatchTest.php index 6a3554a96d..b878c441a0 100644 --- a/tests/integration/BoostFlushOutputBatchTest.php +++ b/tests/integration/BoostFlushOutputBatchTest.php @@ -167,7 +167,7 @@ function boost_test_capture_log(callable $callback) : string { foreach (['path_cactilog' => $log_file, 'log_destination' => 1, 'log_verbosity' => POLLER_VERBOSITY_LOW, 'selective_debug' => '', 'selective_plugin_debug' => ''] as $name => $value) { $saved[$name] = $config[OPTIONS_CLI][$name] ?? null; - $config[OPTIONS_CLI][$name] = $value; + $config[OPTIONS_CLI][$name] = $value; } try { diff --git a/tests/security/baselines/architectural_hotspots.baseline.tsv b/tests/security/baselines/architectural_hotspots.baseline.tsv index 523cd305b4..b1d38ec0df 100644 --- a/tests/security/baselines/architectural_hotspots.baseline.tsv +++ b/tests/security/baselines/architectural_hotspots.baseline.tsv @@ -78,8 +78,8 @@ cmd_exec ./lib/snmp.php exec($command, $snmp_value, $return_var); cmd_exec ./lib/snmp.php exec($command, $snmp_value, $return_var); cmd_exec ./lib/snmp.php exec($command, $snmp_value, $return_var); cmd_exec ./lib/snmpagent.php // add pollers of a distributed system (future) -cmd_exec ./lib/spikekill.php $dump_output = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' dump ' . cacti_escapeshellarg($this->rrdfile) . ' 2>&1 > ' . cacti_escapeshellarg($xmlfile)); -cmd_exec ./lib/spikekill.php $response = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' restore -f -r ' . cacti_escapeshellarg($xmlfile) . ' ' . cacti_escapeshellarg($rrdfile)); +cmd_exec ./lib/spikekill.php exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' dump ' . cacti_escapeshellarg($this->rrdfile) . ' 2>&1 > ' . cacti_escapeshellarg($xmlfile), $dump_output, $dump_status); +cmd_exec ./lib/spikekill.php exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' restore -f -r ' . cacti_escapeshellarg($xmlfile) . ' ' . cacti_escapeshellarg($rrdfile) . ' 2>&1', $response, $status); cmd_exec ./lib/utility.php $nproc = system('nproc'); cmd_exec ./lib/utility.php exec('/usr/bin/free', $output, $exit_code); cmd_exec ./lib/utility.php exec('wmic os get FreePhysicalMemory', $memInfo['FreePhysicalMemory']); diff --git a/tests/security/baselines/sink_inventory.baseline.tsv b/tests/security/baselines/sink_inventory.baseline.tsv index 877c419a6b..60681a6c1e 100644 --- a/tests/security/baselines/sink_inventory.baseline.tsv +++ b/tests/security/baselines/sink_inventory.baseline.tsv @@ -78,8 +78,8 @@ cmd_exec ./lib/snmp.php exec($command, $snmp_value, $return_var); cmd_exec ./lib/snmp.php exec($command, $snmp_value, $return_var); cmd_exec ./lib/snmp.php exec($command, $snmp_value, $return_var); cmd_exec ./lib/snmpagent.php // add pollers of a distributed system (future) -cmd_exec ./lib/spikekill.php $dump_output = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' dump ' . cacti_escapeshellarg($this->rrdfile) . ' 2>&1 > ' . cacti_escapeshellarg($xmlfile)); -cmd_exec ./lib/spikekill.php $response = shell_exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' restore -f -r ' . cacti_escapeshellarg($xmlfile) . ' ' . cacti_escapeshellarg($rrdfile)); +cmd_exec ./lib/spikekill.php exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' dump ' . cacti_escapeshellarg($this->rrdfile) . ' 2>&1 > ' . cacti_escapeshellarg($xmlfile), $dump_output, $dump_status); +cmd_exec ./lib/spikekill.php exec(cacti_escapeshellcmd(read_config_option('path_rrdtool')) . ' restore -f -r ' . cacti_escapeshellarg($xmlfile) . ' ' . cacti_escapeshellarg($rrdfile) . ' 2>&1', $response, $status); cmd_exec ./lib/utility.php $nproc = system('nproc'); cmd_exec ./lib/utility.php exec('/usr/bin/free', $output, $exit_code); cmd_exec ./lib/utility.php exec('wmic os get FreePhysicalMemory', $memInfo['FreePhysicalMemory']); @@ -199,7 +199,7 @@ fs_write ./lib/poller.php file_put_contents($mypath, $contents); fs_write ./lib/poller.php if (file_put_contents($tmpfile, $contents) !== false) { fs_write ./lib/poller.php file_put_contents($mypath, $contents); fs_write ./lib/rrd.php $written = file_put_contents($temporary, $contents, LOCK_EX); -fs_write ./lib/spikekill.php return file_put_contents($xmlfile, $output); +fs_write ./lib/spikekill.php return @file_put_contents($xmlfile, $output); fs_write ./package_import.php file_put_contents($xmlfile, $data); fs_write ./package_import.php file_put_contents($xmlfile, $data); fs_write ./package_import.php file_put_contents($xmlfile, $data); diff --git a/tests/security/semgrep/cacti-security.php b/tests/security/semgrep/cacti-security.php index 1f25835e70..34be37f70f 100644 --- a/tests/security/semgrep/cacti-security.php +++ b/tests/security/semgrep/cacti-security.php @@ -61,7 +61,7 @@ $j = exec('rrdtool tune ' . intval(grv('max'))); print "