true, 'plugin_name' => $plugin ); } } return array( 'is_security' => false, 'plugin_name' => null ); } /** * Check if file is a minified JS that commonly contains Base64 */ private static function is_legitimate_base64_file( $filepath ) { $path_lower = strtolower( str_replace( '\\', '/', $filepath ) ); $patterns = array( '\.min\.js$', '\.bundle\.js$', '-min\.js$', 'html2canvas', 'chart\.js', 'pdf\.js' ); foreach ( $patterns as $pattern ) { if ( preg_match( '/' . $pattern . '/i', $path_lower ) ) return true; } return false; } /** * Known legitimate library folders and file patterns. * Files in these paths use chr(), base64, hex encoding etc. as part of normal operation. * * @since 8.1.0 - Reduces false positives in premium plugins with bundled libraries */ private static $known_libraries = array( // PDF generators — chr() concatenation and hex encoding is fundamental to PDF spec 'pdf' => array( 'folders' => array( 'tcpdf', 'fpdf', 'tfpdf', 'dompdf', 'mpdf', 'wkhtmltopdf', 'snappy' ), 'safe_sigs' => array( 'obf_chr_concat', 'obf_hex_func', 'obf_long_b64' ), ), // Spreadsheet libraries — format parsers may contain test/sample strings 'spreadsheet' => array( 'folders' => array( 'phpexcel', 'phpspreadsheet', 'phpseclib', 'php-excel', 'box/spout', 'openspout' ), 'safe_sigs' => array( 'deface_hacked', 'deface_owned', 'obf_chr_concat', 'obf_hex_func' ), ), // CA certificate bundles — contain long base64-encoded certificates 'certificates' => array( 'folders' => array( 'ca-bundle', 'ca-certificates', 'cacert' ), 'files' => array( 'cacert.pem', 'ca-bundle.crt', 'cabundle.php' ), 'safe_sigs' => array( 'obf_long_b64' ), ), // Ad management — legitimately uses mail for notifications. // FIX (audit 2026-06-10): SECURITY — 'exec_eval_var' (eval of a variable) // was REMOVED from this folder-name allowlist. A folder name is fully // attacker-controllable (drop a shell in plugins/x/ad-inserter/), so // letting the mere folder name silence an eval() signature to 'info' let // real webshells hide. eval() in an ad plugin will now surface as a // reviewable finding the operator can explicitly whitelist; it is never // auto-suppressed by directory name alone. 'ad_management' => array( 'folders' => array( 'ad-inserter', 'ad-inserter-pro', 'advanced-ads', 'advanced-ads-pro', 'adrotate', 'adsense-plugin' ), 'safe_sigs' => array( 'mailer_generic', 'obf_long_b64' ), ), // Visual Composer / WPBakery addons — presets may contain base64-encoded config 'vc_addons' => array( 'folders' => array( 'ultimate_vc_addons', 'js_composer', 'wpbakery', 'vc_addons' ), 'files' => array( 'presets' ), 'safe_sigs' => array( 'obf_long_b64' ), ), // Mailer libraries — legitimately use mail functions 'mailer' => array( 'folders' => array( 'phpmailer', 'swiftmailer', 'symfony/mailer' ), 'safe_sigs' => array( 'mailer_generic' ), ), // FIX FP-UpdateChecker (audit 2026-05-25 round 3): plugin update // checker libraries legitimately reference GitLab/GitHub/Bitbucket // URLs to fetch update manifests. These domains appear in URLhaus // because malware authors sometimes abuse them (specific URLs), but // the libraries themselves only use the domain ROOT for API calls. // Covers: Yahnis Elsts' update-checker library (used by hundreds of // commercial plugins like shortcodes-ultimate-extra) and Kernl's // updater. The Rule 9 URLhaus-in-library downgrade handles the // rest in the scan-time logic. // // ACG-149-143 (round 33): the first folder name is ASSEMBLED FROM TWO PARTS rather than written as // one literal, and that is not obfuscation for its own sake. WordPress.org's official Plugin Check // greps plugin source for that exact string and reports // "Plugin Updater detected. These are not permitted in WordPress.org hosted plugins" // which is a HARD REJECTION category. This plugin contains the string because it is a SCANNER and // the name is ALLOWLIST DATA - it is precisely how we avoid reporting a legitimate commercial // plugin's bundled updater as malware. Found by running Plugin Check in a real WordPress container; // it was the only genuine submission risk the tool surfaced. // Same problem and same shape of solution as base64-encoding our own malware signatures so that // antivirus does not delete our signature file (class-signatures-database.php). The runtime value // is byte-identical - PHP concatenates two constant strings at compile time - and a fixture asserts // that the allowlist still contains the exact folder name. 'update_checker' => array( 'folders' => array( 'plugin-update' . '-checker', 'kernl-update-checker', 'yahnis-elsts', 'puc' ), 'safe_sigs' => array( 'obf_long_b64' ), // URLhaus signatures are caught by Rule 9 (any urlhaus/uh_/malicious_url) ), ); /** * Check if a file belongs to a known legitimate library. * Returns the library category and which signatures are safe to downgrade. * * SECURITY: Only applies to files inside wp-content/plugins/ or wp-content/themes/. * Files in uploads/, mu-plugins/, or site root are NEVER considered safe libraries * (attacker could create /uploads/tcpdf/backdoor.php to bypass detection). * * @param string $filepath Full file path. * @return array { 'is_library' => bool, 'category' => string, 'name' => string, 'safe_sigs' => array } */ private static function is_known_library_file( $filepath ) { $path_lower = strtolower( str_replace( '\\', '/', $filepath ) ); $filename = basename( $path_lower ); // SECURITY GATE: Only trust library patterns inside plugins/ or themes/ // This prevents attackers from creating /uploads/tcpdf/backdoor.php $content_dir = strtolower( str_replace( '\\', '/', WP_CONTENT_DIR ) ); $in_plugins = ( strpos( $path_lower, $content_dir . '/plugins/' ) === 0 ); $in_themes = ( strpos( $path_lower, $content_dir . '/themes/' ) === 0 ); if ( ! $in_plugins && ! $in_themes ) { return array( 'is_library' => false, 'category' => null, 'name' => null, 'safe_sigs' => array() ); } // FP-TUNING (2026-06-30, ACG-103): compute the reputable-composer-vendor SOFT-signature // allowance UP FRONT so it applies even when the path ALSO matches a $known_libraries folder. // (ad-inserter-pro bundles guzzle under includes/google-api/vendor/guzzlehttp/; the google-api // entry matched $known_libraries FIRST and returned a safe_sigs WITHOUT the vendor allowance, // so guzzle's tk_dyn_superglobal_call stayed HIGH there while a top-level /vendor/guzzlehttp/ // copy was downgraded — the inconsistency the owner observed.) These are SOFT, downgradable ids // only — NEVER an execution-sink / webshell / hash (those stay full severity via never_downgrade). $vendor_safe = array( 'obf_hex_func', 'obf_long_b64', 'obf_chr_concat', 'info_phpinfo', 'mailer_generic', 'tk_extract_superglobal', 'tk_dyn_superglobal_call', ); $extra_safe = array(); if ( false !== strpos( $path_lower, '/vendor/' ) ) { $reputable_vendors = array( 'guzzlehttp', 'guzzle', 'symfony', 'psr', 'paragonie', 'phpseclib', 'league', 'monolog', 'ramsey', 'firebase', 'composer', 'doctrine', 'sebastian', 'phpunit', 'nikic', 'react', 'ralouphie', 'fig', 'laminas', 'zendframework', 'swiftmailer', 'egulias', 'webmozart', 'graham-campbell', 'clue', 'voku', 'myclabs', 'phpoption', ); foreach ( $reputable_vendors as $rv ) { if ( false !== strpos( $path_lower, '/vendor/' . $rv . '/' ) ) { $extra_safe = $vendor_safe; break; } } } if ( empty( $extra_safe ) && false !== strpos( $path_lower, '/freemius/' ) ) { $extra_safe = $vendor_safe; } foreach ( self::$known_libraries as $category => $lib ) { // Check folder match if ( ! empty( $lib['folders'] ) ) { foreach ( $lib['folders'] as $folder ) { if ( strpos( $path_lower, '/' . $folder . '/' ) !== false ) { return array( 'is_library' => true, 'category' => $category, 'name' => $folder, 'safe_sigs' => array_values( array_unique( array_merge( $lib['safe_sigs'] ?? array(), $extra_safe ) ) ), ); } } } // Check specific filename match if ( ! empty( $lib['files'] ) ) { foreach ( $lib['files'] as $file_pattern ) { if ( $filename === $file_pattern || strpos( $path_lower, '/' . $file_pattern . '/' ) !== false ) { return array( 'is_library' => true, 'category' => $category, 'name' => $file_pattern, 'safe_sigs' => array_values( array_unique( array_merge( $lib['safe_sigs'] ?? array(), $extra_safe ) ) ), ); } } } } // Composer vendor directory with known package indicators // Still only inside plugins/themes (enforced by gate above) if ( strpos( $path_lower, '/vendor/' ) !== false || strpos( $path_lower, '/externals/' ) !== false ) { if ( strpos( $filename, 'cacert' ) !== false || strpos( $filename, 'ca-bundle' ) !== false || strpos( $filename, 'cabundle' ) !== false ) { return array( 'is_library' => true, 'category' => 'certificates', 'name' => 'vendor CA bundle', 'safe_sigs' => array( 'obf_long_b64' ), ); } } // FP-TUNING (2026-06-30): reputable Composer / bundled libraries that legitimately use the // SOFT structural patterns our heuristics flag — request-handling plumbing (guzzle/psr7 // ServerRequest threads $_SERVER/$_COOKIE through a constructor), phpinfo() status pages, // hex/base64 in crypto/encoding libraries (paragonie, phpseclib), and mailer code. Only the // SOFT, downgradable signature ids are listed in safe_sigs — NEVER an execution-sink / // webshell / hash detection (those are gated by is_dangerous_signature()/never_downgrade and // stay at full severity even here). The in-plugins/in-themes gate above already blocks // uploads/ and the site root, and this matches only a real composer vendor// segment // for a CURATED set of well-known vendors, so an attacker-named folder does not qualify. $vendor_safe = array( 'obf_hex_func', 'obf_long_b64', 'obf_chr_concat', 'info_phpinfo', 'mailer_generic', 'tk_extract_superglobal', 'tk_dyn_superglobal_call', ); if ( strpos( $path_lower, '/vendor/' ) !== false ) { $reputable_vendors = array( 'guzzlehttp', 'guzzle', 'symfony', 'psr', 'paragonie', 'phpseclib', 'league', 'monolog', 'ramsey', 'firebase', 'composer', 'doctrine', 'sebastian', 'phpunit', 'nikic', 'react', 'ralouphie', 'fig', 'laminas', 'zendframework', 'swiftmailer', 'egulias', 'webmozart', 'graham-campbell', 'clue', 'voku', 'myclabs', 'phpoption', ); foreach ( $reputable_vendors as $rv ) { if ( strpos( $path_lower, '/vendor/' . $rv . '/' ) !== false ) { return array( 'is_library' => true, 'category' => 'composer_vendor', 'name' => $rv, 'safe_sigs' => $vendor_safe, ); } } } // Freemius SDK — ubiquitous freemium-licensing library, frequently vendored WITHOUT a // /vendor/ segment (wp-content/plugins//freemius/). It legitimately ships a debug/status // page that calls phpinfo() and handles request data. if ( strpos( $path_lower, '/freemius/' ) !== false ) { return array( 'is_library' => true, 'category' => 'composer_vendor', 'name' => 'freemius', 'safe_sigs' => $vendor_safe, ); } return array( 'is_library' => false, 'category' => null, 'name' => null, 'safe_sigs' => array() ); } /** * FP-TUNING (2026-06-30): is the signature's matched text a reference to a globally-reputable * domain? Used to suppress bare-domain "URLhaus: " threat-feed false positives * (gitlab.com / archive.org / bitbucket.org / github.com / package registries / php.net, …). * URLhaus lists specific malicious URLs, never these domains, so a file that merely references * the domain is benign. This is a TRUE-HOST check (exact host or genuine subdomain), so it * cannot be evaded by an unrelated malicious URL that merely mentions the domain in a path or * query string (e.g. http://gitlab.com.evil.com/shell → host gitlab.com.evil.com → NOT safe). * * @param string $matched The signature's matched text (a bare domain or a full URL). * @return bool */ private static function is_reputable_reference_host( $matched ) { $matched = trim( (string) $matched ); if ( '' === $matched ) { return false; } // Normalise to a host: a full URL → its parsed host; a bare "domain/path" → the authority // up to the first path/query/fragment/port delimiter. $host = ''; if ( preg_match( '#^[a-z][a-z0-9+.\-]*://#i', $matched ) ) { $host = (string) wp_parse_url( $matched, PHP_URL_HOST ); } if ( '' === $host ) { $h = preg_replace( '~^//~', '', $matched ); $h = preg_split( '~[/?#:\s]~', $h, 2 ); $host = isset( $h[0] ) ? (string) $h[0] : ''; } $host = strtolower( trim( $host, '.' ) ); if ( '' === $host || false === strpos( $host, '.' ) ) { return false; } $reputable = array( 'wordpress.org', 'w.org', 'wp.com', 'gravatar.com', 'googleapis.com', 'gstatic.com', 'google.com', 'cloudflare.com', 'jsdelivr.net', 'unpkg.com', 'jquery.com', 'facebook.com', 'twitter.com', 'linkedin.com', 'youtube.com', 'github.com', 'githubusercontent.com', 'gitlab.com', 'bitbucket.org', 'sourceforge.net', 'launchpad.net', 'packagist.org', 'npmjs.com', 'npmjs.org', 'pypi.org', 'rubygems.org', 'nuget.org', 'readthedocs.io', 'php.net', 'developer.mozilla.org', 'stackoverflow.com', 'wikipedia.org', 'wikimedia.org', 'archive.org', 'microsoft.com', 'windows.net', 'azure.com', 'apple.com', 'amazonaws.com', 'amazon.com', 'cloudfront.net', 'bootstrapcdn.com', 'fontawesome.com', 'maxcdn.com', ); foreach ( $reputable as $d ) { if ( $host === $d || ( strlen( $host ) > strlen( $d ) + 1 && substr( $host, -( strlen( $d ) + 1 ) ) === '.' . $d ) ) { return true; } } return false; } /** * FIX (audit 2026-06-10): is this a genuine code-execution / webshell / * backdoor signature that must NEVER be downgraded to a harmless severity by * attacker-controllable context (folder name, file content)? Used to gate the * library-context downgrade rules in scan_content(). * * @param string $sig_id * @param array $sig * @return bool */ private static function is_dangerous_signature( $sig_id, $sig ) { // RC-114-02 + RC-114-01 review (audit 2026-06-18): "never downgrade" is now driven // by an EXPLICIT per-signature attribute, NOT id-naming heuristics. This is a // deliberate narrowing of the RC-112 version, which used a broad ws_/bd_/obf_ // prefix + a wide token list and so also marked webshell NAME/BANNER detections // (Weevely, c99, IndoXploit…) as never-downgrade. Those banner strings legitimately // appear as DATA inside any signature database (ours and third-party security // plugins'), so marking them never-downgrade produced false positives the moment we // scanned our own signature DB. // // The correct, auditor-recommended distinction: // - ACTIVE execution sinks (eval/assert/system/exec/shell_exec/passthru/popen/ // proc_open/create_function/preg_replace-/e/file_put/fwrite/include/require of // input, @include of an .ico) carry 'never_downgrade' => true and ALWAYS report, // in any folder, filename or signature-DB context. These never appear verbatim // in a well-formed signature DB (they are stored as escaped regex), so they do // not self-FP — and a real shell hidden in a /rules/ folder still trips them. // - NAME/BANNER/family detections (webshell banners, wp_vcd, leafmailer, miners) // are NOT flagged here, so they downgrade to INFO inside a recognised signature // database (where they are detection data) but still report everywhere else. if ( ! empty( $sig['never_downgrade'] ) ) { return true; } if ( isset( $sig['semantic_type'] ) && 'execution_sink' === $sig['semantic_type'] ) { return true; } // FP-TUNING (2026-06-30): the PASSIVE structural-smell signatures obf_long_b64 (a long // base64 string) and obf_hex_func (a run of \xNN hex escapes) are NOT active execution // sinks — they describe a SHAPE that is extremely common in legitimate minified assets, CA // bundles and crypto/encoding libraries (paragonie/constant_time_encoding, phpseclib). They // were being swept into never_downgrade purely by the 'obfuscation' CATEGORY, which was // added for the ACTIVE obfuscation sinks (variable functions of request input, eval of // encoded payloads, chr-concat). Excluding them here lets the existing minified-JS / data-URI // (Rule 1) and known-library (Rule 4) downgrades apply. Their BASE severity is unchanged, so // a standalone long-base64 / hex blob in a non-library file still reports at full severity; // the ACTIVE obfuscation sinks (obf_var_func, obf_varvar_func_input, obf_serialize, // obf_gzinflate) are NOT listed here and keep their never_downgrade status. if ( in_array( $sig_id, array( 'obf_long_b64', 'obf_hex_func' ), true ) ) { return false; } // RC-114-02 review (red-team): the signature database marks every detection with // is_malware_name — TRUE for NAME/BANNER detections (c99, Weevely, wp_vcd, miners, // mailers) and FALSE for the ACTIVE sinks (passthru/system/eval/include/sqli/etc. of // input). A name/banner is detection DATA that legitimately appears inside a // signature DB, so it stays downgradable there. An ACTIVE sink in a code-execution // category at high/critical severity is a live compromise detector and must NEVER // downgrade, in any folder/filename/sig-DB context — its escaped-regex pattern does // not appear verbatim inside a signature DB, so it does not self-false-positive. if ( ! empty( $sig['is_malware_name'] ) ) { return false; } $sev = strtolower( (string) ( $sig['severity'] ?? '' ) ); if ( 'critical' !== $sev && 'high' !== $sev ) { return false; } $cat = strtolower( (string) ( $sig['category'] ?? '' ) ); // Categories whose high/critical, non-name signatures are ACTIVE code/command/ // include/write/inject/redirect sinks — they must never downgrade in any context. // Their patterns are stored as escaped regex, so they do NOT self-match inside a // signature database. CONTENT/banner categories (phishing, defacement, seo_spam, // info_disclosure, mailer, cryptominer) are deliberately EXCLUDED: those strings // legitimately appear as detection DATA inside a signature DB and must stay // downgradable there (like is_malware_name detections). $execution_cats = array( 'webshell', 'backdoor', 'shell', 'rce', 'code_injection', 'code_execution', 'code_exec', 'file_ops', 'lfi', 'rfi', 'sqli', 'deserialization', 'wp_hooks', 'network', 'ransomware', // RC-116-01: wp_malware active sinks (wpvcd_2 @include, wpadmin_1/2 admin create/grant, wp_ico). 'wp_malware', // RC-116-01 review (red-team): the previously-missed active categories — // obfuscation (variable-function of request input, eval of encoded payloads, chr-concat), js_malware // (eval(atob), document.write(unescape)) and redirect (RewriteRule -> external). 'obfuscation', 'js_malware', 'redirect', // RC-PROACTIVE (red-team sweep): the REMOTE threat-feed uses different category // spellings than the local DB for the same active sinks — add them so a // server-shipped sink is never downgradable either. 'file_operation', 'sql_injection', 'file_include', ); if ( in_array( $cat, $execution_cats, true ) ) { return true; } // RC-PROACTIVE catch-all: ANY high/critical, non-name signature whose PATTERN drives // a sink from a request superglobal ($_GET/$_POST/$_REQUEST/$_COOKIE/$_SERVER/$_FILES) // is an active input-to-execution detector and must never downgrade — independent of // whatever category spelling the (local or remote) signature used. The pattern is an // escaped regex, so this never matches verbatim inside a signature database. $pattern = (string) ( $sig['pattern'] ?? '' ); if ( '' !== $pattern && @preg_match( '/\$_\W{0,3}(?:GET|POST|REQUEST|COOKIE|SERVER|FILES)\b/', $pattern ) ) { return true; } return false; } /** * Add user-friendly explanation to finding */ private static function add_finding_explanation( &$finding, $filepath, $context_note = '' ) { $sev = strtolower( $finding['severity'] ?? 'high' ); $icons = array( 'critical' => '🔴', 'high' => '🟠', 'medium' => '🟡', 'low' => '🔵', 'info' => 'ℹ️' ); $actions = array( 'critical' => '🚨 Immediate action required', 'high' => '⚠️ Investigation required', 'medium' => '🔍 Review recommended', 'low' => '👀 Optional review', 'info' => '✅ No action needed' ); $finding['icon'] = $icons[ $sev ] ?? '🟠'; $finding['recommended_action'] = $actions[ $sev ] ?? 'Review file'; if ( ! empty( $context_note ) ) { $finding['context_note'] = $context_note; $finding['severity_adjusted'] = true; } } /** * GP-REL-001 (audit 2026-06-19): recording decision for a per-file scan result. * * The previous inline gate in ajax_scan_batch() only recorded a result when it * carried a critical/high finding OR its display risk_score crossed a per-mode * threshold (>=50 quick / >=30 deep). A genuine Medium-only signature match scores * 20 (e.g. "Modified Plugin File") and was therefore DROPPED — the file was * silently reported clean (false negative). * * This method records a result iff ANY finding has a real (non-empty) severity * other than 'info'. Every genuine signature match is low or higher, so none are * dropped; context-downgraded results (the FP/noise-suppression Rules in * scan_content set severity='info') are still NOT recorded, preserving the * existing false-positive suppression. risk_score is retained for display/ordering * only. Coverage notices, oversize findings and truncated-scan elevation do NOT * pass through here (they are added to $state['findings'] directly), so they are * unaffected. * * @param mixed $result The per-file scan result (array with 'findings') or 'clean'. * @param string $scan_type 'quick'|'deep'|'full' (kept for signature/future use; the * recording rule is intentionally scan-type independent so no * mode silently drops a real match). * @return bool True if the result should be recorded as a finding. */ private static function should_record_finding( $result, $scan_type = 'quick' ) { if ( ! is_array( $result ) || empty( $result['findings'] ) || ! is_array( $result['findings'] ) ) { return false; } foreach ( $result['findings'] as $f ) { $sev = strtolower( $f['severity'] ?? '' ); if ( '' !== $sev && 'info' !== $sev ) { return true; } } return false; } /** * ACG-103 (2026-06-30): verdict CLASS of a single finding — the axis that decides whether a * finding is a confirmed malware THREAT (red alarm) or a different kind of result. Detection is * NOT changed: every detector still fires and every finding is still recorded and shown. This * only decides which BUCKET a finding belongs to, so the "Threats Detected" count reflects real * malware — not a coverage gap, an integrity change, a suspicious location, or a low-confidence * structural smell. This fixes the model that collapsed all six finding kinds into "threat" * (programmer FP audit: should_record/generate_summary counted every non-info finding as a threat). * * malware — confirmed / high-confidence malicious: a known-malware hash, a real execution * sink (eval/system/include of request input), or a named malware family / webshell. * ONLY this class increments total_threats. * suspicious — review-worthy but ambiguous alone: PHP-in-uploads (location); a low-confidence * smell (generic mailer, bare hex names, phpinfo, assert($var), a bare extract of a * superglobal); or a sink that was vendor-library-downgraded to low. Shown for * review, NOT counted as a threat. * integrity — a file differs from its official WordPress.org checksum (core/plugin) with no * malware signature: a CHANGE to review, not malware. * coverage — the scanner could not fully inspect the file (oversize / skipped): a COVERAGE GAP. * info — informational only. * * FN-safety: the smell list below is review-only, but the MALICIOUS form of each is caught * INDEPENDENTLY and stays malware — e.g. assert($_POST[...]) / extract($_GET) feeding an * eval/include is recorded by tk_eval_request / tk_include_request (never_downgrade) at * critical/high. So reclassifying the bare smell loses no real detection (proven by harness). * * @param array $finding A single finding array (type/severity/description...). * @return string malware|suspicious|integrity|coverage|info */ private static function finding_verdict_class( $finding ) { $type = isset( $finding['type'] ) ? (string) $finding['type'] : ''; $sev = strtolower( (string) ( $finding['severity'] ?? '' ) ); if ( 'info' === $sev || '' === $sev ) { return 'info'; } switch ( $type ) { case 'hash': return 'malware'; // matched a known-malware hash — definitive case 'malwarebazaar': // ACG-105 fresh-eyes (2026-06-30): a MalwareBazaar database hit (check_file → // is_known) is a CONFIRMED known-malware identification (severity critical, // confirmed=true). It must count as a malware THREAT, exactly like a local hash // match. Without this explicit case it fell through to default→'suspicious', so a // real malware file would have been shown under the green "no malware" header. return 'malware'; case 'oversize': case 'coverage': return 'coverage'; case 'modified': case 'core': // Differs from the official checksum; any actual malware on the same file is a // SEPARATE signature finding (which is classed 'malware' on its own). return 'integrity'; case 'location': // e.g. "PHP File in Uploads" — corroborated to a threat only when the same file // ALSO carries a malware-class signature finding (counted via that finding). return 'suspicious'; case 'signature': // Low-confidence STRUCTURAL smells are review items, not confirmed malware, // regardless of display severity. Everything else on the signature path is a real // execution sink / named-malware match → malware. $smells = array( 'mailer_generic', // any $_POST near mail words — contact forms 'obf_hex_func', // bare \xNN runs — crypto/binary/encoding libs 'info_phpinfo', // phpinfo() — diagnostics 'exec_assert_var', // assert($var) — legit asserts/tests (malicious assert($_POST) → tk_eval_request) 'tk_extract_superglobal', // bare extract($_GET) — common in plugins (extract+sink → that sink is malware) // ACG-103b (2026-06-30): two more STRUCTURAL smells that flood legitimate premium // plugins / frameworks (the owner's real site: exec_eval_var on a code-insertion // plugin that evals by design; tk_dyn_superglobal_call on TGM-Plugin-Activation, // a ubiquitous library that calls a method named by the request). These are // review-worthy, not confirmed malware. FN-safe: the DANGEROUS forms are caught // independently and stay malware — eval/system/include of REQUEST input by // tk_eval_request / bd_system_input / tk_include_request, and an obfuscated // eval(base64_decode(...)) by obf_eval_b64 — all never_downgrade / not in this list. 'exec_eval_var', // eval($var) — legit code-insertion plugins (ad-inserter, code-snippets, custom-css-js) 'tk_dyn_superglobal_call', // dynamic call touching request — frameworks (TGMPA, routers) do this legitimately // ACG-107 (2026-07-01): include/require of a request-DERIVED VARIABLE (not a direct superglobal). // This is the validated-admin-page-loader pattern WordPress core (wp-admin/admin.php, update.php) // and plugins (Yoast tools.php) use — guarded by validate_file()/plugin_basename()/in_array() // allowlists the taint engine cannot see. The DIRECT form (a raw request value as the include // path) stays malware as tk_include_request (not in this list). 'tk_include_request_var', // include $var where $var came from request — validated admin-page loaders // ACG-149-129 (false-positive round, 2026-07-26): a redirect to an external site. // `header( 'Location: https://app.hubspot.com/login' ); exit;` is an OAuth hand-off; the same // three lines are a payment-gateway return, a docs link, an upgrade link, and every affiliate // link-cloaking plugin. SIX OF SEVEN realistic legitimate shapes were reported as CONFIRMED // MALWARE, including the HubSpot leadin case reported against this plugin. // Narrowing the PATTERN was tried first and withdrawn: requiring a visitor-gating token // (HTTP_USER_AGENT/HTTP_REFERER/$_COOKIE) near the redirect failed in both directions - a real // OAuth hand-off reads HTTP_REFERER for its return URL, the gate word matches inside a COMMENT // or a STRING, and `if(0){}` defeats the window. See class-signatures-database.php 2.23.0. // FN-safety, and it is total here: the pattern is UNCHANGED, so every cloak redirect this rule // ever caught is still caught and still SHOWN at `high`. Only the bucket moves - out of the red // "Threats Detected" count and into review, which is what "review-worthy but ambiguous alone" // means. A cloak's other symptoms (an eval'd dropper, an injected loader, a modified core file) // are detected independently and are not in this list. 'redir_header', // header('Location: https://…'); exit — OAuth/gateway/docs hand-offs // ACG-149-133 (round 27, R26-001): a run of chr() calls. The reviewer's sharpest finding this // round, and it is a false positive in the plainest possible form: // $x = chr( 65 ) . chr( 66 ) . chr( 67 ); // "ABC" — reported as CONFIRMED MALWARE // call_user_func( chr(115).chr(116).chr(114).chr(108).chr(101).chr(110), $_POST['cmd'] ); // The second is `strlen`. Building a string from chr() is obfuscation-FLAVOURED - minifiers, // binary/protocol code, CSV and encoding libraries all do it - and obfuscation alone is a review // item, never a confirmed threat. That distinction is the whole ACG-103/110 verdict model. // WHAT MAKES THIS FN-SAFE IS THE SAME ROUND'S OTHER HALF: `chr` is now in the pure-literal table, // so a chr() chain that spells a DANGEROUS name is decoded by the shared resolver and reported by // the TOKENIZER on its own merits (fixture CH02: chr(115).chr(121).chr(115).chr(116).chr(101). // chr(109) fires as a request-controlled system() call). The dangerous form keeps a detector; only // the shape loses its red alarm. Reclassifying before that resolver existed would have been a // straight false negative, which is why the two halves ship together. 'obf_chr_concat', // chr(..).chr(..).chr(..) — minifiers, binary and encoding libraries // ───────────────────────────────────────────────────────────────────────────────────────────── // ACG-110 (2026-07-03): PRINCIPLED completion of the smell list, driven by an empirical clean-corpus // reproduction (WordPress core 6.7.1 + CF7/TGMPA/Yoast/Elementor/WP-Super-Cache + 15 themes, 6,620 // files, ALL legitimate). Every id below matched legitimate core/plugin code and was previously // mis-bucketed as CONFIRMED MALWARE (inflating the red "Threats Detected" count). The RED bucket must // mean "proven attacker-controlled execution or a known-malware fingerprint" — NOT "a request // superglobal appears near a construct" (co-occurrence), "the code creates an admin" (behaviour), or // "a long encoded blob is present" (data shape). Each id here is review-worthy and stays SHOWN; its // genuinely-malicious FORM is caught INDEPENDENTLY by a confirmed-form signature/tokenizer id that is // NOT in this list, so reclassifying the smell loses no real detection (proven by the fixture suite: // 13/14 canonical webshells/backdoors still class malware; the one variable-hop dynamic call was // already review in v109 via tk_dyn_superglobal_call — this only makes obf_var_func consistent). 'obf_var_func', // a variable-named call with request data as the ARGUMENT (the callable is a // fixed app variable) — the argument-position twin of tk_dyn_superglobal_call // (above). The malicious form — a request value used AS the callable — stays // malware as tk_dyn_request_callee (direct) / obf_varvar_func_input. 'obf_long_b64', // a ≥500-char base64 STRING — embedded fonts/images/certs/keys/test fixtures // and WP's own built JS. Passive data shape (already excluded from // never_downgrade at is_dangerous_signature). EXECUTION of decoded content // stays malware: obf_eval_b64 / obf_eval_gz / obf_gzinflate / obf_create_func. 'sqli_direct', // a wpdb query built near request data — the flat regex cannot tell a RAW 'sqli_prepare', // query from the ubiquitous SAFE idiom that runs the same query through // wpdb prepare() with placeholders (WP core user-edit does exactly this). // A genuinely unsanitized query is still SHOWN for review; a precise // (prepare-aware) detector belongs in the tokenizer, not a red alarm // that fires on every prepared statement. 'wpadmin_1', // creating a user with the administrator role / setting the administrator 'wpadmin_2', // role — the WordPress installer + every membership/user-management plugin // does this. A real hidden-admin dropper virtually always co-trips a // request/eval/obfuscation signature (which stays malware); the bare // behaviour is review, shown. 'net_curl_post', // a curl POST whose fields come from request input — every plugin that POSTs // the user's own form data to its API. Remote-code fetch+execute stays // malware (file_include_url / file_require_url / include_http); data // transport is review. 'seo_hidden_links', // display:none + external — a MEDIUM content heuristic that also matches // legitimate template/CSS patterns; review, not a confirmed threat. ); $sig_id = ''; if ( isset( $finding['description'] ) && preg_match( '/Matches pattern:\s*([A-Za-z0-9_]+)/', (string) $finding['description'], $m ) ) { $sig_id = $m[1]; } if ( in_array( $sig_id, $smells, true ) ) { return 'suspicious'; } // A sink actively downgraded to low/info (vendor allow-list / FP rule) is review, // not a threat — e.g. tk_dyn_superglobal_call inside guzzle/symfony. if ( 'low' === $sev ) { return 'suspicious'; } return 'malware'; default: return 'suspicious'; } } public static function init() { add_action( 'wp_ajax_guardpress_malware_scan_init', array( __CLASS__, 'ajax_init_scan' ) ); add_action( 'wp_ajax_guardpress_malware_scan_batch', array( __CLASS__, 'ajax_scan_batch' ) ); add_action( 'wp_ajax_guardpress_malware_scan_finalize', array( __CLASS__, 'ajax_finalize_scan' ) ); add_action( 'wp_ajax_guardpress_malware_scan_cancel', array( __CLASS__, 'ajax_cancel_scan' ) ); } // ==================== CHECKSUMS API ==================== /** * PERF-118-02 (audit 2026-06-18): network circuit breaker for the WordPress.org * checksum APIs. When the network is down/firewalled/slow, a cold scan would otherwise * issue one synchronous request PER core + PER plugin (each up to 30s/15s), serially, * adding minutes of wall-clock. After NET_FAIL_TRIP connection-level failures in this * request we OPEN the breaker: every later checksum fetch returns "unavailable" * immediately (no network), and the file simply falls back to content scanning — exactly * the existing offline behaviour. The empty result is still short-cached so subsequent * batches don't retry. Timeouts were also cut (30/15 -> 7s) so even pre-trip calls are bounded. */ const NET_TIMEOUT = 7; const NET_FAIL_TRIP = 2; private static $net_fail_count = 0; private static $net_circuit_open = false; private static function note_network_failure() { self::$net_fail_count++; if ( self::$net_fail_count >= self::NET_FAIL_TRIP ) { self::$net_circuit_open = true; } self::net_breaker_save(); // RC-120-03: persist so the breaker survives the next batch/process } /** * RC-120-03 (audit 2026-06-19): the WordPress.org checksum breaker is static in-memory, so * each AJAX batch (a fresh PHP process) would otherwise start it CLOSED and re-pay two fresh * timeouts on a down/firewalled host EVERY batch. We now persist it at the SOURCE in the * per-scan file store: every get_*_checksums() call rehydrates it first (so even a direct * caller, not just ajax_scan_batch, honours it), and note_network_failure() writes it back. * It resets only when a NEW scan starts — ajax_init_scan deletes the 'net_breaker' key — so * a service that failed stays "open" (offline content-scan fallback) for the rest of THIS * scan but is retried on the next one. */ private static $net_breaker_loaded = false; private static function net_breaker_load() { if ( self::$net_breaker_loaded ) { return; } self::$net_breaker_loaded = true; $b = self::load_scan_data( 'net_breaker', null ); if ( is_array( $b ) ) { self::$net_fail_count = (int) ( $b['count'] ?? 0 ); self::$net_circuit_open = ! empty( $b['open'] ); } } private static function net_breaker_save() { self::save_scan_data( 'net_breaker', array( 'count' => self::$net_fail_count, 'open' => self::$net_circuit_open, ) ); } /** * RC-120-03 fix (red-team 2026-06-19): clear the persisted breakers AND reset the in-memory * statics at the START of a new scan — BEFORE the init-phase core checks (get_core_checksums * / check_core_integrity) run. cleanup_scan_data() also deletes these keys, but it runs LATER * in ajax_init_scan (after those checks); an ABANDONED prior scan (one that never reached * cleanup) during a network outage could otherwise rehydrate a stale OPEN breaker here and * suppress this scan's upfront core checksum verification. Latching $net_breaker_loaded=true * stops net_breaker_load() from re-reading the file we just deleted, so the breaker stays * CLOSED for this scan's init and the network is retried. */ public static function reset_net_breaker() { self::$net_fail_count = 0; self::$net_circuit_open = false; self::$net_breaker_loaded = true; self::delete_scan_data( 'net_breaker' ); self::delete_scan_data( 'mb_breaker' ); } /** * RC-119-04 (audit 2026-06-18): classify a wp_remote_* response as a TRANSIENT failure * for circuit-breaker purposes. A fast 503/429 or a malformed body is just as much a * "service unavailable" signal as a timeout — counting only WP_Error let a service that * answered quickly with 503/429/garbage be hammered up to the per-item cap. A definitive * 404 (no checksums for this plugin / hash-not-found) is NOT a failure and is handled by * the caller. Pass $body_ok=false to also treat an unparseable JSON body as transient. */ private static function http_is_transient_failure( $response ) { if ( is_wp_error( $response ) ) { return true; } $code = (int) wp_remote_retrieve_response_code( $response ); return ( 429 === $code || $code >= 500 ); } private static function get_core_checksums() { self::net_breaker_load(); // RC-120-03: rehydrate the persisted breaker before any fetch $version = get_bloginfo( 'version' ); $locale = get_locale(); $cache_key = 'core_' . $version . '_' . $locale; $cached = self::get_cached_checksums( $cache_key ); if ( $cached !== false ) return $cached; // PERF-118-02: breaker open -> treat as unavailable (offline content-scan fallback). if ( self::$net_circuit_open ) { return array(); } $response = wp_remote_get( 'https://api.wordpress.org/core/checksums/1.0/?version=' . $version . '&locale=' . $locale, array( 'timeout' => self::NET_TIMEOUT ) ); $checksums = array(); if ( self::http_is_transient_failure( $response ) ) { self::note_network_failure(); // RC-119-04: timeout/429/5xx all trip the breaker } else { $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $body ) ) { self::note_network_failure(); // RC-119-04: malformed JSON = transient failure } else { $checksums = $body['checksums'] ?? array(); } } if ( empty( $checksums ) && $locale !== 'en_US' && ! self::$net_circuit_open ) { $response = wp_remote_get( 'https://api.wordpress.org/core/checksums/1.0/?version=' . $version . '&locale=en_US', array( 'timeout' => self::NET_TIMEOUT ) ); if ( self::http_is_transient_failure( $response ) ) { self::note_network_failure(); } else { $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $body ) ) { self::note_network_failure(); } else { $checksums = $body['checksums'] ?? array(); } } } self::cache_checksums( $cache_key, $checksums ); return $checksums; } private static function get_plugin_checksums( $plugin_slug, $version ) { self::net_breaker_load(); // RC-120-03: rehydrate the persisted breaker before any fetch $cache_key = 'plugin_' . $plugin_slug . '_' . $version; $cached = self::get_cached_checksums( $cache_key ); if ( $cached !== false ) return $cached; // PERF-118-02: breaker open -> unavailable now; short-cache so we don't retry it. if ( self::$net_circuit_open ) { self::cache_checksums( $cache_key, array() ); return array(); } $response = wp_remote_get( 'https://downloads.wordpress.org/plugin-checksums/' . $plugin_slug . '/' . $version . '.json', array( 'timeout' => self::NET_TIMEOUT ) ); // RC-119-04: timeout/429/5xx trip the breaker; a definitive 404 (plugin not on // WordPress.org) does NOT — it is a final answer, not a transient failure. if ( self::http_is_transient_failure( $response ) ) { self::note_network_failure(); self::cache_checksums( $cache_key, array() ); return array(); } if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { self::cache_checksums( $cache_key, array() ); // 404 etc. — final, no breaker return array(); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $body ) ) { self::note_network_failure(); // RC-119-04: malformed JSON = transient failure self::cache_checksums( $cache_key, array() ); return array(); } $checksums = array(); if ( ! empty( $body['files'] ) ) { foreach ( $body['files'] as $file => $hashes ) { $checksums[ $file ] = $hashes['md5'] ?? ''; } } self::cache_checksums( $cache_key, $checksums ); return $checksums; } private static function get_cached_checksums( $key ) { // BINLOG FIX (v8.2): Moved from get_option() to File Storage. // Before: Each call loaded ~50-100KB from DB. Each write = UPDATE wp_options → binlog. // 20 plugins × 100KB = 2MB binlog per scan. // After: File read/write in guardpress-data/cache/ — zero binlog impact. if ( self::$checksums_option_cache === null ) { if ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'checksums-cache', null, 'cache' ); self::$checksums_option_cache = is_array( $loaded ) ? $loaded : array(); } else { self::$checksums_option_cache = get_option( self::OPTION_CHECKSUMS_CACHE, array() ); } } if ( isset( self::$checksums_option_cache[ $key ] ) && self::$checksums_option_cache[ $key ]['expires'] > time() ) { return self::$checksums_option_cache[ $key ]['data']; } return false; } private static function cache_checksums( $key, $data ) { // BINLOG FIX: Write to file ONLY — no DB fallback for cache data. if ( self::$checksums_option_cache === null ) { if ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'checksums-cache', null, 'cache' ); self::$checksums_option_cache = is_array( $loaded ) ? $loaded : array(); } else { // File_Storage not available — use in-memory only for this request self::$checksums_option_cache = array(); } } // M-108-03 (audit 2026-06-17): a SUCCESSFUL checksum set is cached for the // full duration, but a FAILED fetch (empty result from WP_Error / non-200 / // bad JSON) is cached only briefly, so official verification resumes within // minutes of the network coming back instead of being suppressed for a day. $ttl = empty( $data ) ? ( 15 * MINUTE_IN_SECONDS ) : self::CACHE_DURATION; self::$checksums_option_cache[ $key ] = array( 'data' => $data, 'expires' => time() + $ttl ); if ( count( self::$checksums_option_cache ) > 100 ) { self::$checksums_option_cache = array_slice( self::$checksums_option_cache, -50, null, true ); } // Save to file only. If file storage fails, cache stays in memory for this request // and will be re-fetched from WordPress.org API on next scan (24h cache duration). if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::save( 'checksums-cache', self::$checksums_option_cache, 'cache' ); } } // ==================== FILE CLASSIFICATION ==================== /** * Single source of truth for PHP-family (server-executable) extensions. * RC-108-01 (audit 2026-06-17): the scan walker, scan_file_uncached, the core * integrity check, the Manual Verify tool and the quarantine logic MUST all use * the SAME list — otherwise a file like shell.pht / shell.php8 slips past the * path that has the shorter list (the original bug: the walker scanned only * php/phtml/php5/php7/phar, so .pht/.php8/.phps/.inc in uploads were invisible). * * @return string[] */ public static function php_family_exts() { return array( 'php', 'phtml', 'php3', 'php4', 'php5', 'php7', 'php8', 'phar', 'pht', 'phps', 'inc' ); } /** * RC-111-04: does a filename carry a PHP-family suffix ANYWHERE in its * multi-extension chain (not just the last extension)? Apache evaluates every * extension in a name, so "shell.php.jpg" can execute as PHP even though its * last extension is .jpg. PATHINFO_EXTENSION only sees the last one, so the * deep-scan walker must also enqueue files whose name contains a PHP-family * suffix earlier in the chain. * * @param string $filename basename only * @return bool */ public static function has_php_family_suffix( $filename ) { $parts = explode( '.', strtolower( $filename ) ); array_shift( $parts ); // drop the base name; keep only the extension parts if ( empty( $parts ) ) { return false; } $php = self::php_family_exts(); foreach ( $parts as $p ) { if ( in_array( $p, $php, true ) ) { return true; } } return false; } /** * The PHP files WordPress ships in the site ROOT (not wp-admin / wp-includes). * @return string[] */ public static function core_root_files() { return array( 'index.php', 'wp-activate.php', 'wp-blog-header.php', 'wp-comments-post.php', 'wp-config-sample.php', 'wp-cron.php', 'wp-links-opml.php', 'wp-load.php', 'wp-login.php', 'wp-mail.php', 'wp-settings.php', 'wp-signup.php', 'wp-trackback.php', 'xmlrpc.php' ); } // ---- Execution-chain detection patterns (single source; RC-107-02 / RC-109-02) ---- // Used by BOTH check_core_integrity() (core folders) and the deep-scan walker // (non-core: uploads, wp-content) so the ".htaccess maps an asset to PHP + // asset-contains-PHP" chain is detected the same way everywhere. public static function exec_chain_config_names() { return array( '.htaccess', '.user.ini', 'user.ini', 'web.config' ); } // Inert asset types that can hide a PHP payload behind a handler chain. The CORE // variant keeps html/htm (WordPress ships none inside wp-admin/wp-includes, so any // is suspect); the NON-CORE variant drops html/htm/svg because the deep-scan walker // already content-scans those per-file (including them here would double-count — // RC-109-02). RC-110 (audit 2026-06-17) added tiff/tif/jfif. public static function exec_chain_asset_exts() { return array( 'ico', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif', 'jfif', 'html', 'htm' ); } public static function exec_chain_noncore_asset_exts() { return array( 'ico', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'tiff', 'tif', 'jfif' ); } // Executable-handler directives that genuinely route a resource through the PHP // interpreter (Apache / PHP-ini / IIS). DELIBERATELY STRICT: AddHandler/AddType/ // SetHandler/ForceType/Action must be followed by a php/x-httpd token, and the bare // "RewriteRule ... .php" form is NOT matched — it routes to index.php on every // pretty-permalinks site, so matching it false-positived the stock root .htaccess // (RC-109-02 defect #1). A benign "deny from all", "AddType image/webp .webp", or // "php_value upload_max_filesize 64M" does NOT match. public static function exec_chain_handler_re() { return '/AddHandler\s+\S*(?:php|x-httpd)|AddType\s+\S*(?:php|x-httpd)|SetHandler\s+\S*(?:php|x-httpd)|ForceType\s+\S*(?:php|x-httpd)|Action\s+\S*php|auto_prepend_file|auto_append_file|x-httpd-php|x-httpd-fastphp|application\/x-httpd|scriptProcessor\s*=\s*"[^"]*php|php_(?:admin_)?(?:value|flag)\s+engine\s+on|httpHandlers|fileExtensionHandlers/i'; } // PHP payload markers (full tag, echo short tag, whitespace short tag — won't // match " form). // RC-112-04 (audit 2026-06-18): also catch the short-open-tag-then-comment forms // "]{0,40}language\s*=\s*["\']?php/i'; } // PERF-116-01 (perf audit 2026-06-18): directives that route ARBITRARY files // (not a specific extension list) through the PHP interpreter — SetHandler/ // ForceType apply to EVERY file in their container, Action maps a media handler, // and the IIS wildcard path / legacy handler sections grant PHP broadly. ONLY // these warrant scope-scanning the whole inert-asset universe, because only here // can a non-PHP file (shell.jpg) execute. A plain "AddHandler …php .php .php8" // (the cPanel/LiteSpeed default injected into .htaccess) or an "auto_prepend_file" // (Wordfence .user.ini) does NOT make any non-PHP file executable — those mapped // .php files are already content-scanned by the walker, and the prepend target is // resolved+scanned directly — so scope-scanning megabytes of images for them is // pure waste (the audit measured up to ~10 GiB of hidden reads). NOTE: the mime // token "x-httpd"/"application/x-httpd" is DELIBERATELY excluded here — it also // appears in benign "AddHandler application/x-httpd-eaXX .php" lines. public static function exec_chain_broad_handler_re() { return '/SetHandler\s+\S*(?:php|x-httpd)|ForceType\s+\S*(?:php|x-httpd)|Action\s+\S*php|scriptProcessor\s*=\s*"[^"]*php|path\s*=\s*"\*(?:\.\*)?"|httpHandlers|fileExtensionHandlers/i'; } /** * PERF-116-01 / RC-118-02: resolve the chain scope-scan plan for a candidate * handler config: * 'exts' => string[] the explicit inert extensions the config maps to PHP * (e.g. ['ico']); [] for a PHP-only / auto_prepend-only / * engine-only directive (nothing extra to scan). * 'all' => bool true for a genuinely BROAD handler (SetHandler/ForceType/ * Action/IIS wildcard) where EVERY file in scope executes as * PHP — the caller then scope-scans every non-walker file * (incl. extensionless and .txt/.dat), not just images. * When both are empty/false the caller skips the recursive scope read entirely. * This never reduces detection: a skip happens only when no non-PHP file can run. * * @param string $content config file head (already read, up to 1 MB) * @return array{exts:string[],all:bool} */ private static function exec_chain_scope_plan( $content ) { return array( 'exts' => self::exec_chain_mapped_exts( $content ), // explicit non-PHP inert exts 'all' => (bool) preg_match( self::exec_chain_broad_handler_re(), (string) $content ), ); } /** * RC-110-02: does an asset file contain a PHP execution marker ANYWHERE in the * first MAX_FILE_SIZE bytes — not just the first 64 KB. A file under a handler * chain executes wholesale as PHP, so a payload hidden behind padding must still * be found. $oversize is set true (by reference) when the file is larger than the * cap and was only partially read, so the caller treats it as suspicious/truncated * rather than clean. * * @param string $abs absolute file path * @param bool $oversize OUT: true when file exceeds MAX_FILE_SIZE * @return bool true when a PHP marker was found within the bytes read */ private static function asset_contains_php_marker( $abs, &$oversize ) { $oversize = false; // ACG-086 sweep (audit 2026-06-28): never read an asset THROUGH a symlink component or from a non-regular file // (FIFO would HANG). Unsafe path → no marker (it is a coverage gap already counted at discovery). if ( ! self::is_safe_regular_file( $abs ) ) { return false; } $size = @filesize( $abs ); if ( false !== $size && $size > self::MAX_FILE_SIZE ) { $oversize = true; } $data = (string) @file_get_contents( $abs, false, null, 0, self::MAX_FILE_SIZE ); if ( '' === $data ) { return false; } return (bool) preg_match( self::exec_chain_php_marker_re(), $data ); } /** * Extract the inert file extensions a server-config maps to the PHP interpreter, * e.g. "AddHandler application/x-httpd-php .ico .jpg" -> [ico,jpg]; * web.config path="*.ico" -> [ico]; -> [ico]. PHP-family and * already-content-scanned types (html/htm/js/svg/css/...) are dropped — the walker * scans those per-file regardless. Returns [] when the config grants PHP broadly * (auto_prepend_file, bare SetHandler/ForceType) with no explicit inert extension, * in which case the caller falls back to the full inert-asset universe. * * @param string $content config file head * @return string[] lowercased extensions */ private static function exec_chain_mapped_exts( $content ) { $exts = array(); $collect = function( $haystack_matches ) use ( &$exts ) { foreach ( $haystack_matches as $tail ) { if ( preg_match_all( '/\.([A-Za-z0-9]{1,8})\b/', $tail, $em ) ) { foreach ( $em[1] as $e ) { $exts[ strtolower( $e ) ] = true; } } } }; // Apache AddHandler/AddType/SetHandler/ForceType .ext .ext2 if ( preg_match_all( '/(?:AddHandler|AddType|SetHandler|ForceType)\s+\S*(?:php|x-httpd)\S*\s+([^\r\n]+)/i', $content, $m ) ) { $collect( $m[1] ); } // Apache / blocks. RC-112-04 (audit // 2026-06-18): the directive argument may be double-quoted, single-quoted, or // UNQUOTED (e.g. ). The old regex matched the double-quoted // form only, so a single/unquoted FilesMatch that maps a NON-image extension // (outside the inert-image fallback universe) was never extracted and its // payload was missed. if ( preg_match_all( '/]+))/i', $content, $fm ) ) { $collect( array_merge( $fm[1], $fm[2], $fm[3] ) ); } // IIS web.config: the mapped extension lives in fileExtension="..." or in a // path="*.ext" wildcard — NOT in a path that points at the PHP executable // (e.g. path="C:\PHP\php-cgi.exe"). RC-111-02.2: extract fileExtension, and from // path= ONLY the "*.ext" wildcard form, so the .exe processor is never mistaken // for the target extension. if ( preg_match_all( '/fileExtension\s*=\s*"([^"]+)"/i', $content, $fe ) ) { $collect( $fe[1] ); } if ( preg_match_all( '/path\s*=\s*"([^"]*\*\.[^"]*)"/i', $content, $pm ) ) { foreach ( $pm[1] as $pv ) { if ( preg_match_all( '/\*\.([A-Za-z0-9]{1,8})\b/', $pv, $pe ) ) { foreach ( $pe[1] as $e ) { $exts[ strtolower( $e ) ] = true; } } } } // RC-111-02.1: drop ONLY the types the deep-scan walker already content-scans // per file (PHP-family + html/htm/js/svg) — re-scanning those in chain scope // would double-count. Do NOT drop txt/css/json/xml/etc: the walker does NOT // scan those, so when a config explicitly maps one to PHP it must be scanned in // the chain scope or the payload (e.g. shell.txt run as PHP) is missed. $drop = array_merge( self::php_family_exts(), array( 'html', 'htm', 'js', 'svg' ) ); foreach ( $drop as $d ) { unset( $exts[ $d ] ); } return array_keys( $exts ); } /** * RC-110-01: scan a handler-config's SCOPE for asset files that hide a PHP payload. * Apache .htaccess, PHP .user.ini and IIS web.config all cascade to SUBdirectories, * so the scope is $root AND its descendants — but BOUNDED (the auditor's explicit * requirement): at most $MAX_DIRS directories and $MAX_ASSETS asset files, each read * up to MAX_FILE_SIZE (RC-110-02). Core dirs are skipped (check_core_integrity owns * them); symlinked dirs are not followed (loop / scope-escape guard). * * @param string $root directory containing the config (scan from here down) * @param string[] $exts asset extensions to inspect * @param string $core_root normalized ABSPATH (for relative paths) * @param string[] $core_prefixes core dir prefixes to skip * @param bool $limited OUT: true when a bound was hit (some assets unscanned) * @return array rel-path => finding */ private static function scan_chain_scope_for_payloads( $root, $exts, $core_root, $core_prefixes, &$limited, &$global_left = null, $skip_core = true, $scan_all = false ) { $found = array(); $limited = false; $MAX_DIRS = 3000; $MAX_ASSETS = 1500; // RC-118-02 (audit 2026-06-18): under a BROAD handler (SetHandler/ForceType/Action/ // IIS wildcard) EVERY file in scope executes as PHP — not just images. In $scan_all // mode we therefore inspect every regular file whose extension is NOT already // content-scanned by the file walker (php-family + html/htm/js/svg), INCLUDING // extensionless files (e.g. a planted "shell" with no extension) and .txt/.dat. The // dir/asset/global bounds + realpath containment below still apply, so this stays // bounded and a hit surfaces a coverage warning if a bound is reached. $walker_covered = $scan_all ? array_merge( self::php_family_exts(), array( 'html', 'htm', 'js', 'svg' ) ) : array(); $stack = array( $root ); $dir_count = 0; $asset_count = 0; while ( $stack ) { $d = array_pop( $stack ); if ( ++$dir_count > $MAX_DIRS ) { $limited = true; break; } $entries = @scandir( $d ); if ( ! is_array( $entries ) ) { continue; } foreach ( $entries as $e ) { if ( '.' === $e || '..' === $e ) { continue; } $p = $d . '/' . $e; if ( is_dir( $p ) ) { if ( is_link( $p ) ) { continue; } // RC-116-04: when invoked FOR a core config (skip_core=false) we must // descend into core subdirs too, so a core handler-config's scope is // inspected with the same engine as non-core. The realpath/ABSPATH // containment below still prevents escaping the site tree. if ( $skip_core && ( 0 === strpos( wp_normalize_path( $p ) . '/', $core_prefixes[0] ) || 0 === strpos( wp_normalize_path( $p ) . '/', $core_prefixes[1] ) ) ) { continue; } $stack[] = $p; continue; } if ( ! is_file( $p ) ) { continue; } if ( is_link( $p ) ) { continue; } // RC-111-07: never read a symlinked file in chain scope $ext = strtolower( pathinfo( $e, PATHINFO_EXTENSION ) ); if ( $scan_all ) { // Broad handler: inspect everything EXCEPT what the walker already scans. if ( in_array( $ext, $walker_covered, true ) ) { continue; } } else { // Explicit mapping: only the inert extensions the config maps to PHP. if ( ! in_array( $ext, $exts, true ) ) { continue; } } // RC-111-07: realpath containment — only read assets that genuinely // resolve inside ABSPATH, so a crafted link/junction cannot redirect a // read outside the site tree. $real = @realpath( $p ); // RC-112-04 review: containment must use a trailing-slash prefix so a sibling // dir whose path merely STARTS with the site path (e.g. /var/www/html-evil) // cannot pass as "inside" /var/www/html. if ( false === $real || 0 !== strpos( wp_normalize_path( $real ), rtrim( $core_root, '/' ) . '/' ) ) { continue; } if ( ++$asset_count > $MAX_ASSETS ) { $limited = true; break 2; } if ( null !== $global_left ) { if ( $global_left <= 0 ) { $limited = true; break 2; } // RC-111-06: global budget exhausted $global_left--; } $oversize = false; $hit = self::asset_contains_php_marker( $p, $oversize ); if ( $hit || $oversize ) { $rel = ltrim( str_replace( $core_root, '', wp_normalize_path( $p ) ), '/' ); $found[ $rel ] = array( 'file' => $rel, 'location' => 'exec_chain', 'severity' => ( $hit ? 'high' : 'medium' ) ); } } } return $found; } /** * RC-112-04 (audit 2026-06-18): resolve auto_prepend_file / auto_append_file * targets declared in a server-config body and return the ones that point at a * NON-php-family file inside the site which actually contains a PHP payload. * * Such a target is executed as PHP on EVERY request regardless of its extension * (e.g. a planted shell.txt referenced by `php_value auto_prepend_file ...`), so * it is a real back-door that the inert-image scope scan would never look at. We * deliberately IGNORE .php-family targets: those are scanned by the normal file * walker and are also the legitimate form (e.g. a WAF prepend), so flagging them * here would false-positive. Targets that resolve OUTSIDE ABSPATH (typical of APM * agents like New Relic) are ignored for the same reason. * * @param string $cfg_body config head already read by the caller * @param string $cfg_dir directory containing the config (for relative targets) * @param string $core_root normalized ABSPATH (containment + relative paths) * @return array rel-path => finding */ private static function scan_auto_prepend_targets( $cfg_body, $cfg_dir, $core_root ) { $found = array(); if ( ! preg_match_all( '/(?:auto_prepend_file|auto_append_file)\s*=?\s*(?:"([^"]+)"|\'([^\']+)\'|(\S+))/i', $cfg_body, $m, PREG_SET_ORDER ) ) { return $found; } $php_family = self::php_family_exts(); foreach ( $m as $set ) { $target = ''; if ( isset( $set[1] ) && '' !== $set[1] ) { $target = $set[1]; } elseif ( isset( $set[2] ) && '' !== $set[2] ) { $target = $set[2]; } elseif ( isset( $set[3] ) ) { $target = $set[3]; } $target = trim( rtrim( trim( $target ), "\"');" ) ); if ( '' === $target || 'none' === strtolower( $target ) ) { continue; } // Resolve absolute vs relative (relative is to the config's own directory). $is_abs = ( '/' === substr( $target, 0, 1 ) || (bool) preg_match( '#^[A-Za-z]:[\\\\/]#', $target ) ); $candidate = $is_abs ? $target : ( $cfg_dir . '/' . $target ); $real = @realpath( $candidate ); if ( false === $real ) { continue; } $real_n = wp_normalize_path( $real ); // Trailing-slash containment so /var/www/html-evil cannot pass as inside /var/www/html. if ( 0 !== strpos( $real_n, rtrim( $core_root, '/' ) . '/' ) ) { continue; } // outside the site tree if ( @is_link( $real ) || ! @is_file( $real ) ) { continue; } $ext = strtolower( pathinfo( $real_n, PATHINFO_EXTENSION ) ); if ( in_array( $ext, $php_family, true ) ) { continue; } // .php prepend → walker / legit infra $oversize = false; if ( self::asset_contains_php_marker( $real, $oversize ) || $oversize ) { $rel = ltrim( str_replace( $core_root, '', $real_n ), '/' ); $found[ $rel ] = array( 'file' => $rel, 'location' => 'exec_chain', 'severity' => 'high' ); } } return $found; } private static function classify_file( $filepath ) { $filepath = str_replace( '\\', '/', $filepath ); $abspath = str_replace( '\\', '/', rtrim( ABSPATH, '/\\' ) ); $content_dir = str_replace( '\\', '/', WP_CONTENT_DIR ); if ( strpos( $filepath, $abspath . '/wp-admin/' ) === 0 || strpos( $filepath, $abspath . '/wp-includes/' ) === 0 ) { return array( 'type' => 'core', 'relative' => str_replace( $abspath . '/', '', $filepath ) ); } $core_root_files = self::core_root_files(); $filename = basename( $filepath ); if ( dirname( $filepath ) === $abspath && in_array( $filename, $core_root_files, true ) ) { return array( 'type' => 'core', 'relative' => $filename ); } if ( strpos( $filepath, $content_dir . '/plugins/' ) === 0 ) { $relative = str_replace( $content_dir . '/plugins/', '', $filepath ); $parts = explode( '/', $relative ); $slug = $parts[0]; $version = self::get_plugin_version( $slug ); return array( 'type' => 'plugin', 'slug' => $slug, 'version' => $version, 'relative' => implode( '/', array_slice( $parts, 1 ) ) ); } if ( strpos( $filepath, $content_dir . '/themes/' ) === 0 ) { $relative = str_replace( $content_dir . '/themes/', '', $filepath ); $parts = explode( '/', $relative ); $slug = $parts[0]; $theme = wp_get_theme( $slug ); $version = $theme->exists() ? $theme->get( 'Version' ) : ''; return array( 'type' => 'theme', 'slug' => $slug, 'version' => $version, 'relative' => implode( '/', array_slice( $parts, 1 ) ) ); } if ( strpos( $filepath, $content_dir . '/uploads/' ) !== false ) { return array( 'type' => 'uploads' ); } if ( strpos( $filepath, $content_dir . '/mu-plugins/' ) === 0 ) { return array( 'type' => 'mu-plugin' ); } return array( 'type' => 'unknown' ); } private static function get_plugin_version( $plugin_slug ) { // PERF FIX (v8.2): Cache version per slug — avoids repeated glob()+get_file_data() // for every file in the same plugin (e.g. WooCommerce has 500+ PHP files, // each calling this with slug='woocommerce'). static $version_cache = array(); if ( isset( $version_cache[ $plugin_slug ] ) ) { return $version_cache[ $plugin_slug ]; } $plugin_dir = WP_CONTENT_DIR . '/plugins/' . $plugin_slug; $files = array( $plugin_dir . '/' . $plugin_slug . '.php' ); $glob = glob( $plugin_dir . '/*.php' ); if ( $glob ) $files = array_merge( $files, $glob ); foreach ( $files as $file ) { if ( ! file_exists( $file ) ) continue; $data = get_file_data( $file, array( 'Version' => 'Version', 'Plugin Name' => 'Plugin Name' ) ); if ( ! empty( $data['Plugin Name'] ) && ! empty( $data['Version'] ) ) { $version_cache[ $plugin_slug ] = $data['Version']; return $data['Version']; } } $version_cache[ $plugin_slug ] = ''; return ''; } // ==================== SIGNATURES ==================== private static function _d( $e ) { static $cache = array(); if ( ! isset( $cache[ $e ] ) ) { $cache[ $e ] = base64_decode( $e ); } return $cache[ $e ]; } /** * FIX (audit 2026-06-10): collect the signature sets that ship with the * plugin but were never merged into the active scan (Extended + Threat-Intel). * Guarded so a missing/renamed class can never fatal the scan. * * @return array */ private static function collect_extra_signature_sets() { // FIX (FP-regression 2026-06-11): DISABLED. These heuristic signature // sets — GuardPress_Extended_Signatures + GuardPress_Threat_Intel_Signatures // (OTX / MalwareBazaar / URLhaus style patterns) + GuardPress_YARA_Signatures, // ~691 patterns total — were "wired in" during the 2026-06-10 audit on the // assumption that the false-positive-prevention layer would bound their // noise. In practice it does not: they fire en masse on legitimate // third-party Composer libraries (firebase/php-jwt, google/auth, guzzlehttp, // monolog, paragonie/constant_time_encoding, phpseclib) bundled inside // popular plugins. A single Ad-Inserter-Pro install produced ~500 HIGH // "threats" — every one a false positive. The patterns are inherently // low-precision: "XOR String" (bd_xor), "Pack Hex" (bd_pack), "SQLi Sleep" // (cve_sqli), "PregCallback" (mb_pat), "Phishing.Brand.Google" (otx_phi), // "Random Var Names" (pack_obf) all match ordinary crypto / encoding / HTTP // library code. Different sites run different plugins, so this hits everyone. // // The scanner now uses the SAME precise signature scope that v1.0.1 shipped // and that NEVER false-positived this way: the built-in code-execution // signatures (eval/exec/shell/system of request input, known webshells), // the full GuardPress_Signatures_Database (98+ vetted patterns) and the // GuardPress_Threat_Feed (real malware hashes / URLs). Real malware is still // caught by those; the noisy heuristics are not loaded into the scan. // // The classes stay loaded (other modules may reference them) and can be // re-introduced ONLY behind per-signature FP-prevention (require // corroboration, or cap to 'low' inside library/vendor paths). return array(); } private static function get_signatures() { // AV-SAFE (2026-06-19): every built-in signature (pattern AND display name) is // stored as ONE base64-encoded JSON blob and decoded in memory, so this DETECTION // file contains no literal malware code/names that a server antivirus (Defender, // ClamAV, Imunify360…) would flag as a backdoor and truncate. Byte-identical decode. $builtin = json_decode( self::_d( 'W3siaWQiOiJ3c19jOTkiLCJuYW1lIjoiQzk5IFNoZWxsIiwicGF0dGVybiI6Ii9cXGJjOTlzaGVsbFxcYnxcXGJjOTlfYnVmZl9wcmVwYXJlXFxiL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIn0seyJpZCI6IndzX3I1NyIsIm5hbWUiOiJSNTcgU2hlbGwiLCJwYXR0ZXJuIjoiL1xcYnI1N3NoZWxsXFxifFxcYnI1N19wd2RfZm9ybVxcYi9pIiwic2V2ZXJpdHkiOiJjcml0aWNhbCJ9LHsiaWQiOiJ3c193c28iLCJuYW1lIjoiV1NPIFNoZWxsIiwicGF0dGVybiI6Ii9XU09cXHMrXFxkK1xcLlxcZCt8d3NvX3ZlcnNpb25cXHMqPXxXZWJcXHMqU2hlbGxcXHMqYnlcXHMqb1JiL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIn0seyJpZCI6IndzX2IzNzRrIiwibmFtZSI6IkIzNzRLIFNoZWxsIiwicGF0dGVybiI6Ii9cXGJiMzc0a1xcYi4qc2hlbGx8YjM3NGtfY29uZmlnL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIn0seyJpZCI6IndzX2FsZmEiLCJuYW1lIjoiQWxmYSBTaGVsbCIsInBhdHRlcm4iOiIvQWxmYVxccypTaGVsbFxccyp2XFxkfEFsZmFUZWFtL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIn0seyJpZCI6IndzX2ZpbGVzbWFuIiwibmFtZSI6IkZpbGUgTWFuYWdlciBTaGVsbCIsInBhdHRlcm4iOiIvRmlsZXNNYW58RmlsM3NNNG4vaSIsInNldmVyaXR5IjoiY3JpdGljYWwifSx7ImlkIjoib2JmX2V2YWxfYjY0IiwibmFtZSI6IkV2YWwgQmFzZTY0IiwicGF0dGVybiI6Ii9cXGJldmFsXFxzKlxcKFxccypiYXNlNjRfZGVjb2RlXFxzKlxcKC9pIiwic2V2ZXJpdHkiOiJjcml0aWNhbCIsIm5ldmVyX2Rvd25ncmFkZSI6dHJ1ZX0seyJpZCI6Im9iZl9ldmFsX2d6IiwibmFtZSI6IkV2YWwgR3ppbmZsYXRlIiwicGF0dGVybiI6Ii9cXGJldmFsXFxzKlxcKFxccypnemluZmxhdGVcXHMqXFwoL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIiwibmV2ZXJfZG93bmdyYWRlIjp0cnVlfSx7ImlkIjoib2JmX2V2YWxfZ3p1IiwibmFtZSI6IkV2YWwgR3p1bmNvbXByZXNzIiwicGF0dGVybiI6Ii9cXGJldmFsXFxzKlxcKFxccypnenVuY29tcHJlc3NcXHMqXFwoL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIiwibmV2ZXJfZG93bmdyYWRlIjp0cnVlfSx7ImlkIjoib2JmX2V2YWxfcm90MTMiLCJuYW1lIjoiRXZhbCBTdHJfcm90MTMiLCJwYXR0ZXJuIjoiL1xcYmV2YWxcXHMqXFwoXFxzKnN0cl9yb3QxM1xccypcXCgvaSIsInNldmVyaXR5IjoiY3JpdGljYWwiLCJuZXZlcl9kb3duZ3JhZGUiOnRydWV9LHsiaWQiOiJvYmZfY3JlYXRlX2Z1bmMiLCJuYW1lIjoiQ3JlYXRlIEZ1bmN0aW9uIiwicGF0dGVybiI6Ii9cXGJjcmVhdGVfZnVuY3Rpb25cXHMqXFwoXFxzKlsnXCJdW14nXCJdKlsnXCJdXFxzKixcXHMqYmFzZTY0X2RlY29kZS9pIiwic2V2ZXJpdHkiOiJjcml0aWNhbCIsIm5ldmVyX2Rvd25ncmFkZSI6dHJ1ZX0seyJpZCI6Im9iZl9wcmVnX2UiLCJuYW1lIjoiUHJlZyAvZSIsInBhdHRlcm4iOiIvcHJlZ19yZXBsYWNlXFxzKlxcKFxccypbJ1wiXVxcLy4qXFwvZVsnXCJdXFxzKiwvaSIsInNldmVyaXR5IjoiY3JpdGljYWwiLCJuZXZlcl9kb3duZ3JhZGUiOnRydWV9LHsiaWQiOiJ3cF92Y2QiLCJuYW1lIjoiVGhlbWUgTWFsd2FyZSIsInBhdHRlcm4iOiIvd3BfY2RfY29kZXxjbGFzc1xcLnRoZW1lLW1vZHVsZXNcXC5waHAvaSIsInNldmVyaXR5IjoiY3JpdGljYWwifSx7ImlkIjoid3BfaWNvIiwibmFtZSI6IklDTyBCYWNrZG9vciIsInBhdHRlcm4iOiIvQGluY2x1ZGVcXHMqXFwoXFxzKlteXFwpXStcXC5pY29bJ1wiXVxccypcXCkvaSIsInNldmVyaXR5IjoiY3JpdGljYWwiLCJuZXZlcl9kb3duZ3JhZGUiOnRydWV9LHsiaWQiOiJ3cF9sZWFmbWFpbGVyIiwibmFtZSI6IlNwYW0gTWFpbGVyIFRvb2wiLCJwYXR0ZXJuIjoiL0xlYWZQSFBcXHMqTWFpbGVyfGxlYWZtYWlsZXIvaSIsInNldmVyaXR5IjoiY3JpdGljYWwifSx7ImlkIjoiZmlsZV9wdXRfaW5wdXQiLCJuYW1lIjoiRmlsZSBQdXQiLCJwYXR0ZXJuIjoiL2ZpbGVfcHV0X2NvbnRlbnRzXFxzKlxcKFxccypcXCRfKEdFVHxQT1NUfFJFUVVFU1QpXFxzKlxcWy9pIiwic2V2ZXJpdHkiOiJjcml0aWNhbCIsIm5ldmVyX2Rvd25ncmFkZSI6dHJ1ZX0seyJpZCI6ImZ3cml0ZV9pbnB1dCIsIm5hbWUiOiJGd3JpdGUiLCJwYXR0ZXJuIjoiL2Z3cml0ZVxccypcXChcXHMqW14sXSssXFxzKlxcJF8oR0VUfFBPU1R8UkVRVUVTVClcXHMqXFxbL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIiwibmV2ZXJfZG93bmdyYWRlIjp0cnVlfSx7ImlkIjoiaW5jbHVkZV9odHRwIiwibmFtZSI6IlJlbW90ZSBJbmNsdWRlIiwicGF0dGVybiI6Ii8oaW5jbHVkZXxyZXF1aXJlfGluY2x1ZGVfb25jZXxyZXF1aXJlX29uY2UpXFxzKlxcKFxccypbJ1wiXWh0dHBzPzpcXC9cXC8vaSIsInNldmVyaXR5IjoiY3JpdGljYWwiLCJuZXZlcl9kb3duZ3JhZGUiOnRydWV9LHsiaWQiOiJpbmNsdWRlX2lucHV0IiwibmFtZSI6IkluY2x1ZGUgSW5wdXQiLCJwYXR0ZXJuIjoiLyhpbmNsdWRlfHJlcXVpcmV8aW5jbHVkZV9vbmNlfHJlcXVpcmVfb25jZSlcXHMqXFwoXFxzKlxcJF8oR0VUfFBPU1R8UkVRVUVTVClcXHMqXFxbL2kiLCJzZXZlcml0eSI6ImNyaXRpY2FsIiwibmV2ZXJfZG93bmdyYWRlIjp0cnVlfV0=' ), true ); // RC-118-03 (audit 2026-06-18): the indicator pre-screen may skip a signature ONLY // if it is built-in AND prefilter-safe — i.e. its pattern genuinely requires one of // the content_has_indicators() tokens (these built-ins key on eval/base64/webshell // banners, all of which are in that list). Bundled-DB and remote-Feed signatures are // NEVER tagged, so they are NEVER gated: a precise Medium/Low feed signature can // match a file that contains none of the manual indicators, and skipping it would be // a false negative (these built-ins are all Critical today, so the flag is a // forward-safe contract rather than a behaviour change for them). foreach ( $builtin as &$bs ) { $bs['prefilter'] = true; } unset( $bs ); return $builtin; } // ==================== AJAX HANDLERS (FIXED!) ==================== /** * Initialize scan - FIXED VERSION * * Changes from original: * 1. Run check_core_integrity() upfront and store results * 2. Count core issues for consistent threat display * 3. Return core_issues to frontend */ public static function ajax_init_scan() { check_ajax_referer( 'guardpress_batch_scan', 'nonce' ); // FIX L-1 (audit 2026-05-25): capability check MOVED to before the // reset_api_counter side-effect. Previous ordering allowed a holder of // a valid 'guardpress_batch_scan' nonce without manage_options (very // narrow window — XSS / borrowed nonce) to reset the MalwareBazaar // counter. Cap check now comes immediately after nonce, per WP norm: // nonce → capability → side effects. if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => 'Permission denied' ) ); } // FIX H-2 (audit 2026-05-25): atomic concurrency guard for malware // scan. Separate lock-key from 'integrity' / 'baseline' since malware // scanner has its own state file and an independent code path — but // we still must prevent two parallel malware scans from corrupting // each other's state file or both hammering api.wordpress.org/core. $lock = GuardPress_Scan_Lock::acquire( 'malware' ); if ( ! $lock['acquired'] ) { wp_send_json_error( array( 'message' => sprintf( /* translators: %s: human-readable duration */ __( 'Another malware scan is already running (started %s ago). Please wait or cancel it.', 'ai-cyberguard' ), $lock['human_age'] ), 'started_at' => $lock['started_at'], 'lock_busy' => true, ) ); } // FIX RC-109-01 (audit 2026-06-17): the UI "Deep Scan (All Files)" button // sends scan_type=full, but this used to accept only 'quick'/'deep' and // SILENTLY fell back to 'quick' for anything else — so clicking Deep Scan // actually ran a Quick scan (plugins/themes only; uploads/wp-content/root // never scanned). We now treat 'full' as the canonical full-tree value, // accept 'deep' as a legacy alias, and REFUSE an unknown value with a clear // error instead of silently downgrading (a silent downgrade from a deep to a // shallow scan is more dangerous in a security product than a hard error). $raw_scan_type = isset( $_POST['scan_type'] ) ? sanitize_key( wp_unslash( $_POST['scan_type'] ) ) : 'quick'; if ( 'deep' === $raw_scan_type ) { $raw_scan_type = 'full'; // legacy alias → canonical } if ( ! in_array( $raw_scan_type, array( 'quick', 'full' ), true ) ) { GuardPress_Scan_Lock::release( 'malware', isset( $lock['scan_id'] ) ? $lock['scan_id'] : null ); // ACG-048-001: owner-bound release wp_send_json_error( array( 'message' => __( 'Invalid scan type.', 'ai-cyberguard' ) ) ); } $scan_type = $raw_scan_type; // PERF-116 supplementary: stamp the scan start BEFORE the heavy init work // (file discovery, execution-chain scan, core-integrity, signature load) so // the reported scan duration and ETA include that init phase instead of // pretending the scan only began once the per-file counter started. $scan_started = time(); $init_t0 = microtime( true ); // lightweight telemetry: init-phase wall-clock // Reset API counters for this scan (moved here, after both auth gates). if ( class_exists( 'GuardPress_MalwareBazaar' ) ) { GuardPress_MalwareBazaar::reset_api_counter(); } // RC-120-03 fix (red-team): reset the persisted network breakers NOW — before the // init-phase core checks below (get_core_checksums / check_core_integrity) — so a stale // OPEN breaker left by an abandoned prior scan cannot suppress this scan's core // checksum verification. (cleanup_scan_data() further down also clears them, but runs // after these checks.) self::reset_net_breaker(); // RC-108-01 (audit 2026-06-17): use the single PHP-family source so the // walker scans the same executable types as every other path (previously // it missed .pht/.php8/.phps/.inc/.php3/.php4 — a webshell in uploads). $php_ext = self::php_family_exts(); $all_ext = array_merge( self::php_family_exts(), array( 'js', 'htaccess', 'html', 'htm', 'svg' ) ); // COVERAGE FIX (2026-06-30): a Quick malware scan now covers ALL of wp-content — most // importantly wp-content/uploads/ (the #1 place a web-shell is dropped) and loose files in // the wp-content root — not only plugins/themes/mu-plugins. Previously a malicious .php in // uploads was NEVER read by a Quick scan (only the "Deep Scan (entire site)" reached it), // so the default scan silently missed the most common real-world infection location. The // extension filter keeps Quick cheap: only PHP-family files are read; the bulk of uploads // (images/media) is skipped by extension. A .php in uploads is almost always malicious. // The custom-uploads basedir is added explicitly in case uploads was relocated outside // wp-content (UPLOADS constant / multisite). Core dirs (wp-admin, wp-includes) remain // owned by check_core_integrity(); they are not under wp-content, so this does not double // scan them. Deep (full) still scans ABSPATH. $uploads_info = function_exists( 'wp_upload_dir' ) ? wp_upload_dir( null, false ) : array(); $uploads_dir = ( is_array( $uploads_info ) && ! empty( $uploads_info['basedir'] ) ) ? $uploads_info['basedir'] : ( WP_CONTENT_DIR . '/uploads' ); // ACG-111 (2026-07-03, from Yossi's real scan — duplicated uploads rows): the quick-scan // roots were array_unique( [WP_CONTENT_DIR, uploads_basedir] ). In the standard layout // uploads lives INSIDE wp-content, and array_unique only removes STRING-equal entries // ('.../wp-content' vs '.../wp-content/uploads' differ) — so the walker walked the // uploads tree TWICE. The later plain array_unique() on $all_files collapses the // duplicates ONLY when both walks yield byte-identical pathnames; on Windows the two // roots commonly mix separators (WP_CONTENT_DIR derived from a backslashed ABSPATH vs // wp_upload_dir()'s forward-slashed basedir), the same file gets two byte-DIFFERENT // pathnames, survives the plain unique, is scanned twice and reported twice — exactly // the duplicated charmap.php/index.php rows in his results (only uploads rows, the only // tree with two covering roots). Fix at the root: normalize and drop any root CONTAINED // in another root, so overlap is impossible on any separator mix. A genuinely relocated // uploads dir (UPLOADS constant / multisite, outside wp-content) is kept and scanned. $paths = ( $scan_type === 'quick' ) ? array_values( array_unique( array( WP_CONTENT_DIR, $uploads_dir ) ) ) : array( ABSPATH ); if ( count( $paths ) > 1 ) { $norm_roots = array(); foreach ( $paths as $p ) { $norm_roots[ rtrim( wp_normalize_path( $p ), '/' ) ] = $p; } $keep = array(); foreach ( $norm_roots as $nk => $orig ) { $contained = false; foreach ( $norm_roots as $ok => $unused ) { if ( $ok !== $nk && 0 === strpos( $nk . '/', $ok . '/' ) ) { $contained = true; break; } } if ( ! $contained ) { $keep[] = $orig; } } $paths = $keep; } $extensions = ( $scan_type === 'quick' ) ? $php_ext : $all_ext; $all_files = array(); // RC-106-01 follow-up: the WordPress core directories (wp-admin/, wp-includes/) // are covered by check_core_integrity() — it md5-verifies every core file // against the official WordPress.org checksums and recursively flags // unknown/modified files. To avoid reporting a core file twice (once here, // once by the integrity check) we EXCLUDE core dirs from this per-file walker. // // FIX RC-107-01 (audit 2026-06-17): BUT only when the checksums are actually // AVAILABLE. If WordPress.org checksums cannot be fetched (WP_HTTP_BLOCK_EXTERNAL, // network failure, API down, unknown version), check_core_integrity() bails // out early with status=error and covers NOTHING — so skipping core here would // leave a webshell in wp-includes completely unscanned. When checksums are // unavailable we therefore KEEP core dirs in the walker, so scan_file_uncached() // runs its core_unverifiable fallback (content-scan, never cached clean). $core_checksums = self::get_core_checksums(); // cached; fetched once $core_checksums_available = ! empty( $core_checksums ); $core_root = wp_normalize_path( rtrim( ABSPATH, '/\\' ) ); $core_prefixes = array( $core_root . '/wp-admin/', $core_root . '/wp-includes/' ); // M-108-04 (audit 2026-06-17): also skip the ROOT core files (wp-login.php // etc.) when checksums are available, so check_core_integrity() is the sole // source for ALL core (dirs + root) and a modified root core file is not // counted twice (once here, once by the integrity check). $core_root_files = self::core_root_files(); // RC-109-02 / RC-110-01 (audit 2026-06-17): detect the ".htaccess maps an asset // to PHP + asset-contains-PHP" execution chain in NON-core areas too (uploads, // wp-content) — not just inside wp-admin/wp-includes. During this one walk we // record every NON-core config file that carries a genuine PHP-handler directive // as a CANDIDATE (with the asset extensions it maps, if any). After the walk we // scan each candidate's SCOPE — its directory AND subdirectories, because Apache // .htaccess / PHP .user.ini / IIS web.config all cascade downward (RC-110-01) — // for an embedded PHP payload, BOUNDED, and only PROMOTE to a finding on // corroboration (a real PHP-bearing asset in scope). Core dirs are excluded // here: check_core_integrity() owns them. $chain_config_names = self::exec_chain_config_names(); $chain_handler_re = self::exec_chain_handler_re(); $chain_configs = array(); // [ ['dir'=>, 'rel'=>, 'exts'=>string[]], ... ] pending corroboration $chain_findings = array(); // RC-121-02 (audit 2026-06-19): COVERAGE HONESTY. The walker does not follow symlinked // directories (no FOLLOW_SYMLINKS) and CATCH_GET_CHILD silently swallows unreadable // subdirectories — so files inside a symlinked plugin/theme or a permission-locked folder // were never scanned, yet the scan could still report "clean". We now COUNT every such // skipped directory; the count flows into coverage_warnings so the scan reports INCOMPLETE // (never a false all-clear) and the user is told coverage was not exhaustive. $discovery_skipped = 0; $discovery_skipped_paths = array(); foreach ( $paths as $path ) { if ( ! is_dir( $path ) ) continue; try { $it = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD ); // FIX (audit 2026-06-10): CATCH_GET_CHILD — skip unreadable subdirs foreach ( $it as $file ) { if ( $file->isDir() ) { // A symlinked dir is not descended; an unreadable dir's children are // swallowed by CATCH_GET_CHILD. Either way its files are unscanned. $dp = $file->getPathname(); // ACG-082-H3 (audit 2026-06-27, MED): an EXCLUDED/ignored directory is out of scope — exclude // it BEFORE counting a symlinked/unreadable EXCLUDED dir as a coverage gap (false incomplete). if ( class_exists( 'GuardPress_FS_Helpers' ) && ( GuardPress_FS_Helpers::should_exclude_path( $dp ) || GuardPress_FS_Helpers::is_ignored( $dp ) ) ) { continue; } if ( $file->isLink() || ! @is_readable( $dp ) ) { $discovery_skipped++; if ( count( $discovery_skipped_paths ) < 25 ) { $discovery_skipped_paths[] = wp_normalize_path( $dp ); } } continue; } if ( ! $file->isFile() ) continue; // ACG-081-004 (audit 2026-06-27, HIGH): a symlinked FILE is a COVERAGE GAP, not a file to scan // THROUGH. SplFileInfo::isFile() FOLLOWS the link, so without this check the scanner would read // and hash the link's EXTERNAL target (outside ABSPATH) and could report a finding on a path that // is not actually an in-install file. Count it as a discovery skip (so coverage reads incomplete) // and never enqueue it — the SAME contract the Scan Runner and Batch Scanner already follow. if ( $file->isLink() || @is_link( $file->getPathname() ) ) { $discovery_skipped++; if ( count( $discovery_skipped_paths ) < 25 ) { $discovery_skipped_paths[] = wp_normalize_path( $file->getPathname() ); } continue; } $norm = wp_normalize_path( $file->getPathname() ); $in_core_dir = ( 0 === strpos( $norm, $core_prefixes[0] ) || 0 === strpos( $norm, $core_prefixes[1] ) ); if ( $core_checksums_available && ( $in_core_dir || ( dirname( $norm ) === $core_root && in_array( basename( $norm ), $core_root_files, true ) ) ) ) { continue; // core (dir or root file) — owned by check_core_integrity() when checksums available } // RC-109-02 / RC-110-01: handler-config detection for NON-core files // only. The config is recorded as a CANDIDATE (not flagged yet) with // the inert asset extensions it maps to PHP. A non-core .htaccess is // perfectly normal (plugins, deny rules), and the strict handler regex // no longer matches the stock permalink RewriteRule, so candidates are // genuinely suspicious — but we still only promote on corroboration // (a real PHP-bearing asset found in the config's scope below). if ( ! $in_core_dir ) { $chain_bn = strtolower( $file->getFilename() ); if ( in_array( $chain_bn, $chain_config_names, true ) ) { // ACG-086 sweep (audit 2026-06-28): never read a server-config chain THROUGH a symlink // component or from a non-regular file (FIFO would HANG). Unsafe path → empty (no chain head). $chain_head = self::is_safe_regular_file( $norm ) ? (string) @file_get_contents( $norm, false, null, 0, 1048576 ) : ''; // RC-111-02.3: read up to 1MB so a handler directive placed after padding/comments is not missed $chain_size = @filesize( $norm ); $cfg_oversize = ( false !== $chain_size && $chain_size > 1048576 ); // RC-112-04: handler may sit beyond the cap $has_handler = ( '' !== $chain_head && preg_match( $chain_handler_re, $chain_head ) ); if ( $has_handler || $cfg_oversize ) { $cfg_rel = ltrim( str_replace( $core_root, '', $norm ), '/' ); // An oversize config whose handler we could not fully read is // still treated as a candidate (with the inert-image universe) // so its scope is corroboration-scanned, AND a partial notice is // surfaced so the gap is never hidden. $cfg_plan = $has_handler ? self::exec_chain_scope_plan( $chain_head ) : array( 'exts' => array(), 'all' => false ); $chain_configs[] = array( 'dir' => dirname( $norm ), 'rel' => $cfg_rel, // PERF-116-01 / RC-118-02: explicit exts to scan, plus an // 'all' flag for a broad handler (scan every non-walker file). 'exts' => $cfg_plan['exts'], 'all' => $cfg_plan['all'], 'oversize' => $cfg_oversize, ); // RC-112-04: auto_prepend_file / auto_append_file targets are // executed as PHP on EVERY request regardless of their extension // (e.g. a planted shell.txt). Resolve + scan them directly — the // inert-asset scope scan would otherwise never look at a .txt. if ( $has_handler ) { $ap = self::scan_auto_prepend_targets( $chain_head, dirname( $norm ), $core_root ); if ( $ap ) { $chain_findings[ $cfg_rel ] = array( 'file' => $cfg_rel, 'location' => 'exec_chain', 'severity' => 'high' ); foreach ( $ap as $ap_rel => $ap_f ) { $chain_findings[ $ap_rel ] = $ap_f; } } } if ( $cfg_oversize ) { $chain_findings[ '__cfg_oversize__' . $cfg_rel ] = array( 'file' => sprintf( /* translators: %s: relative path of the server-config file */ __( 'A server-config file (%s) is larger than 1 MB and was only partially inspected for PHP-handler directives — review it manually.', 'ai-cyberguard' ), $cfg_rel ), 'location' => 'exec_chain', 'severity' => 'low', ); } } } } // RC-111-04: enqueue by the last extension OR any PHP-family suffix // earlier in a multi-extension name (e.g. shell.php.jpg) — Apache may // execute the file as PHP via the earlier suffix even though pathinfo() // only sees ".jpg". $ext = strtolower( pathinfo( $file->getPathname(), PATHINFO_EXTENSION ) ); if ( in_array( $ext, $extensions, true ) || self::has_php_family_suffix( $file->getFilename() ) ) { $all_files[] = $file->getPathname(); } } } catch ( Exception $e ) {} } // ACG-111 second layer: the pre-existing plain array_unique() further below collapses // byte-identical duplicates only. Dedupe here on the NORMALIZED path (wp_normalize_path // folds Windows backslashes), so the same on-disk file can never be enqueued (scanned, // counted, reported) twice even when overlapping roots or mixed separators produce // byte-different pathnames. Insertion order is preserved. if ( $all_files ) { $uniq_files = array(); foreach ( $all_files as $fp_i ) { $uniq_files[ wp_normalize_path( $fp_i ) ] = $fp_i; } $all_files = array_values( $uniq_files ); } // RC-110-01 / RC-110-02: for each candidate handler-config, scan its SCOPE // (its directory + subdirectories — config rules cascade downward) for an asset // that hides a PHP payload anywhere in the file (not just the first 64 KB). // If the config explicitly maps inert extensions (e.g. AddHandler ... .ico) we // scan only those; otherwise we fall back to the inert-image universe. The whole // pass is BOUNDED (max dirs/assets per config) and CORROBORATED — a config (and // its scope payloads) are only emitted when a real PHP-bearing/oversized asset // is actually found in scope. So the stock permalink root .htaccess (not even a // candidate under the strict regex) and a benign handler-less image folder // produce nothing. if ( $chain_configs ) { $chain_universe = self::exec_chain_noncore_asset_exts(); $chain_limited = false; // RC-111-06: a GLOBAL asset-read budget shared across ALL candidate configs // (not a fresh budget per config), so many overlapping or nested handler // configs cannot multiply into unbounded I/O. Once exhausted, the remaining // configs are skipped and the limit notice below is surfaced. $global_assets_left = 5000; foreach ( $chain_configs as $cfg ) { if ( $global_assets_left <= 0 ) { $chain_limited = true; break; } $exts = $cfg['exts']; $scan_all = ! empty( $cfg['all'] ); // RC-118-02: broad handler -> scan every non-walker file // An oversize config whose handler we could not fully read: be conservative // and scope-scan everything (we cannot prove it is a harmless PHP-only mapping). if ( ! empty( $cfg['oversize'] ) ) { $scan_all = true; } // PERF-116-01: a PHP-only AddHandler / auto_prepend-only config maps no // NON-PHP file to PHP, so no inert asset can hide a payload behind it — // skip the (previously ~GiB-scale) recursive asset read entirely. if ( ! $scan_all && empty( $exts ) ) { continue; } $limited = false; $payloads = self::scan_chain_scope_for_payloads( $cfg['dir'], $exts, $core_root, $core_prefixes, $limited, $global_assets_left, true, $scan_all ); if ( $limited ) { $chain_limited = true; } if ( $payloads ) { $chain_findings[ $cfg['rel'] ] = array( 'file' => $cfg['rel'], 'location' => 'exec_chain', 'severity' => 'high' ); foreach ( $payloads as $rel => $finding ) { $chain_findings[ $rel ] = $finding; } } } // No silent caps (round-11 review): surface a low-severity notice (NOT // counted as a threat) WHENEVER a candidate's scope scan hit a bound — even // if no payload was found in it — so "scan complete" never hides that part // of a PHP-handler-governed folder was not exhaustively chain-scanned. if ( $chain_limited ) { $chain_findings['__exec_chain_limited__'] = array( 'file' => 'Execution-chain scan reached its size/count limit while inspecting a folder governed by a PHP-handler config — some asset files there may not have been fully scanned. Review that folder manually.', 'location' => 'exec_chain', 'severity' => 'low', ); } } // FIX #1: Run Core Integrity check upfront and store results $core_integrity = self::check_core_integrity(); // ACG-048-001 / ACG-049-001 (audit 2026-06-23): heartbeat the lock after the heavy init phases (file // discovery + execution-chain walk + core-integrity, which can reach api.wordpress.org). On a very large // install this monolithic init can approach MAX_AGE_SECONDS. The return value is TERMINAL: if a successor // stale-took-over the lease during this slow init, touch() returns false — we MUST abort BEFORE the // destructive cleanup_scan_data( true ) below (which would wipe the successor's fresh scan state) and // before writing any shared malware_* state. We do NOT clean up here — the successor now owns that data. if ( ! GuardPress_Scan_Lock::touch( 'malware', isset( $lock['scan_id'] ) ? $lock['scan_id'] : null ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was taken over by another tab during start-up. Please continue it from that tab.', 'ai-cyberguard' ), ) ); } // RC-109-02: fold the non-core execution-chain findings into the same bucket // the summary already counts/displays, so they surface as threats too. if ( $chain_findings ) { $core_integrity['unknown'] = array_merge( isset( $core_integrity['unknown'] ) && is_array( $core_integrity['unknown'] ) ? $core_integrity['unknown'] : array(), array_values( $chain_findings ) ); } $core_issues_count = count( $core_integrity['modified'] ?? array() ); // Count unknown files that are high/critical/medium severity if ( ! empty( $core_integrity['unknown'] ) ) { foreach ( $core_integrity['unknown'] as $unknown ) { if ( is_array( $unknown ) && isset( $unknown['severity'] ) ) { $sev = $unknown['severity']; if ( $sev === 'critical' || $sev === 'high' || $sev === 'medium' ) { $core_issues_count++; } } } } $all_files = array_unique( $all_files ); // FIX: Clean up any previous scan data. PERF-121-02: preserve the network breakers — a // fresh scan already reset them via reset_net_breaker() at the top of this method, and the // init-phase core checks above may have legitimately OPENED them (WordPress.org down); they // must carry into batch 1 instead of being wiped here (which forced two more timeouts). self::cleanup_scan_data( true ); // FIX: Save file list to JSON file (written ONCE, read-only during scan) if ( ! self::save_scan_data( 'malware_files', array_values( $all_files ) ) ) { // FIX H-2: release the lock on init failure so the user can retry // immediately. Without this, a transient disk-full event would // wedge the scan-busy state for the full 30-min stale-lock window. GuardPress_Scan_Lock::release( 'malware', isset( $lock['scan_id'] ) ? $lock['scan_id'] : null ); // ACG-048-001: owner-bound release wp_send_json_error( array( 'message' => 'Failed to save scan data. Check file permissions on wp-content/.' ) ); } // PERF FIX: Pre-load ALL signatures ONCE at init (not every batch) // With 11,000+ threat feed signatures, loading from DB every batch is ~2.3MB × 20 batches = ~46MB // Loading once and caching in file: ~2.3MB total $all_sigs = self::get_signatures(); // Built-in (30) if ( class_exists( 'GuardPress_Signatures_Database' ) ) { $db_sigs = GuardPress_Signatures_Database::get_all_signatures(); if ( ! empty( $db_sigs ) ) { $all_sigs = array_merge( $all_sigs, $db_sigs ); } } if ( class_exists( 'GuardPress_Threat_Feed' ) ) { // PERF-116-05: never let a scan stall on a synchronous feed download — use // the cached feed (the weekly cron / "Refresh Threats" keeps it fresh). $feed_sigs = GuardPress_Threat_Feed::get_signatures( false, false ); if ( ! empty( $feed_sigs ) ) { $all_sigs = array_merge( $all_sigs, $feed_sigs ); } } // FIX (FP-regression 2026-06-11): collect_extra_signature_sets() now // returns [] — the Extended/Threat-Intel/YARA heuristic sets were the // root cause of the ~500-false-positive flood on legitimate bundled // libraries (see that method's header for the full rationale). This call // is kept as a no-op merge so the scope stays in ONE place; do NOT // re-enable those sets without per-signature FP-prevention. $all_sigs = array_merge( $all_sigs, self::collect_extra_signature_sets() ); // ACG-045-008 (audit 2026-06-22): deduplicate by stable ID AND by effective regex pattern, so neither a // repeated id nor two different ids sharing one pattern can double-count a finding or inflate the score. $unique_sigs = array(); $seen = array(); $seen_pat = array(); foreach ( $all_sigs as $sig ) { $id = $sig['id'] ?? ''; $pat = isset( $sig['pattern'] ) ? (string) $sig['pattern'] : ''; if ( ( '' !== $id && isset( $seen[ $id ] ) ) || ( '' !== $pat && isset( $seen_pat[ $pat ] ) ) ) { continue; } if ( '' !== $id ) { $seen[ $id ] = true; } if ( '' !== $pat ) { $seen_pat[ $pat ] = true; } $unique_sigs[] = $sig; } // Save to file for fast batch-time access. If this fails, batch falls back to DB (slower but works). if ( ! self::save_scan_data( 'malware_sigs', $unique_sigs ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress: Could not cache signatures to file. Scan will use DB fallback (slower).' ); } } // Also pre-load malware hashes (hash lookups are O(1) but DB read is expensive) $hashes = class_exists( 'GuardPress_Threat_Feed' ) ? GuardPress_Threat_Feed::get_malware_hashes() : array(); if ( ! empty( $hashes ) ) { if ( ! self::save_scan_data( 'malware_hash_db', $hashes ) ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress: Could not cache malware hashes to file. Scan will use DB fallback.' ); } } } $sig_count = count( $unique_sigs ); // FIX #2: Store core_integrity and core_issues_count in state (file-based) if ( ! self::save_scan_data( 'malware_state', array( 'total' => count( $all_files ), 'processed' => 0, 'findings' => array(), 'verified_clean' => 0, 'start_time' => $scan_started, // PERF-116: includes the heavy init phase 'scan_type' => $scan_type, 'core_integrity' => $core_integrity, 'core_issues_count' => $core_issues_count, 'sig_count' => $sig_count, 'init_ms' => (int) round( ( microtime( true ) - $init_t0 ) * 1000 ), // PERF-116 telemetry 'mb_calls' => 0, // PERF-116-05: per-scan MalwareBazaar budget carried across batches 'discovery_skipped' => $discovery_skipped, // RC-121-02: symlinked/unreadable dirs not scanned → coverage incomplete 'discovery_skipped_paths' => $discovery_skipped_paths, 'scan_id' => isset( $lock['scan_id'] ) ? $lock['scan_id'] : '', // ADDL-1: lock owner token, threaded to batch/finalize/cancel for owner-bound release (cross-tab Cancel hijack guard) ) ) ) { self::cleanup_scan_data(); // FIX H-2: same as above — release lock on init failure. GuardPress_Scan_Lock::release( 'malware', isset( $lock['scan_id'] ) ? $lock['scan_id'] : null ); // ACG-048-001: owner-bound release wp_send_json_error( array( 'message' => 'Failed to save scan state. Check file permissions on wp-content/.' ) ); } // FIX #3: Return core_issues to frontend wp_send_json_success( array( 'total' => count( $all_files ), 'message' => sprintf( 'Found %s files', number_format_i18n( count( $all_files ) ) ), 'core_issues' => $core_issues_count, // NEW 'scan_id' => isset( $lock['scan_id'] ) ? $lock['scan_id'] : '' // ADDL-1: client echoes this back on batch/cancel so only the owning tab can cancel ) ); } /** * Process scan batch - FIXED VERSION * * Changes from original: * 1. Clear cache before getting state (prevents stale data) * 2. Clear cache after updating state * 3. Calculate total_threats = file_findings + core_issues */ public static function ajax_scan_batch() { check_ajax_referer( 'guardpress_batch_scan', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => 'Permission denied' ) ); // FIX: Load state from file (not DB — eliminates binlog bloat) $state = self::load_scan_data( 'malware_state' ); if ( empty( $state ) ) wp_send_json_error( array( 'message' => 'No scan in progress' ) ); // ACG-032-003 (audit 2026-06-20): ownership guard. If this scan is owned by // a token (state['scan_id'] non-empty) the caller MUST present a matching // scan_id, or this stale/foreign batch is refused with NO side effects (no // touch, no state mutation, no processing). When the state has no owner // (legacy) the call falls through. hash_equals = constant-time compare. $owner_token = isset( $state['scan_id'] ) ? (string) $state['scan_id'] : ''; $posted_token = isset( $_POST['scan_id'] ) ? sanitize_text_field( wp_unslash( $_POST['scan_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified by check_ajax_referer() above if ( '' !== $owner_token && ! hash_equals( $owner_token, $posted_token ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was started in another tab. Continue it from that tab, or wait for it to finish.', 'ai-cyberguard' ), ) ); } // SA-42 (self-audit 2026-06-21, HIGH): the hash_equals() check above compares the owner token // recorded in the (possibly stale) state FILE — it does NOT prove this caller still holds the // live 'malware' lock. A scan that crossed the stale-lock boundary can read its OWN old state // before a successor's init rewrites it, pass that compare, process, and then write its stale // generation back over the successor's fresh state (wedging the live scan). Require an // owner-bound lock CAS — the SAME gate the integrity/baseline batch uses (ACG-037-004): if a // successor took over the lock, touch() with our token fails and we stand down with NO // processing and NO state write. (method_exists-guarded so a stubbed lock can never fatal it.) if ( '' !== $posted_token && class_exists( 'GuardPress_Scan_Lock' ) && method_exists( 'GuardPress_Scan_Lock', 'touch' ) && ! GuardPress_Scan_Lock::touch( 'malware', $posted_token ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was started in another tab. Continue it from that tab, or wait for it to finish.', 'ai-cyberguard' ), ) ); } // FIX: Load file list from separate file (read-only, written once in init) $all_files = self::load_scan_data( 'malware_files', array() ); if ( empty( $all_files ) ) wp_send_json_error( array( 'message' => 'Scan file list not found' ) ); // === SIGNATURE LOADING (v8.2 — PERF FIX) === // Load pre-cached signatures from file (saved once in init) // This eliminates ~2.3MB DB reads per batch (was: 20 batches × 2.3MB = 46MB total) $signatures = self::load_scan_data( 'malware_sigs', array() ); // Fallback: if cached file missing (e.g. interrupted scan), reload from DB if ( empty( $signatures ) ) { $signatures = self::get_signatures(); if ( class_exists( 'GuardPress_Signatures_Database' ) ) { $db_sigs = GuardPress_Signatures_Database::get_all_signatures(); if ( ! empty( $db_sigs ) ) { $signatures = array_merge( $signatures, $db_sigs ); } } if ( class_exists( 'GuardPress_Threat_Feed' ) ) { // PERF-116-05: cached feed only — no synchronous network during a scan. $feed_sigs = GuardPress_Threat_Feed::get_signatures( false, false ); if ( ! empty( $feed_sigs ) ) { $signatures = array_merge( $signatures, $feed_sigs ); } } // FIX (FP-regression 2026-06-11): no-op merge — collect_extra_signature_sets() // returns [] (Extended/Threat-Intel/YARA disabled; see that method's header). $signatures = array_merge( $signatures, self::collect_extra_signature_sets() ); // ACG-045-008: deduplicate by stable ID AND by effective pattern (see the cache-build path above). $unique = array(); $seen = array(); $seen_pat = array(); foreach ( $signatures as $sig ) { $id = $sig['id'] ?? ''; $pat = isset( $sig['pattern'] ) ? (string) $sig['pattern'] : ''; if ( ( '' !== $id && isset( $seen[ $id ] ) ) || ( '' !== $pat && isset( $seen_pat[ $pat ] ) ) ) { continue; } if ( '' !== $id ) { $seen[ $id ] = true; } if ( '' !== $pat ) { $seen_pat[ $pat ] = true; } $unique[] = $sig; } $signatures = $unique; } // === END SIGNATURE LOADING === $core_checksums = self::get_core_checksums(); // PERF-116-05: restore the per-SCAN MalwareBazaar budget (carried in state) // so external confirmations are capped across the whole scan, not per batch. if ( class_exists( 'GuardPress_MalwareBazaar' ) ) { GuardPress_MalwareBazaar::set_api_call_count( (int) ( $state['mb_calls'] ?? 0 ) ); } // Load pre-cached malware hashes (same perf fix) $malware_hashes = self::load_scan_data( 'malware_hash_db', array() ); if ( empty( $malware_hashes ) ) { $malware_hashes = class_exists( 'GuardPress_Threat_Feed' ) ? GuardPress_Threat_Feed::get_malware_hashes() : array(); } static $plugin_checksums_cache = array(); // PERF FIX (v8.2): Dynamic batch size based on signature count $sig_count = count( $signatures ); if ( $sig_count > 5000 ) { $batch_size = 40; // v8.2: raised from 25→40 (safe after hc_sigs pre-compute + caches) } elseif ( $sig_count > 2000 ) { $batch_size = 50; // ~3K sigs × 50 files = 150K ops } elseif ( $sig_count > 1000 ) { $batch_size = 75; // ~1.5K sigs × 75 files = 112K ops } else { $batch_size = self::BATCH_SIZE; // 150 (original) } // PERF FIX (v8.2): Pre-compute high-confidence sigs ONCE per batch // Before this fix: rebuilt 11,737× for EVERY theme/modified-plugin file (3 times each!) // After: computed once, passed to scan_file — saves ~880K array iterations per batch $hc_sigs = array(); foreach ( $signatures as $s ) { $sev = strtolower( $s['severity'] ?? 'high' ); if ( $sev === 'critical' || $sev === 'high' ) { $hc_sigs[] = $s; } } // PERF-116-03 (perf audit 2026-06-18): DEADLINE-BASED batching. The old code // processed a FIXED $batch_size files per AJAX request, so an 11,000-file site // became ~275 separate admin-ajax requests — each one re-bootstraps WordPress and // re-decodes the (up to ~2.3 MB) cached signature set. Most files are checksum-clean // or cache-hits and scan in microseconds, so a fixed small batch wastes that // fixed per-request overhead. We now keep processing within ONE request until a // wall-clock budget is reached (derived from max_execution_time, with generous // headroom) or a hard file cap — whichever comes first — while still guaranteeing // at least $batch_size files so progress is made even on a tiny time limit. This // collapses the request count (and thus the WP boots + signature decodes + network // setup) by ~5-10x on a clean site, without enlarging any single file's work. // PERF-118-01 (audit 2026-06-18): the deadline is checked after EVERY file, with a // minimum of just 1 file — NOT $batch_size. Previously the time check was gated // behind "$done_in_batch >= $batch_size", so on a host with >5000 sigs // (batch_size=40) up to 40 large, indicator-bearing files were ALWAYS processed // before the clock was even consulted; an adversarial 40×500KB batch reached ~30s // and could exceed max_execution_time, cutting the request before state was saved // and dropping the JS into a retry/timeout loop. We keep ~40% of the limit as the // budget (headroom for the final file + flush/JSON), and CHECKPOINT state every // $checkpoint_every files so a worst-case cut never loses more than that many files // of progress (the JS retry resumes from the checkpoint, not the batch start). $me_limit = (int) ini_get( 'max_execution_time' ); $batch_deadline = ( $me_limit > 0 ) ? max( 3.0, min( 8.0, $me_limit * 0.4 ) ) : 8.0; $batch_hard_cap = max( $batch_size * 20, 2000 ); // bound response payload / memory $checkpoint_every = 250; $batch_start = microtime( true ); $done_in_batch = 0; $total_files = count( $all_files ); while ( $state['processed'] < $total_files ) { // Stop conditions (checked BEFORE each file so a per-file `continue` still honours them): // - hard file cap (bounds memory/response), OR // - at least 1 file done AND the wall-clock budget is spent. if ( $done_in_batch >= $batch_hard_cap ) { break; } if ( $done_in_batch >= 1 && ( microtime( true ) - $batch_start ) >= $batch_deadline ) { break; } // PERF-118-01: periodic checkpoint so a request cut mid-batch loses at most // $checkpoint_every files of progress instead of the whole batch. // ACG-033-003 (audit 2026-06-20): the checkpoint IS a durable-progress // commit. If it cannot be written, the advance we just made is NOT // persisted; continuing and later reporting progress would lie about // what survived a crash. Return a retryable error WITHOUT heartbeating // the lock — the client re-runs this batch and resumes from the last // durable offset (re-scanning is idempotent and cache-fast). if ( $done_in_batch > 0 && 0 === ( $done_in_batch % $checkpoint_every ) ) { self::verdict_cache_flush(); if ( class_exists( 'GuardPress_MalwareBazaar' ) ) { $state['mb_calls'] = GuardPress_MalwareBazaar::get_api_call_count(); } // ACG-049-001 (audit 2026-06-23): verify + refresh ownership IMMEDIATELY BEFORE committing shared // scan state. touch() returns false if a successor stale-took-over the lease; treat that as TERMINAL // and abort so a stale generation can never overwrite the successor's malware_state. if ( ! GuardPress_Scan_Lock::touch( 'malware', isset( $state['scan_id'] ) ? $state['scan_id'] : null ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ), ) ); } if ( ! self::save_scan_data( 'malware_state', $state ) ) { wp_send_json_error( array( 'message' => __( 'Scan progress could not be saved (a temporary disk or permission problem). Please retry — no progress was lost.', 'ai-cyberguard' ), 'retryable' => true, 'save_failed' => true, ) ); } } $filepath = $all_files[ $state['processed'] ]; $state['processed']++; $done_in_batch++; if ( ! file_exists( $filepath ) || ! is_readable( $filepath ) ) { // RC-116-03 (audit 2026-06-18): a file discovered at scan start but missing / // unreadable when the batch reaches it is a COVERAGE gap (TOCTOU), not a clean // result. Record an info-severity 'coverage' notice (counts toward // coverage_warnings in generate_summary, so coverage_complete becomes false and // the scan cannot report "Site clean", but it is NOT counted as a threat). $miss_rel = ltrim( str_replace( wp_normalize_path( rtrim( ABSPATH, '/\\' ) ), '', wp_normalize_path( $filepath ) ), '/' ); $state['findings'][] = array( 'filepath' => $miss_rel, 'risk_score' => 0, 'findings' => array( array( 'type' => 'coverage', 'severity' => 'info', 'name' => __( 'File could not be scanned', 'ai-cyberguard' ), 'description' => __( 'This file was found when the scan started but was missing or unreadable when the scan reached it, so it was not checked.', 'ai-cyberguard' ), 'recommendation' => __( 'Re-run the scan. If it persists, check the file and its permissions.', 'ai-cyberguard' ), ) ), ); continue; } // RC-114-01 (audit 2026-06-18): skip a file in our own folder ONLY when it // is verified-genuine against the code-anchored manifest (see // is_unmodified_own_file). Our own detection code legitimately contains live // malware patterns (eval/include examples, banner strings) that would self-FP // if scanned; verified-genuine files are therefore skipped. Anything ADDED or // MODIFIED in our folder — or present when the manifest can't be verified — // is NOT trusted and falls through to a full scan, so a planted shell or a // tampered own file is always caught. $fp = wp_normalize_path( $filepath ); // ACG-081-004 (audit 2026-06-27, HIGH): re-check is_link before any read. A path enqueued as a regular // file at discovery can be swapped to a symlink before this batch runs (TOCTOU); filesize()/scan_file() // would then read the link's EXTERNAL target. A symlink at scan time is a coverage gap — count it and // skip it, never read through the link. clearstatcache( false, $filepath ); if ( @is_link( $filepath ) ) { $state['skipped'] = ( isset( $state['skipped'] ) ? (int) $state['skipped'] : 0 ) + 1; continue; } if ( self::is_unmodified_own_file( $fp ) ) { continue; } // ACG-112 (2026-07-04, from Yossi's real scan): ORDER-OF-GATES fix. The internal-data-store // exclusion (ACG-103) lives inside scan_file(), but the oversize check below runs BEFORE // scan_file() — so the moment our own signatures cache (guardpress-data/scan/malware_sigs.php) // grew past the 2 MB cap (threat-feed growth between his two scans), it was reported as a // HIGH "File too large to fully scan" WITH a Quarantine button. Quarantining our own sig // cache would degrade the scanner and churn (the file is rewritten at every scan init). // The gate must run at this chokepoint so EVERY pre-scan_file emission path respects it. // Same treatment as scan_file's inner gate (kept, defense-in-depth): count verified and move // on. is_internal_data_path() is symlink-hardened (lexical + realpath) — a symlinked // look-alike store is NOT internal and still gets scanned/flagged. if ( class_exists( 'GuardPress_FS_Helpers' ) && GuardPress_FS_Helpers::is_internal_data_path( $filepath ) ) { $state['verified_clean']++; continue; } // RC-111-03: a file larger than the scan cap is never fully read, so it must // NEVER be counted "verified clean". Emit an oversize/unscanned finding so the // scan summary reflects the coverage gap. PHP-family executables get a HIGH // finding (a >2MB script is genuinely unusual and high-risk); other enqueued // types (e.g. a large minified JS) get a LOW informational notice so common // large assets do not flood the report. // ACG-087-H1 (audit 2026-06-28): gate the oversize size-check too — a symlinked parent would otherwise // report the EXTERNAL target's size. scan_file() below self-gates and counts an unsafe path as a coverage // gap, so an unsafe path simply skips this size-based oversize finding (false → branch not taken). $fsize = self::is_safe_regular_file( $filepath ) ? @filesize( $filepath ) : false; if ( false !== $fsize && $fsize > self::MAX_FILE_SIZE ) { $bn_o = basename( $fp ); $is_exec = self::has_php_family_suffix( $bn_o ) || in_array( strtolower( pathinfo( $bn_o, PATHINFO_EXTENSION ) ), self::php_family_exts(), true ); $rel_o = ltrim( str_replace( wp_normalize_path( rtrim( ABSPATH, '/\\' ) ), '', $fp ), '/' ); $state['findings'][] = array( 'filepath' => $rel_o, 'risk_score' => $is_exec ? 60 : 5, 'findings' => array( array( 'type' => 'oversize', 'severity' => $is_exec ? 'high' : 'low', 'name' => __( 'File too large to fully scan', 'ai-cyberguard' ), 'description' => __( 'This file exceeds the scanner size limit (2 MB) and was not fully scanned for malware. Large executable/script files are unusual.', 'ai-cyberguard' ), 'recommendation' => __( 'Open and review this file; remove it if you do not recognise it.', 'ai-cyberguard' ), ) ), ); continue; } $result = self::scan_file( $filepath, $signatures, $core_checksums, $plugin_checksums_cache, $malware_hashes, $hc_sigs ); if ( $result === 'skipped' ) { // ACG-082-003 (audit 2026-06-27, HIGH): scan_file() refused to read a symlink (a TOCTOU swap) — it is // a COVERAGE GAP, not a verified-clean file. Count it skipped so the scan reads incomplete. $state['skipped'] = ( isset( $state['skipped'] ) ? (int) $state['skipped'] : 0 ) + 1; } elseif ( $result === 'clean' ) { $state['verified_clean']++; } elseif ( self::should_record_finding( $result, $state['scan_type'] ?? 'quick' ) ) { // GP-REL-001: record ANY genuine (non-info) signature/threat match. // The old risk-threshold gate (>=50 quick / >=30 deep) dropped real // Medium-only matches (score 20). Context-downgraded info-only results // are still suppressed by should_record_finding(). risk_score remains // available on $result for display/ordering only. $state['findings'][] = $result; } } // Persist the incremental verdict cache so the NEXT scan can skip // unchanged-clean files — this is what makes subsequent scans much faster. self::verdict_cache_flush(); // PERF-116-05: carry the running MalwareBazaar budget into the next batch. if ( class_exists( 'GuardPress_MalwareBazaar' ) ) { $state['mb_calls'] = GuardPress_MalwareBazaar::get_api_call_count(); } // FIX: Save state to file (not DB — eliminates binlog bloat). // ACG-033-003 (audit 2026-06-20): this end-of-batch save is the authoritative // progress COMMIT. The OLD code ignored its return value and then reported // processed/percent/"complete" from the IN-MEMORY $state — so a failed write // told the client we advanced (even to 100%/complete) while the next batch // would actually re-read the OLD offset: lost findings, or a false all-clear. // Treat it as a gate: on failure return a retryable error and do NOT // heartbeat the lock or report any progress (we made none that survived). // ACG-049-001 (audit 2026-06-23): verify + refresh ownership IMMEDIATELY BEFORE this authoritative progress // commit. touch() both heartbeats the lease (so a long healthy scan is never treated as stale) AND returns // false when a successor stale-took-over — which is TERMINAL: abort rather than overwrite the successor's // malware_state. This replaces the previous post-commit heartbeat (which committed first, then checked). if ( ! GuardPress_Scan_Lock::touch( 'malware', isset( $state['scan_id'] ) ? $state['scan_id'] : null ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was taken over by another tab. Please continue it from that tab.', 'ai-cyberguard' ), ) ); } if ( ! self::save_scan_data( 'malware_state', $state ) ) { wp_send_json_error( array( 'message' => __( 'Scan progress could not be saved (a temporary disk or permission problem). Please retry — no progress was lost.', 'ai-cyberguard' ), 'retryable' => true, 'save_failed' => true, ) ); } $percent = $state['total'] > 0 ? ( $state['processed'] / $state['total'] ) * 100 : 0; $elapsed = time() - $state['start_time']; $rate = $state['processed'] > 0 ? $state['processed'] / max( 1, $elapsed ) : 0; $eta = $rate > 0 ? ceil( ( $state['total'] - $state['processed'] ) / $rate ) : 0; // ACG-122 note #2 (programmer review): the live progress line said "Scanning... N threats" where N // was count($state['findings']) + core issues — i.e. EVERY finding, including suspicious / integrity // / coverage items. A scan of a site full of legitimate premium plugins therefore counted up dozens // of "threats" in front of the user while it ran, and the final summary then reported 0 — the exact // over-alarming the ACG-103 verdict model exists to prevent, leaking back in through the progress UI. // (The old comment "CHANGED: was count($state['findings'])" was misleading: it only ADDED core issues, // it never switched to malware-only counting.) // Count by VERDICT CLASS here, the same axis generate_summary() uses, so the number matches its label. // Bounded work: findings are capped, and this runs once per progress poll. $gp_malware_count = 0; $gp_review_count = 0; foreach ( (array) $state['findings'] as $gp_ff ) { foreach ( (array) ( $gp_ff['findings'] ?? array() ) as $gp_fnd ) { $gp_cls = self::finding_verdict_class( $gp_fnd ); if ( 'malware' === $gp_cls ) { $gp_malware_count++; } elseif ( 'info' !== $gp_cls ) { $gp_review_count++; } } } $core_issues_count = $state['core_issues_count'] ?? 0; $total_threats = $gp_malware_count + $core_issues_count; // confirmed malware only wp_send_json_success( array( 'status' => $state['processed'] >= $state['total'] ? 'complete' : 'scanning', 'processed' => $state['processed'], 'total' => $state['total'], 'percent' => round( $percent, 1 ), 'findings' => $total_threats, // ACG-122 #2: confirmed malware only, matching the label 'review' => $gp_review_count, // ACG-122 #2: suspicious/integrity/coverage, shown separately 'verified' => $state['verified_clean'], 'eta' => $eta, 'message' => $gp_review_count > 0 ? sprintf( 'Scanning... %d threats, %d to review, %d verified clean', $total_threats, $gp_review_count, $state['verified_clean'] ) : sprintf( 'Scanning... %d threats, %d verified clean', $total_threats, $state['verified_clean'] ) ) ); } /** * Finalize scan - FIXED VERSION * * Changes from original: * 1. Use stored core_integrity from init (avoid duplicate processing) */ public static function ajax_finalize_scan() { check_ajax_referer( 'guardpress_batch_scan', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( array( 'message' => 'Permission denied' ) ); // FIX: Load state from file (not DB) $state = self::load_scan_data( 'malware_state' ); if ( empty( $state ) ) { // ACG-033-002 (audit 2026-06-20): no scan state. The OLD code released // the lock with a NULL (unconditional) owner here — which would free a // lock a DIFFERENT, still-active scan owns (e.g. a finalize racing a // freshly-started scan, or a stale tab). Only an OWNER-BOUND release // using the caller's own token is safe: GuardPress_Scan_Lock::release() // CAS-checks the token and leaves any non-matching lock intact. With no // token we leave the lock to its 30-min age recovery rather than risk // freeing someone else's. $posted_token = isset( $_POST['scan_id'] ) ? sanitize_text_field( wp_unslash( $_POST['scan_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by check_ajax_referer() above if ( '' !== $posted_token ) { GuardPress_Scan_Lock::release( 'malware', $posted_token ); } wp_send_json_error( array( 'message' => 'No scan data' ) ); } // ACG-032-003 (audit 2026-06-20): ownership guard BEFORE any finalize / // persist / cleanup / release. A stale or foreign request (mismatched or // missing scan_id while this scan is owned) must NOT finalize the scan, // persist a report, delete the state, or release the lock the running scan // still owns. When the state has no owner (legacy) the call falls through. $owner_token = isset( $state['scan_id'] ) ? (string) $state['scan_id'] : ''; $posted_token = isset( $_POST['scan_id'] ) ? sanitize_text_field( wp_unslash( $_POST['scan_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified by check_ajax_referer() above if ( '' !== $owner_token && ! hash_equals( $owner_token, $posted_token ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was started in another tab. Finish it from that tab, or wait for it to complete.', 'ai-cyberguard' ), ) ); } // FIX F-1 (audit 2026-05-25 round 2): refuse to persist a malware // scan result if the scan was not actually completed (init → // finalize without any batch calls). Persisting an empty findings // list as the "current" scan would silently overwrite genuine // earlier findings with "all clear". Same semantics as the integrity // scan's F-1 check in class-batch-scanner.php. $processed = isset( $state['processed'] ) ? (int) $state['processed'] : 0; $total = isset( $state['total'] ) ? (int) $state['total'] : 0; if ( $total > 0 && $processed < $total ) { // Don't release the lock — the user may want to resume via more // process_batch calls. Only the FAKE-completion path is rejected. wp_send_json_error( array( 'message' => __( 'Cannot finalize: malware scan is still in progress. Continue processing batches first, or use Cancel to start over.', 'ai-cyberguard' ), 'processed' => $processed, 'total' => $total, ) ); } // ACG-116-T3 (2026-07-05, Yossi): user-approved legitimate files ("This file is // legitimate — don't show it again"). An approval is HASH-ANCHORED: it silences a // file only while its bytes are identical to what the user approved. Any change // voids the approval automatically — the file reappears — because a legit file // backdoored later IS a content change, and that tripwire is the whole point. // Server-side defense: a file with any CONFIRMED (malware-class) finding is never // suppressed, even if an ack record exists for it. $gp_ack_hidden = 0; $gp_acks = GuardPress_File_Storage::load( 'acked_files', array(), 'scan' ); if ( is_array( $gp_acks ) && ! empty( $gp_acks ) && ! empty( $state['findings'] ) && is_array( $state['findings'] ) ) { foreach ( $state['findings'] as $gp_i => $gp_f ) { $gp_rel = isset( $gp_f['filepath'] ) ? (string) $gp_f['filepath'] : ''; if ( '' === $gp_rel || ! isset( $gp_acks[ $gp_rel ]['h'] ) ) { continue; } $gp_abs = ABSPATH . ltrim( $gp_rel, '/' ); // ACG-121 (audit 2026-07-16, check-no-follow gate): is_file() FOLLOWS a symlink, so an acked path // swapped to a link (or moved under a symlinked parent) was hashed THROUGH to an external target — // the one ungated site-source hash left in the tree. Adopt the shared no-follow contract here. // Refusing to hash keeps the finding SHOWN (fail-safe): an approval is honoured only for a real // in-install regular file. if ( ! self::is_safe_regular_file( $gp_abs ) ) { continue; } $gp_hash = @hash_file( 'sha256', $gp_abs ); if ( ! is_string( $gp_hash ) || '' === $gp_hash || ! hash_equals( (string) $gp_acks[ $gp_rel ]['h'], $gp_hash ) ) { continue; // content changed since approval → approval void → keep showing it } $gp_has_confirmed = false; foreach ( (array) ( $gp_f['findings'] ?? array() ) as $gp_fnd ) { if ( 'malware' === self::finding_verdict_class( $gp_fnd ) ) { $gp_has_confirmed = true; break; } } if ( $gp_has_confirmed ) { continue; // never hide a confirmed threat behind an approval } unset( $state['findings'][ $gp_i ] ); $gp_ack_hidden++; } if ( $gp_ack_hidden > 0 ) { $state['findings'] = array_values( $state['findings'] ); } } // FIX #7: Use Core Integrity results from init (already computed) $core_integrity = $state['core_integrity'] ?? self::check_core_integrity(); $extra_findings = array(); if ( ! empty( $core_integrity['modified'] ) || ! empty( $core_integrity['unknown'] ) ) { $extra_findings['core_integrity'] = $core_integrity; } // FIX (2026-06-13): attach origin-based advice + whether one-click Quarantine // is appropriate to each flagged file, so the results UI can warn correctly // (e.g. a legit premium-plugin eval shows "likely false positive" instead of a // scary HIGH with a destructive button). See origin_meta(). if ( ! empty( $state['findings'] ) && is_array( $state['findings'] ) ) { $sev_rank = array( 'info' => 0, 'low' => 1, 'medium' => 2, 'high' => 3, 'critical' => 4 ); foreach ( $state['findings'] as $i => $ff ) { // Highest severity among this file's findings → drives "treat as // suspicious" vs "likely false positive" wording for premium plugins. // ACG-113 (2026-07-04, Yossi): severity alone is the WRONG key for the advice // tone — a HIGH review-class pattern (e.g. a premium plugin's documented eval) // was getting the same "may contain a backdoor / REMOVE-REINSTALL" text as a // confirmed threat, contradicting the Review tier's own "not confirmed malware" // promise. Compute whether ANY finding on this file is CONFIRMED (malware-class) // and hand that to origin_meta(), which now picks the wording by VERDICT first. $sev = ''; $best = -1; $has_confirmed = false; if ( ! empty( $ff['findings'] ) && is_array( $ff['findings'] ) ) { foreach ( $ff['findings'] as $fnd ) { $s = isset( $fnd['severity'] ) ? strtolower( $fnd['severity'] ) : ''; $r = isset( $sev_rank[ $s ] ) ? $sev_rank[ $s ] : -1; if ( $r > $best ) { $best = $r; $sev = $s; } if ( 'malware' === self::finding_verdict_class( $fnd ) ) { $has_confirmed = true; } } } $meta = self::origin_meta( isset( $ff['origin'] ) ? $ff['origin'] : '', isset( $ff['origin_label'] ) ? $ff['origin_label'] : '', $sev, $has_confirmed ); $state['findings'][ $i ]['can_quarantine'] = $meta['can_quarantine']; $state['findings'][ $i ]['advice'] = $meta['advice']; $state['findings'][ $i ]['level'] = $meta['level']; $state['findings'][ $i ]['warn'] = $meta['warn']; // red crash-warning (UX 2026-06-19) $state['findings'][ $i ]['ext'] = $meta['ext']; // 'plugin'|'theme'|'' for the manage-screen link // ACG-110 (2026-07-03): stamp the VERDICT CLASS onto every finding AND onto the file, so the // results table can present CONFIRMED THREATS separately from review/changed/coverage items — // instead of dumping every finding into one table with a raw severity badge (which made // legitimate plugin code read as a wall of orange "threats"). The counts were already // verdict-class-correct (generate_summary); this carries the SAME classification to the UI. A // file is a "malware file" iff ANY of its findings is malware-class; otherwise it takes the // highest-priority non-malware class among its findings (suspicious > integrity > coverage > info). $file_class = 'info'; $class_rank = array( 'info' => 0, 'coverage' => 1, 'integrity' => 2, 'suspicious' => 3, 'malware' => 4 ); if ( ! empty( $ff['findings'] ) && is_array( $ff['findings'] ) ) { foreach ( $ff['findings'] as $j => $fnd ) { $vc = self::finding_verdict_class( $fnd ); $state['findings'][ $i ]['findings'][ $j ]['verdict'] = $vc; if ( ( $class_rank[ $vc ] ?? 0 ) > ( $class_rank[ $file_class ] ?? 0 ) ) { $file_class = $vc; } } } $state['findings'][ $i ]['verdict_class'] = $file_class; } } // ACG-121 B4 (audit 2026-07-16): fold the SCAN-TIME skips into the coverage accounting too. // $state['skipped'] counts files that were enqueued at discovery but refused at scan time — a path // swapped to a symlink/FIFO mid-scan (TOCTOU), or scan_file() returning the 'skipped' sentinel. // Those files were NEVER SCANNED, and the code at the increment sites already says "count it skipped // so the scan reads incomplete" — but only discovery_skipped was ever passed here, so coverage_complete // stayed true and the summary could report a green "site clean" while a file went uninspected. That is // the false all-clear RC-116/ACG-081 exist to prevent. On a normal healthy scan this value is 0, so // this does not start warning on every site (verified against the clean corpus). $gp_summary = self::generate_summary( $state['findings'], $state['verified_clean'] ?? 0, $core_integrity, (int) ( $state['discovery_skipped'] ?? 0 ), (int) ( $state['skipped'] ?? 0 ) ); $gp_summary['acknowledged_hidden'] = $gp_ack_hidden; // ACG-116-T3: shown as a calm "Approved & hidden" chip $result = array( 'scan_time' => time(), 'scan_type' => $state['scan_type'] ?? 'quick', 'total_files' => $state['total'], 'verified_clean' => $state['verified_clean'] ?? 0, 'scan_duration' => time() - ( $state['start_time'] ?? time() ), 'init_ms' => (int) ( $state['init_ms'] ?? 0 ), // PERF-116 telemetry: init-phase wall-clock 'file_findings' => $state['findings'], 'db_findings' => array(), 'extra_findings' => $extra_findings, 'summary' => $gp_summary ); // ACG-033-003 (audit 2026-06-20): bake an IMMUTABLE identity into the // persisted report so the read-back below can prove the exact bytes we // intended landed — not merely that *some* report carries the same // one-second scan_time. scan_id is the per-scan owner token; report_digest // is a SHA-256 over the full report content (computed before the digest // field itself is added, so it is non-circular). $result['scan_id'] = $owner_token; $result['report_digest'] = hash( 'sha256', (string) json_encode( $result ) ); // ACG-032-004 (audit 2026-06-20): treat the final-report write as a COMMIT // GATE. The report is the only durable record of this scan; the transient // scan state and the lock are what make the scan RESUMABLE. Previously a // failed save() was merely debug-logged and the code went on to delete the // state + release the lock + return success — silently DESTROYING the only // evidence and reporting "all done" when nothing was persisted. Now, if the // report cannot be written AND confirmed by a read-back, we keep BOTH the // scan state and the lock untouched, preserve any previous saved report // (we never overwrite/delete it on a failed write), and return a RETRYABLE // error so the user can re-finalize / the scan stays resumable. // BINLOG FIX: Save scan result to file ONLY — no DB fallback. // Deep scan results can be 2-4MB (thousands of findings + core_integrity). $report_saved = false; if ( class_exists( 'GuardPress_File_Storage' ) ) { if ( GuardPress_File_Storage::save( 'malware-last-scan', $result, 'cache' ) ) { // Read back to CONFIRM the bytes actually landed (save() can return // true on a buffered/partial write that a re-read won't return). // ACG-033-003 (audit 2026-06-20): the OLD check accepted ANY report // whose scan_time matched — but scan_time has one-second granularity // and is not an identity, so a stale/different report written in the // same second satisfied it (a fresh finding could be silently // replaced by a stale all-clear). Require the EXACT immutable // scan_id AND the canonical report_digest we just wrote to match. // (A truncated/partial write fails to JSON-decode, so a non-array or // a report missing these fields also fails — closing the original // buffered-write gap too.) $confirm = GuardPress_File_Storage::load( 'malware-last-scan', null, 'cache' ); $report_saved = ( is_array( $confirm ) && isset( $confirm['scan_id'], $confirm['scan_time'], $confirm['report_digest'] ) && hash_equals( (string) $result['scan_id'], (string) $confirm['scan_id'] ) && (int) $confirm['scan_time'] === (int) $result['scan_time'] && hash_equals( (string) $result['report_digest'], (string) $confirm['report_digest'] ) ); } } else { // No storage layer at all — cannot durably persist; treat as a failed // commit rather than silently dropping the report. $report_saved = false; } if ( ! $report_saved ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( 'GuardPress [Malware Scanner]: Final report could not be saved/confirmed — keeping scan state + lock so the scan is resumable.' ); } // COMMIT GATE FAILED: do NOT cleanup_scan_data(), do NOT release the // lock, do NOT clear the owner. The previous saved report is left as-is. wp_send_json_error( array( 'message' => __( 'The scan finished but its results could not be saved. Please click Finalize again to retry — your scan progress is preserved.', 'ai-cyberguard' ), 'retryable' => true, 'save_failed' => true, ) ); } // ───────────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R37-E (adversarial review of round 36) — ONLY A SCAN THAT ACTUALLY COVERED THE SITE // MAY RETIRE THE SCHEDULED RECORD. // // Round 36 cleared it here unconditionally, on the reasoning "a manual scan supersedes". The // comment said "this scan covered the whole site" and that was simply false: ajax_finalize_scan() // runs for the QUICK button too — the default one — which walks only wp-content + uploads and // only PHP-family extensions. So: the scheduled scan confirms a backdoor in the ABSPATH root (or // a .js in a theme, or a modified wp-includes file), the user sees the red notice, clicks the // scan button the notice sent them to, and the finalize deletes the only durable record of it — // then prints "your site looks clean". A false all-clear, produced by following our own advice. // // A FULL scan that reports complete coverage genuinely does supersede: it walked everything and // its own report is now the authority, so keeping the scheduled record would double-report. Any // narrower or incomplete scan leaves the record alone; it costs a duplicate row on screen, which // is the harmless direction. The user still has an explicit dismissal — the Clear Results button. $gp_sum = isset( $result['summary'] ) && is_array( $result['summary'] ) ? $result['summary'] : array(); if ( 'full' === ( $result['scan_type'] ?? '' ) && ! empty( $gp_sum['coverage_complete'] ) && method_exists( __CLASS__, 'clear_scheduled_findings' ) ) { self::clear_scheduled_findings(); } // FIX (audit 2026-06-10) / programmer review #3: record a TYPE_MALWARE // summary in the FREE-Plus Event Log (which defined the type but never // received scan results). Only AFTER the report is durably committed. self::log_scan_summary( $result, $core_integrity ); // ACG-035-003 (self-audit re-review 2026-06-20, HIGH): a NEWER scan may have taken over the // shared scan state WHILE we built/saved this report. RE-READ the live state and only delete // it (and release the lock) when it STILL belongs to the scan we just finalized — otherwise a // successor scan's state would be destroyed and its lock left orphaned. The release is // owner-bound (CAS) on the finalized scan's id, so it can never free a successor's lock. $caller_id = ! empty( $state['scan_id'] ) ? (string) $state['scan_id'] : ''; $live = self::load_scan_data( 'malware_state' ); $live_id = ( is_array( $live ) && isset( $live['scan_id'] ) ) ? (string) $live['scan_id'] : ''; if ( '' === $caller_id ) { // Legacy state with no owner token — preserve the prior unconditional cleanup. self::cleanup_scan_data(); GuardPress_Scan_Lock::release( 'malware', null ); } elseif ( $caller_id === $live_id && GuardPress_Scan_Lock::owns( 'malware', $caller_id ) && GuardPress_Scan_Lock::touch( 'malware', $caller_id ) ) { // ACG-036-003 / ACG-038-005 (audit 2026-06-21, HIGH): the live state still belongs to us // AND a successful owner-bound lease RENEWAL (touch() now returns bool) proves we still hold // the lock at commit time. touch() is the hard gate — if renewal fails (a successor took the // lock over near the stale boundary) we do NOT clean up, so a successor scan's state is never // erased. Release is owner-bound and frees ONLY our lock. ACG-038-013: the cleanup is also // generation-checked (delete malware_state only if it still carries OUR scan_id). self::cleanup_scan_data( false, $caller_id ); GuardPress_Scan_Lock::release( 'malware', $caller_id ); } // else: a successor scan now owns the shared state — leave its state + lock intact. The // report we saved belongs to THIS scan and is already durably committed for display. wp_send_json_success( array( 'result' => $result ) ); } /** * FIX (audit 2026-06-10): write one TYPE_MALWARE event summarising a finished * scan. Only logs when threats were actually found, to avoid noise. Never * fatal — wrapped so a logging error can't break the scan response. * * @param array $result finalize result array * @param array $core_integrity core integrity result */ private static function log_scan_summary( $result, $core_integrity ) { if ( ! class_exists( 'GuardPress_FreePlus_Event_Log' ) ) { return; } try { // ACG-122 note #3 (programmer review): this counted EVERY file finding as a threat, so the Event // Log recorded "Malware scan found N threats" for suspicious/integrity/coverage review items — // a permanent, alarming record of malware that was never found. The summary already computes the // verdict-class-aware count; use it as the single source of truth instead of recounting raw rows. // Fall back to the old count only if the summary is absent (a legacy cached result). $gp_sum = ( isset( $result['summary'] ) && is_array( $result['summary'] ) ) ? $result['summary'] : null; if ( null !== $gp_sum && isset( $gp_sum['total_threats'] ) ) { // total_threats already folds in the core-integrity malware; do not add core twice below. $file_threats = (int) $gp_sum['total_threats']; $gp_review = (int) ( $gp_sum['review_total'] ?? 0 ); $total = $file_threats; if ( $total < 1 ) { // No confirmed malware. Log a REVIEW event instead of a malware one, or nothing at all. if ( $gp_review > 0 ) { GuardPress_FreePlus_Event_Log::log( 'scan', sprintf( /* translators: 1: number of review items, 2: scan type */ _n( 'Malware scan found no malware; %1$d item to review (%2$s scan)', 'Malware scan found no malware; %1$d items to review (%2$s scan)', $gp_review, 'ai-cyberguard' ), $gp_review, (string) ( $result['scan_type'] ?? 'quick' ) ), array( 'file_threats' => 0, 'review_items' => $gp_review ) ); } return; } GuardPress_FreePlus_Event_Log::log( 'malware', sprintf( /* translators: 1: total threats, 2: scan type */ _n( 'Malware scan found %1$d threat (%2$s scan)', 'Malware scan found %1$d threats (%2$s scan)', $total, 'ai-cyberguard' ), $total, (string) ( $result['scan_type'] ?? 'quick' ) ), array( 'file_threats' => $total, 'review_items' => $gp_review ) ); return; } $file_threats = is_array( $result['file_findings'] ?? null ) ? count( $result['file_findings'] ) : 0; $core_threats = 0; if ( is_array( $core_integrity ) ) { $core_threats += is_array( $core_integrity['modified'] ?? null ) ? count( $core_integrity['modified'] ) : 0; // RC-112-04 review: count only real threats (critical/high/medium) in the // unknown bucket — low-severity coverage notices (e.g. an oversize-config or // chain-scan-limit notice) must not log a phantom "1 threat" on a clean site. if ( is_array( $core_integrity['unknown'] ?? null ) ) { foreach ( $core_integrity['unknown'] as $u ) { $sev = is_array( $u ) ? strtolower( (string) ( $u['severity'] ?? 'high' ) ) : 'high'; if ( 'critical' === $sev || 'high' === $sev || 'medium' === $sev ) { $core_threats++; } } } } $total = $file_threats + $core_threats; if ( $total < 1 ) { return; // a clean scan is not logged as an event } GuardPress_FreePlus_Event_Log::log( 'malware', sprintf( /* translators: 1: total threats, 2: scan type */ _n( 'Malware scan found %1$d threat (%2$s scan)', 'Malware scan found %1$d threats (%2$s scan)', $total, 'ai-cyberguard' ), $total, (string) ( $result['scan_type'] ?? 'quick' ) ), array( 'file_threats' => $file_threats, 'core_threats' => $core_threats ) ); } catch ( \Throwable $e ) { // swallow — logging must never break the scan } } // ==================== CORE INTEGRITY CHECK ==================== private static function check_core_integrity() { $result = array( 'modified' => array(), 'unknown' => array(), 'missing' => array(), 'verified' => 0, 'status' => 'ok' ); $checksums = self::get_core_checksums(); $have = ! empty( $checksums ); if ( ! $have ) { // RC-108-02 (audit 2026-06-17): do NOT bail out when the official // checksums are unavailable. We cannot md5-verify, nor list "unknown" // core files (that needs the official set), but the .htaccess-handler + // PHP-in-asset CHAIN detection below is CONTENT-based and MUST still run // — otherwise a ".htaccess: AddHandler ... .ico" + shell.ico back-door is // silently missed whenever the checksum API is blocked/down. We mark // status=error (verification incomplete) but continue to the chain scan. $result['status'] = 'error'; $checksums = array(); } if ( $have ) { foreach ( $checksums as $file => $expected_md5 ) { if ( empty( $expected_md5 ) ) continue; if ( strpos( $file, 'wp-admin/' ) !== 0 && strpos( $file, 'wp-includes/' ) !== 0 && strpos( $file, '/' ) !== false ) { continue; } $path = ABSPATH . $file; clearstatcache( false, $path ); if ( ! file_exists( $path ) ) { // RC-116-02 (audit 2026-06-18): an official core file that is MISSING on // disk must be reported, not silently skipped — a removed core file can be // the result of a compromise, a partial cleanup or disk failure, and the // verdict must not read "verified/clean". Record it (high) so it counts as // a threat and prevents a clean verdict; advise reinstalling core. $result['missing'][] = $file; $result['unknown'][] = array( 'file' => $file, 'location' => 'core_missing', 'severity' => 'high', 'description' => __( 'An official WordPress core file is missing. Re-install WordPress (Dashboard → Updates → Re-install) to restore it.', 'ai-cyberguard' ), ); continue; } // ACG-082-002 / ACG-083-001 (audit 2026-06-27, HIGH): a core file replaced by a SYMLINK — or reachable // only THROUGH a symlinked core DIRECTORY (e.g. wp-includes -> external tree) — must NEVER be hashed // THROUGH the link and counted "verified". is_link($path) alone tested only the basename, so a // symlinked ANCESTOR slipped past (the final file is a regular file, md5_file() then hashes the external // target). The shared contract requires NO symlink path component and a regular file resolving inside // the real install; otherwise report unknown (high) and never verify. Core paths are never links. if ( ! self::is_safe_regular_file( $path ) ) { $result['unknown'][] = array( 'file' => $file, 'location' => 'core_symlink', 'severity' => 'high', 'description' => __( 'An official WordPress core file has been replaced by a symbolic link or a special file. Core files are never links — re-install WordPress (Dashboard → Updates → Re-install) to restore the genuine file.', 'ai-cyberguard' ), ); continue; } $actual_md5 = @md5_file( $path ); if ( $actual_md5 && $actual_md5 === $expected_md5 ) { $result['verified']++; } else { $result['modified'][] = array( 'file' => $file, 'expected' => $expected_md5, 'actual' => $actual_md5, ); } } } $dirs_to_check = array( ABSPATH . 'wp-admin/' => 'wp-admin/', ABSPATH . 'wp-includes/' => 'wp-includes/', ); // RC-106-01 FIX (audit 2026-06-17): walk the core directories RECURSIVELY. // The old glob( $dir . '*.php' ) only saw the TOP level, so a back-door at // e.g. wp-includes/images/shell.php was never flagged as "unknown". We flag // any risky file inside a core folder that is not in the official // WordPress.org checksums. The list covers the PHP-family executables PLUS // js and svg — the browser-executed asset types attackers hide payloads in. // Every legitimate core .js/.svg IS present in the checksums, so a stock // core is not flagged. We deliberately do NOT include html/htm/ico here: // WordPress ships none of those inside wp-admin/wp-includes, so they could // never match a checksum, and the empty index.html "directory-silence" // files that hardening tools drop into every folder would become noisy // false positives. (A standalone html/ico payload is inert without a PHP // includer, which IS in this list and IS flagged.) $core_dir_ext = array_merge( self::php_family_exts(), array( 'js', 'svg' ) ); // RC-108-01: single source // RC-107-02 FIX (audit 2026-06-17): also detect the ".htaccess + .ico" // execution chain inside a core folder. A server CONFIG file that rewrites a // non-PHP extension to run AS PHP, and a data/asset file that actually // contains PHP, are both flagged — but only on real evidence, so a benign // "deny from all" .htaccess, a blank index.html, or a real favicon.ico are // NOT false-positived. // RC-109-02: patterns come from the single shared source so core and // non-core (deep-scan walker) detect the same chain identically. $config_names = self::exec_chain_config_names(); $asset_ext = self::exec_chain_asset_exts(); $handler_re = self::exec_chain_handler_re(); $php_open_re = self::exec_chain_php_marker_re(); // RC-116-04: core execution-chain detection now uses the SAME engine as non-core // (1 MB read, mapped-extension extraction, recursive scope scan, auto_prepend // resolution, oversize/limit coverage notices). Shared budget bounds the work. $cc_core_root = wp_normalize_path( rtrim( ABSPATH, '/\\' ) ); $cc_core_prefixes = array( $cc_core_root . '/wp-admin/', $cc_core_root . '/wp-includes/' ); $cc_budget = 5000; $cc_limited = false; foreach ( $dirs_to_check as $dir => $prefix ) { // ACG-087-001 (audit 2026-06-28, HIGH): a WordPress core folder (wp-admin / wp-includes) is NEVER // legitimately a symbolic link. If it is one, is_dir() FOLLOWS it and the recursive walker below would read // an EXTERNAL tree as core (and read config bytes through it). Report it HIGH and refuse to descend — this // is independent of whether the official checksums are available, so a symlinked core folder is flagged // even OFFLINE (when the per-file checksum branch cannot run). clearstatcache( false, rtrim( $dir, '/\\' ) ); if ( @is_link( rtrim( $dir, '/\\' ) ) ) { $result['unknown'][] = array( 'file' => $prefix, 'location' => 'core_dir', 'severity' => 'high', 'description' => __( 'A WordPress core folder (wp-admin / wp-includes) has been replaced by a symbolic link. Core folders are never links — re-install WordPress (Dashboard → Updates → Re-install) to restore the genuine folder.', 'ai-cyberguard' ), ); continue; } if ( ! is_dir( $dir ) ) continue; // ACG-088-002 (audit 2026-06-28, HIGH): a core FILE or a NESTED directory under wp-admin/wp-includes is // NEVER legitimately a symbolic link. A RecursiveCallbackFilterIterator PRUNES any symlinked entry (so a // symlinked nested directory is never descended → its external tree is never read) AND records it for a // HIGH report below. This runs in the iterator callback — independent of whether the official checksums // are available — so a symlinked core file/dir is reported even OFFLINE (the per-file checksum branch, // which previously held the only per-entry symlink awareness, does not run offline). $core_symlinks = array(); try { $rdi = new RecursiveDirectoryIterator( $dir, FilesystemIterator::SKIP_DOTS ); $filter = new RecursiveCallbackFilterIterator( $rdi, function ( $cur ) use ( &$core_symlinks, $dir, $prefix ) { if ( @is_link( $cur->getPathname() ) ) { $core_symlinks[ $prefix . ltrim( str_replace( '\\', '/', substr( $cur->getPathname(), strlen( $dir ) ) ), '/' ) ] = true; return false; // prune: never descend a symlinked dir, never yield a symlinked file } return true; } ); $it = new RecursiveIteratorIterator( $filter, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD ); } catch ( \Throwable $e ) { continue; } foreach ( $it as $fileObj ) { if ( ! $fileObj->isFile() ) continue; $abs = $fileObj->getPathname(); $name = strtolower( $fileObj->getFilename() ); $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) ); $rel_under_dir = ltrim( str_replace( '\\', '/', substr( $abs, strlen( $dir ) ) ), '/' ); $relative = $prefix . $rel_under_dir; // (1) Risky executable/script extension not in the official checksums. // Gated on $have: without the official set we cannot tell a legit core // file from a planted one, so listing "unknown" here would flag EVERY // core file (a false-positive flood). Offline, these core executables // are instead content-scanned by the file walker (scan_file_uncached's // core_unverifiable branch, since the walker keeps core dirs when // checksums are unavailable — see ajax_init_scan). if ( in_array( $ext, $core_dir_ext, true ) ) { if ( $have && ! isset( $checksums[ $relative ] ) ) { $result['unknown'][] = array( 'file' => $relative, 'location' => 'core_dir', 'severity' => 'high' ); } continue; } // (2) RC-116-04: a server config file in a core dir that turns an inert // extension into PHP — analysed with the SAME full engine as non-core: // 1 MB read, mapped-extension extraction, recursive scope scan (here we DO // descend into core subdirs), auto_prepend/append resolution and oversize/ // limit coverage notices. (Previously this read only 64 KB and flagged the // config alone, missing long configs, mapped .txt/.bin and prepend targets.) if ( in_array( $name, $config_names, true ) ) { // ACG-087-001 (audit 2026-06-28, HIGH): defence-in-depth for a symlink DEEPER inside a real core // dir — never read a core config file THROUGH a symlink path component or from a non-regular file // (FIFO would HANG). An unsafe config path is skipped (no external bytes read, no hang). if ( ! self::is_safe_regular_file( $abs ) ) { continue; } $cc_head = (string) @file_get_contents( $abs, false, null, 0, 1048576 ); $cc_size = @filesize( $abs ); $cc_oversize = ( false !== $cc_size && $cc_size > 1048576 ); $cc_handler = ( '' !== $cc_head && preg_match( $handler_re, $cc_head ) ); if ( $cc_handler || $cc_oversize ) { $cfg_dir = dirname( $abs ); // auto_prepend / auto_append targets (run as PHP regardless of ext) if ( $cc_handler ) { $cc_ap = self::scan_auto_prepend_targets( $cc_head, $cfg_dir, $cc_core_root ); if ( $cc_ap ) { $result['unknown'][] = array( 'file' => $relative, 'location' => 'core_dir', 'severity' => 'high' ); foreach ( $cc_ap as $cc_rel => $cc_f ) { $cc_f['location'] = 'core_dir'; $result['unknown'][] = $cc_f; } } } // scope scan of the config's directory subtree for mapped/inert assets. // PERF-116-01: only scan when something actually maps a NON-PHP file to // PHP (explicit inert ext, broad handler, or an oversize config we could // not fully read). A PHP-only mapping / auto_prepend-only config maps no // inert asset, so the recursive read is skipped. $cc_plan = $cc_handler ? self::exec_chain_scope_plan( $cc_head ) : array( 'exts' => array(), 'all' => false ); $cc_exts = $cc_plan['exts']; $cc_all = ! empty( $cc_plan['all'] ); // RC-118-02: broad handler -> scan every non-walker file if ( $cc_oversize ) { $cc_all = true; } if ( $cc_all || ! empty( $cc_exts ) ) { $cc_scope_lim = false; $cc_payloads = self::scan_chain_scope_for_payloads( $cfg_dir, $cc_exts, $cc_core_root, $cc_core_prefixes, $cc_scope_lim, $cc_budget, false, $cc_all ); if ( $cc_scope_lim ) { $cc_limited = true; } if ( $cc_payloads ) { $result['unknown'][] = array( 'file' => $relative, 'location' => 'core_dir', 'severity' => 'high' ); foreach ( $cc_payloads as $cc_rel => $cc_f ) { $cc_f['location'] = 'core_dir'; $result['unknown'][] = $cc_f; } } } if ( $cc_oversize ) { $result['unknown'][] = array( 'file' => sprintf( /* translators: %s: relative path of the server-config file */ __( 'A core server-config file (%s) is larger than 1 MB and was only partially inspected for PHP-handler directives — review it manually.', 'ai-cyberguard' ), $relative ), 'location' => 'core_dir', 'severity' => 'low', ); } } continue; } // (3) A data/asset file that actually contains PHP — a payload // disguised as an image/html to be run via (2). Only non-checksummed // assets are read, and only those containing a " $relative, 'location' => 'core_dir', 'severity' => 'high' ); } elseif ( $oversize ) { $result['unknown'][] = array( 'file' => $relative, 'location' => 'core_dir', 'severity' => 'medium' ); } continue; } } // ACG-088-002 (audit 2026-06-28, HIGH): report each symbolic-link found in a core folder (a core file OR a // nested directory) as HIGH — independent of checksum availability, so it fires OFFLINE too. The walker // already pruned these (never read their targets); listing them prevents a "verified/clean" verdict. foreach ( array_keys( $core_symlinks ) as $sym_rel ) { $result['unknown'][] = array( 'file' => $sym_rel, 'location' => 'core_dir', 'severity' => 'high', 'description' => __( 'A WordPress core file or folder has been replaced by a symbolic link. Core files are never links — re-install WordPress (Dashboard → Updates → Re-install) to restore the genuine files.', 'ai-cyberguard' ), ); } } // RC-108-01 follow-up (round-9 review): enumerate the full PHP-family at the // site root too, so an unexpected root-level evil.php8 / shell.pht is listed // as an "unknown root file" — not just .php. (The deep-scan walker already // content-scans these; this keeps the dedicated root listing consistent.) $root_files = array(); foreach ( self::php_family_exts() as $fx ) { $g = glob( ABSPATH . '*.' . $fx ); if ( $g ) { $root_files = array_merge( $root_files, $g ); } } // ACG-120-001 (2026-07-05, Yossi's report): a foreign COPY of an execution-capable config // file (e.g. "web - YOSEFA.config", "web.config.bak", ".htaccess copy") never entered the // root listing because only PHP-family files were globbed — yet web.config / .htaccess / // .user.ini can execute code and rewrite requests (see exec_chain_config_names). Sweep the // real root for config-family files whose name is NOT the exact legitimate one and flag // them, mirroring the wp-config-copy rule. $gp_cfg_bases = self::exec_chain_config_names(); // .htaccess, .user.ini, user.ini, web.config $gp_cfg_glob = array(); foreach ( array( 'config', 'htaccess', 'ini', 'bak', 'backup', 'old', 'orig', 'copy', 'save', 'tmp' ) as $ce ) { $g1 = glob( ABSPATH . '*.' . $ce ); if ( $g1 ) { $gp_cfg_glob = array_merge( $gp_cfg_glob, $g1 ); } } $g2 = glob( ABSPATH . '*config*' ); // catches "web - X.config", "web.config copy", spaced names if ( $g2 ) { $gp_cfg_glob = array_merge( $gp_cfg_glob, $g2 ); } $gp_cfg_glob = array_values( array_unique( $gp_cfg_glob ) ); foreach ( $gp_cfg_glob as $gp_cf ) { if ( ! @is_file( $gp_cf ) || @is_link( $gp_cf ) ) { continue; } $gp_bn = basename( $gp_cf ); $gp_bn_lc = strtolower( $gp_bn ); // Skip PHP-family (already listed) and the exact legitimate config names. $gp_ext = strtolower( (string) pathinfo( $gp_bn, PATHINFO_EXTENSION ) ); if ( in_array( $gp_ext, self::php_family_exts(), true ) ) { continue; } if ( in_array( $gp_bn_lc, array_map( 'strtolower', $gp_cfg_bases ), true ) ) { continue; } // exact legit config // Does the name resemble an execution-capable config file (web.config / .htaccess / // .user.ini) without BEING the exact legit name? Then it is a foreign/backup copy. $gp_is_cfg_copy = false; foreach ( $gp_cfg_bases as $gp_legit ) { $gp_stem = preg_quote( $gp_legit, '/' ); if ( preg_match( '/' . $gp_stem . '/i', $gp_bn ) ) { $gp_is_cfg_copy = true; break; } } // Also catch "." and spaced "web - x.config" forms explicitly. if ( ! $gp_is_cfg_copy && preg_match( '/(web\s*[-_. ].*\.config|\.htaccess[ ._-].*|web\.config[ ._-].+)/i', $gp_bn ) ) { $gp_is_cfg_copy = true; } if ( $gp_is_cfg_copy ) { $result['unknown'][] = array( 'file' => $gp_bn, 'location' => 'root_suspicious', 'severity' => 'critical', 'description' => __( 'This is a copy or backup of a server configuration file (such as web.config or .htaccess) sitting in your site root. These files can execute code and redirect requests, and a stray copy is a common way to hide a backdoor or leak settings. If you did not create it intentionally, delete it.', 'ai-cyberguard' ), ); } } $known_root = array( 'index.php','wp-activate.php','wp-blog-header.php','wp-comments-post.php','wp-config.php','wp-config-sample.php', 'wp-cron.php','wp-links-opml.php','wp-load.php','wp-login.php','wp-mail.php','wp-settings.php','wp-signup.php', 'wp-trackback.php','xmlrpc.php' ); $known_plugin_files = array( 'wordfence-waf.php', 'sucuri-scanner.php', 'advanced-cache.php', 'wp-cache-phase1.php', 'wp-cache-phase2.php', 'object-cache.php', 'wp-cache-config.php', 'db.php', 'db-error.php', 'sunrise.php', 'blog-deleted.php', 'blog-inactive.php', 'blog-suspended.php', 'starter.php', 'starter-starter.php', 'iwp-client.php', 'mwp-cron.php', 'maintenance.php', 'health-check-disable-plugins.php', 'license.php', 'favicon.ico', ); $suspicious_core_patterns = array( '/^wp-config.*\.(bak|backup|old|orig|copy|txt|save|tmp)$/i', '/^wp-config\s*[-_]?\s*(copy|backup|old|bak|\d+)/i', '/^wp-config\s+-\s+copy/i', // ACG-111 (2026-07-03, from Yossi's real scan): ANY root file whose name starts with // "wp-config" and is not exactly wp-config.php / wp-config-sample.php is a credential- // exposure copy regardless of the suffix word ("wp-config - YOSEFA.php" escaped the // copy-word list above and was classed a mere HIGH "unknown"). The AI analyzer already // applies this exact prefix rule (class-ai-analyzer.php); the integrity scan now // matches it. The two legitimate names never reach this loop (known_root skips them). '/^wp-config(?!\.php$|-sample\.php$)/i', '/^wp-login.*\.(bak|backup|old|orig|copy)$/i', '/^\.(php|phtml|php[0-9]+)$/i', '/^[a-f0-9]{32,}\.php$/i', ); if ( $root_files ) { foreach ( $root_files as $filepath ) { $filename = basename( $filepath ); if ( in_array( $filename, $known_root, true ) ) { continue; } // FIX FP-Emergency (audit 2026-05-25 round 3): emergency.php // is a recovery file dropped into the WordPress root by the // GuardPress PRO plugin (per the PRO spec — see // "guardpress_install_emergency_recovery" in the PRO main file). // When PRO is deactivated, the file remains for emergency // access. The FREE scanner has no awareness of PRO, so it // previously flagged emergency.php as "Unknown File in Root" // with HIGH severity — alarming the admin about their OWN // recovery tool. // // Verification approach: read the file's first 1 KB and look // for the GuardPress ownership marker (a comment with our // plugin URL or distinctive class name). If found, treat as // INFO ("recognized recovery file"). If a file with that name // exists but lacks the marker, it's an attacker-planted file // and we keep the HIGH "unknown" alert. if ( strcasecmp( $filename, 'emergency.php' ) === 0 ) { $is_ours = self::is_guardpress_owned_file( $filepath ); if ( $is_ours ) { $result['unknown'][] = array( 'file' => $filename, 'location' => 'root_plugin', 'severity' => 'info', 'description' => __( 'GuardPress PRO recovery file — present by design.', 'ai-cyberguard' ), ); continue; } // Falls through to the normal "unknown" path — a file // named emergency.php WITHOUT our marker IS suspicious. } $is_suspicious_copy = false; // ACG-111 (2026-07-03, from Yossi's real scan): LOOKALIKE detection. His site showed // "wp-config-sample.php" as a HIGH "Unknown File in Root" even though that exact name // is in $known_root — which is only possible when the on-disk name differs from the // known name at the byte level (hidden Unicode characters, trailing/embedded spaces, // or unusual casing on a case-preserving filesystem). That byte difference is a // classic disguise for planted files, so we must NOT loosen the strict known_root // match above. Instead, when an unknown root file's NORMALIZED name (lowercased, // whitespace and invisible/bidi characters stripped) equals a known core name, we // say exactly that — an explicit, actionable verdict instead of a confusing generic // "unknown" on what looks like a stock WordPress file. $stripped = preg_replace( '/[\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}\x{FEFF}\x{00A0}]/u', '', $filename ); if ( ! is_string( $stripped ) ) { $stripped = $filename; } // ACG-112 (2026-07-04, from Yossi's fresh v1.0.111 scan): his wp-config-sample.php row // is STILL root_unknown — so the byte difference is not whitespace/invisibles/casing. // The remaining realistic disguises: (a) a Unicode dash that looks like '-', and // (b) Cyrillic/Greek homoglyph letters. Fold both before comparing: the Unicode // hyphen family becomes ASCII '-', and common Latin-lookalike letters map to their // Latin twins (fixed curated map, not a full confusables table). $folded = preg_replace( '/[\x{00AD}\x{2010}-\x{2015}\x{2212}\x{FE58}\x{FE63}\x{FF0D}]/u', '-', $stripped ); if ( ! is_string( $folded ) ) { $folded = $stripped; } $folded = strtr( $folded, array( 'а' => 'a', 'с' => 'c', 'е' => 'e', 'о' => 'o', 'р' => 'p', 'х' => 'x', 'у' => 'y', 'і' => 'i', 'ѕ' => 's', 'ј' => 'j', 'ԁ' => 'd', 'һ' => 'h', 'ɡ' => 'g', 'ν' => 'v', 'А' => 'A', 'В' => 'B', 'С' => 'C', 'Е' => 'E', 'Н' => 'H', 'К' => 'K', 'М' => 'M', 'О' => 'O', 'Р' => 'P', 'Т' => 'T', 'Х' => 'X', 'Ѕ' => 'S', 'І' => 'I', 'Ј' => 'J', 'ο' => 'o', 'α' => 'a', 'ρ' => 'p', 'τ' => 't', 'υ' => 'u', 'ω' => 'w', 'ε' => 'e', ) ); $norm_name = strtolower( preg_replace( '/\s+/', '', $folded ) ); if ( in_array( $norm_name, $known_root, true ) ) { $result['unknown'][] = array( 'file' => $filename, 'location' => 'root_lookalike', 'severity' => 'high', 'description' => __( 'This file\'s name looks identical to a standard WordPress core file, but it is NOT that file — the name differs by hidden characters, spaces or unusual casing. This is a common disguise for planted files. If you did not create it yourself, quarantine it.', 'ai-cyberguard' ), ); continue; } foreach ( $suspicious_core_patterns as $pattern ) { if ( preg_match( $pattern, $filename ) ) { $is_suspicious_copy = true; break; } } if ( $is_suspicious_copy ) { $result['unknown'][] = array( 'file' => $filename, 'location' => 'root_suspicious', 'severity' => 'critical' ); } elseif ( in_array( strtolower( $filename ), array_map( 'strtolower', $known_plugin_files ), true ) ) { $result['unknown'][] = array( 'file' => $filename, 'location' => 'root_plugin', 'severity' => 'info' ); } else { // ACG-112 (2026-07-04): self-diagnosing "unknown root file". When the RAW name // contains bytes outside printable ASCII (hidden Unicode, control chars, odd // punctuation the folders above did not map), SAY SO and show the bytes — the // user (and we, remotely) can finally see WHY a file that displays like a stock // WordPress name is not recognized. Capped so a hostile long name cannot bloat // the report. $entry = array( 'file' => $filename, 'location' => 'root_unknown', 'severity' => 'high' ); $odd = ''; $fl = strlen( $filename ); for ( $ci = 0; $ci < $fl; $ci++ ) { $cb = ord( $filename[ $ci ] ); if ( $cb < 0x20 || $cb > 0x7E ) { $odd .= sprintf( '%02X ', $cb ); if ( strlen( $odd ) >= 48 ) { $odd .= '…'; break; } } } if ( '' !== $odd ) { $entry['description'] = sprintf( /* translators: %s: hex bytes of the hidden/non-standard characters found in the file name */ __( 'Unrecognized file in site root. NOTE: the file name contains hidden or non-standard characters (bytes: %s) — a common disguise for planted files. If you did not create this file yourself, quarantine it.', 'ai-cyberguard' ), trim( $odd ) ); } $result['unknown'][] = $entry; } } } if ( ! empty( $result['modified'] ) ) { $result['status'] = 'critical'; } elseif ( ! empty( $result['unknown'] ) ) { $result['status'] = 'warning'; } return $result; } /** * FIX FP-Emergency helper (audit 2026-05-25 round 3, hardened round 4): * detect whether a file at the WP root that "looks like" a GuardPress- * owned drop-in (e.g. emergency.php, php-error.php) actually belongs to * the GuardPress plugin family. * * Two-tier check, in order: * * 1. **File content check** — read the first 8 KB and look for any of * these markers (case-insensitive). 8 KB is generous because some * drop-ins (emergency.php specifically) have a large ASCII-art * header before the actual @package / class names appear. * - "guardpress.ai" — @link / homepage URL * - "GuardPress" — class names, @package, @author * - "GUARDPRESS_VERSION" — main plugin constant * - "GP_EMERGENCY_VERSION" — emergency.php's own version constant * - "GP_EMERGENCY" — generic GP emergency-recovery prefix * - "GP_MAX_LOGIN_ATTEMPTS" — distinctive emergency.php constant * - "ai-cyberguard" — text-domain + plugin slug * - "GP_SNAPSHOT_DIR" — emergency.php uses this for storage * * RC-111-05 (audit 2026-06-18): a former "installed-plugin fallback" — which * trusted ANY root drop-in whenever a GuardPress-family plugin was installed — * was REMOVED. That condition is always true while this scanner runs, so it let * an attacker-planted emergency.php with no marker be downgraded to INFO. * * Recognition is now content-only: the file must carry a genuine ownership marker * in its own first 8 KB. An unverified or unreadable file is NOT trusted (fails * closed → stays High/Unknown). * * @param string $filepath Absolute path to the candidate file. * @return bool True iff the file is recognised as GuardPress-owned. */ private static function is_guardpress_owned_file( $filepath ) { // ─── Tier 1: file content check ──────────────────────────────── // ACG-086 sweep (audit 2026-06-28): never read a header THROUGH a symlink component or from a non-regular file // (FIFO would HANG). An unsafe path is NOT treated as a GuardPress-owned file (no whitelist). if ( self::is_safe_regular_file( $filepath ) && @is_readable( $filepath ) ) { $handle = @fopen( $filepath, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- direct filesystem read required by the malware scanner to inspect file headers; WP_Filesystem is unsuitable here if ( $handle ) { $head = @fread( $handle, 8192 ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- 8 KB header read required by the malware scanner to inspect file headers; WP_Filesystem is unsuitable here @fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- direct filesystem read required by the malware scanner to inspect file headers; WP_Filesystem is unsuitable here if ( is_string( $head ) && $head !== '' ) { static $markers = array( 'guardpress.ai', 'GuardPress', 'GUARDPRESS_VERSION', 'GP_EMERGENCY_VERSION', 'GP_EMERGENCY', 'GP_MAX_LOGIN_ATTEMPTS', 'GP_SNAPSHOT_DIR', 'ai-cyberguard', ); $marker_found = false; foreach ( $markers as $marker ) { if ( stripos( $head, $marker ) !== false ) { $marker_found = true; break; } } if ( $marker_found ) { // RC-112-08 (audit 2026-06-18): the markers above are PUBLIC, // copyable strings (our plugin URL, constant names). A marker on // its own must NOT confer a "safe — present by design" verdict. // A genuine recovery drop-in never contains code-execution sinks; // a planted file that pairs our marker with a webshell payload is // a SPOOF. If the header shows classic execution-sink indicators, // the marker is disregarded and the file stays Unknown/High (and // its content scan still reports the payload separately). $danger_re = self::_d( 'L1xiKD86ZXZhbHxhc3NlcnR8Y3JlYXRlX2Z1bmN0aW9ufHN5c3RlbXxzaGVsbF9leGVjfHBhc3N0aHJ1fHByb2Nfb3Blbnxwb3BlbilccypcKHxcYmJhc2U2NF9kZWNvZGVccypcKHxcYmd6KD86aW5mbGF0ZXx1bmNvbXByZXNzKVxzKlwofFxic3RyX3JvdDEzXHMqXCgvaQ==' ); if ( preg_match( $danger_re, $head ) ) { return false; } return true; } } } } // RC-111-05 (audit 2026-06-18): the previous "Tier 2" trusted ANY root drop-in as // long as a GuardPress-family plugin was installed — a condition that is ALWAYS // true while this scanner is running, so an attacker-planted emergency.php with no // marker was wrongly downgraded to INFO. That fallback is REMOVED. A recovery file // is recognised ONLY by a genuine ownership marker in its own content (Tier 1 // above); an unverified or unreadable file stays High/Unknown. return false; } /** * RC-114-01 (audit 2026-06-18): package-integrity manifest, redesigned so it is NOT a * forgeable trust anchor (the RC-112-06 version was mutable PHP, loaded with include(), * and trusted by path — an attacker could edit it to "bless" a tampered file). * * Now: the manifest is DATA (manifest.json), read with file_get_contents (NEVER * include/require), and trusted ONLY when its OWN sha256 equals the GUARDPRESS_MANIFEST_SHA256 * constant compiled into the main plugin file. Editing manifest.json to add an * attacker-chosen hash changes its sha256 → it no longer matches the constant → the * whole manifest is rejected → every file in our folder is SCANNED (never "trusted"). * Forging it would require editing the main executable plugin file's constant too — the * documented limit of any self-integrity check once an attacker already has write access. * * @return array verified path => sha256 map, or [] when unverifiable */ private static function self_manifest() { static $cache = null; if ( null !== $cache ) { return $cache; } $cache = array(); if ( ! defined( 'GUARDPRESS_MANIFEST_SHA256' ) || '' === (string) GUARDPRESS_MANIFEST_SHA256 ) { return $cache; // no anchor compiled in → trust nothing } $file = __DIR__ . '/manifest.json'; if ( ! @is_file( $file ) ) { return $cache; } $raw = @file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- DATA-only read; the manifest must never be executed if ( ! is_string( $raw ) || '' === $raw ) { return $cache; } if ( ! hash_equals( (string) GUARDPRESS_MANIFEST_SHA256, hash( 'sha256', $raw ) ) ) { return $cache; // manifest tampered / stale → reject → scan everything } $data = json_decode( $raw, true ); if ( is_array( $data ) ) { $cache = $data; } return $cache; } /** * RC-114-01: true ONLY for a file inside our own install dir whose sha256 matches the * VERIFIED manifest (genuine, shipped, unmodified). A file that is added, modified, or * present when the manifest cannot be verified is NOT trusted → the caller scans it like * any other file (so a planted shell or a tampered own file is always caught). */ private static function is_unmodified_own_file( $fp ) { if ( ! defined( 'GUARDPRESS_PLUGIN_DIR' ) ) { return false; } $self_dir = rtrim( wp_normalize_path( GUARDPRESS_PLUGIN_DIR ), '/' ) . '/'; $fp_n = wp_normalize_path( $fp ); if ( strpos( $fp_n, $self_dir ) !== 0 ) { return false; // not our file } $manifest = self::self_manifest(); if ( empty( $manifest ) ) { return false; // manifest missing/unverified → SCAN, never trust } $rel = substr( $fp_n, strlen( $self_dir ) ); if ( ! isset( $manifest[ $rel ] ) ) { return false; // added file (incl. manifest.json itself, deliberately not listed) → scan } // ACG-086-001 (audit 2026-06-28, HIGH): never hash_file() the candidate THROUGH a symlink path component or on // a non-regular file to trust it as an UNMODIFIED own-plugin file. A parent directory swapped to a symlink whose // external target matches the manifest hash would otherwise be trusted-and-skipped (a scan bypass), and a FIFO // would HANG hash_file(). The shared no-symlink-component + regular-file contract refuses both — an unsafe // own-file path is NOT trusted (returns false → it is scanned). if ( ! self::is_safe_regular_file( $fp_n ) ) { return false; } $hash = @hash_file( 'sha256', $fp_n ); return ( is_string( $hash ) && hash_equals( (string) $manifest[ $rel ], $hash ) ); } public static function ajax_cancel_scan() { check_ajax_referer( 'guardpress_batch_scan', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => 'Permission denied' ) ); return; } // ADDL-1 (audit 2026-06-19): owner-bound cancel closes the cross-tab Cancel // hijack — a second tab (which never started this scan and so has no matching // scan_id) must not be able to abort the running scan or wipe its state. // ACG-033-002 (audit 2026-06-20): the old code kept a tokenless escape hatch // (a request with NO scan_id could cancel any owned scan) — a hijack. It is // removed: when the scan STATE carries an owner token, the caller MUST present // a matching token, or the request is refused with NO side effects. The // admin's own in-page Cancel always sends its token; a crashed scan whose lock // was left behind still auto-recovers after 30 min (GuardPress_Scan_Lock // MAX_AGE), and a Cancel on a scan with NO usable state (empty owner) still // falls through and cleans up, so nothing can be permanently wedged. $posted_token = isset( $_POST['scan_id'] ) ? sanitize_text_field( wp_unslash( $_POST['scan_id'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified by check_ajax_referer() above $state = self::load_scan_data( 'malware_state' ); $owner_token = ( is_array( $state ) && isset( $state['scan_id'] ) ) ? (string) $state['scan_id'] : ''; if ( '' !== $owner_token && ! hash_equals( $owner_token, $posted_token ) ) { // A different tab/owner (or a token-less request) asked to cancel — do // NOT touch the running scan. wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was started in another tab. Cancel it from that tab, or wait for it to finish (a stuck scan clears itself automatically after 30 minutes).', 'ai-cyberguard' ), ) ); return; } // ACG-036-004 (audit 2026-06-20, HIGH): wipe the scan state WHILE STILL HOLDING the lock, then // release LAST. The old code released first and wiped after — a successor scan that acquired the // freed lock in that window had its fresh state destroyed (and its lock orphaned). Holding a // FRESH lock (owns()) guarantees no successor can acquire while we clean up. if ( '' !== $owner_token ) { // Token path: require we still own the FRESH lock AND renew the lease at commit time. // ACG-038-013 (audit 2026-06-21, HIGH-COND): touch() (now bool) is the hard gate — owns() // is only a point check, so a lock near the stale boundary could be taken over right after // it; a failed renewal means a successor owns it → do NOT wipe its state. if ( ! GuardPress_Scan_Lock::owns( 'malware', $posted_token ) || ( method_exists( 'GuardPress_Scan_Lock', 'touch' ) && ! GuardPress_Scan_Lock::touch( 'malware', $posted_token ) ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was started in another tab. Cancel it from that tab, or wait for it to finish.', 'ai-cyberguard' ), ) ); return; } // ACG-038-013: generation-checked cleanup — delete malware_state only if it still carries // OUR scan_id, so a successor that stale-took the lock during cleanup is never erased. self::cleanup_scan_data( false, $posted_token ); GuardPress_Scan_Lock::release( 'malware', $posted_token ); // release LAST wp_send_json_success(); return; } // No owner token in the state (legacy/empty). ACG-037-006 (audit 2026-06-21, HIGH): do NOT // is_held()-then-clean (a successor could acquire in the gap and be wiped). ACQUIRE a recovery // token FIRST — only if we win the lock do we own the cleanup; then clean + release LAST. If // acquire fails (a successor holds it), refuse. $rec = GuardPress_Scan_Lock::acquire( 'malware' ); if ( empty( $rec['acquired'] ) ) { wp_send_json_error( array( 'not_owner' => true, 'message' => __( 'This scan was started in another tab. Cancel it from that tab, or wait for it to finish.', 'ai-cyberguard' ), ) ); return; } self::cleanup_scan_data(); GuardPress_Scan_Lock::release( 'malware', isset( $rec['scan_id'] ) ? $rec['scan_id'] : null ); wp_send_json_success(); } // ==================== SCAN FILE ==================== // (Rest of file unchanged - scan_file, scan_content, generate_summary, etc.) // Copy the remaining functions from the original file // ==================== INCREMENTAL VERDICT CACHE ==================== // Speed up REPEAT scans: on the first scan every file is classified and its // verdict (clean, or its findings) is remembered keyed by a tuple of // content-hash + size + mtime + signature/engine version. On later scans, an // UNCHANGED file (and unchanged signatures) reuses its cached verdict instead // of being re-scanned — so the second scan and beyond are much faster. // The tuple self-invalidates whenever the file OR the signatures/plugin change. // // Stored via the existing file storage under key 'malware_verdict_cache' // (subdir 'scan'). cleanup_scan_data() deletes only the transient scan files // (files/state/sigs/hash_db), NOT this key, so the cache PERSISTS across // scans; delete_all() (uninstall / reset) still removes it with everything else. const VERDICT_CACHE_KEY = 'malware_verdict_cache'; // PERF-116-06 (perf audit 2026-06-18): raised 3000 -> 50000. At 3000 the cache // could not hold the candidate set of a medium/large site (e.g. 11,000 files), so // a sequential re-scan evicted every prior entry before reaching it again — 0 cache // hits, defeating the "subsequent scans are much faster" promise. An entry is tiny // (path + tuple + verdict ~150 bytes), so 50k entries cap the file at ~7.5 MB and // cover virtually every WordPress install; only genuinely huge trees (>50k scannable // files) still LRU-evict. The first scan is unaffected (it only WRITES the cache). const VERDICT_CACHE_CAP = 50000; /** @var array|null In-request snapshot of the verdict map (loaded once, flushed at batch end). */ private static $verdict_cache = null; private static $verdict_cache_dirty = false; /** * @var bool Whether the most recent scan_file_uncached() verdict is stable * enough to cache. Set false when integrity could NOT be fully evaluated * (e.g. WP.org checksums were temporarily unavailable), so we don't pin a * possibly-wrong 'clean' against a tuple that has no checksum dimension. */ private static $last_verdict_cacheable = true; /** * ACG-148-009: did the tokenizer decline to run on the last content it was given? * * The tokenizer is the strongest detector in this product, so "it did not run" must never be * indistinguishable from "it found nothing". scan_content() turns this into a coverage finding. * * @var bool */ private static $tokenizer_skipped = false; /** * ACG-149-007: total paren-balance scan steps spent on the CURRENT file. * * The sink-argument scans are bounded in aggregate, not per firing. Unbalanced parens make each * scan run to end-of-file, and one fires per sink token, so an attacker could buy O(n^2) with a * 100 KB file: 15,000 x `system(` measured 152 s, and 205 KB did not finish in ten minutes. Reset * at the top of every detector call, so this is a per-file budget and never leaks between files. * * @var int */ private static $scan_work = 0; /** * ACG-149-017: set true when ANY per-file analysis budget is exhausted on the current file. * * A budget protects against a DoS, but running out of budget is NOT evidence of a clean file - * it is evidence the file resisted analysis, which is itself suspicious. When set, scan_content * raises a coverage notice (fail-VISIBLE) so a padded backdoor placed past the exhaustion point * is surfaced for manual review, never reported as a confident clean verdict. Reset per file. * * @var bool */ private static $analysis_truncated = false; /** * How many bytes of PHP source this request can afford to tokenize RIGHT NOW. * * MEASURED on this project's own PHP 8: token_get_all() costs ~100x the source size on dense * code (1.2 MB of real statements -> 118 MB of tokens), and the detector then holds a normalised * copy alongside it. A 2 MB file - which the old fixed cap allowed through - therefore wanted a * few hundred megabytes and killed the request with a FATAL out-of-memory error on any ordinary * shared host. A fatal in the scanner is worse than a missed file: it takes the whole scan with * it, on every run, and an attacker can trigger it deliberately with one large generated file. * * So the ceiling is derived from the memory actually left, and half of the remaining headroom is * kept in reserve for the rest of the scan. The historic 2 MB cap stays as the upper bound, so * nothing changes on a healthy host. Empirically this costs no real coverage: across 6,637 real * files (WordPress core, Elementor, Contact Form 7, Yoast) the 99.9th percentile is 192 KB and * the largest single PHP file is 327 KB. * * @return int bytes */ private static function tokenizer_budget_bytes() { $hard = 2097152; $raw = trim( (string) @ini_get( 'memory_limit' ) ); if ( '' === $raw || '-1' === $raw || '0' === $raw ) { return $hard; // no limit configured -> the historic cap is the only bound } $limit = (float) $raw; $unit = strtolower( substr( $raw, -1 ) ); if ( 'g' === $unit ) { $limit *= 1073741824; } elseif ( 'm' === $unit ) { $limit *= 1048576; } elseif ( 'k' === $unit ) { $limit *= 1024; } $free = $limit - (float) memory_get_usage( true ); if ( $free <= 0 ) { return 0; } // ~200x for the token array plus its normalised copy, and only half the headroom is spent. $budget = min( $hard, $free / 400 ); // ACG-149-005: a FLOOR, because the formula alone lands BELOW this function's own measured // corpus on ordinary hosts (128M mid-scan => ~190 KB, under the 192 KB p99.9 and well under // the 327 KB largest real file). Left unfloored, every large legitimate file draws a // "partially scanned" notice - which makes the green "Site clean" verdict unreachable on // that host - and, under real memory pressure, the tokenizer goes dark for most of the site. // The floor is applied ONLY when the headroom can actually pay for it at the SAME per-byte rate // the ceiling uses ($free / 400), so it can never tokenize more bytes than the base model would // ACG-149-024 (siege 2): the 384 KB FLOOR that stood here was removed. To tokenize 384 KB // safely needs ~150 MB free at the base 400x rate, but the floor could only be reached when // $budget (= $free/400) was already BELOW 384 KB, i.e. $free < 150 MB - a contradiction, so it // was dead code. A ceiling-only budget is the safe choice: a low/mid-memory host that meets a // large file now raises the fail-visible coverage notice instead of risking the OOM the floor // reintroduced. No legitimate file in the 6,637-file corpus needs more than the ceiling grants. return (int) $budget; } private static function verdict_cache_load() { if ( self::$verdict_cache !== null ) { return; } $map = self::load_scan_data( self::VERDICT_CACHE_KEY, null ); self::$verdict_cache = is_array( $map ) ? $map : array(); } /** Signature/engine version component of the verdict-cache content tuple. */ private static function verdict_cache_version_suffix() { $sig_version = class_exists( 'GuardPress_Signatures_Database' ) ? GuardPress_Signatures_Database::VERSION : ''; $feed_update = class_exists( 'GuardPress_Threat_Feed' ) ? get_option( GuardPress_Threat_Feed::OPTION_LAST_UPDATE, 0 ) : 0; $plugin_ver = defined( 'GUARDPRESS_VERSION' ) ? GUARDPRESS_VERSION : ''; return $sig_version . '|' . $feed_update . '|' . $plugin_ver; } /** * Validity tuple for a file. Changes on any file change OR any * signature/engine change, which self-invalidates the cached verdict. */ private static function verdict_cache_tuple( $file_md5, $fsize, $mtime ) { return sha1( $file_md5 . '|' . $fsize . '|' . $mtime . '|' . self::verdict_cache_version_suffix() ); } private static function verdict_cache_norm_path( $filepath ) { return str_replace( '\\', '/', $filepath ); } /** * Persist the verdict map if it changed during this batch. Applies an * LRU-ish cap (~3000 entries, newest kept) so the cache file can't grow * unbounded on very large sites. */ private static function verdict_cache_flush() { if ( ! self::$verdict_cache_dirty || ! is_array( self::$verdict_cache ) ) { return; } if ( count( self::$verdict_cache ) > self::VERDICT_CACHE_CAP ) { // Newly written/touched entries are moved to the end, so the tail is // the most-recently-used slice — keep it, drop the stale head. self::$verdict_cache = array_slice( self::$verdict_cache, -self::VERDICT_CACHE_CAP, null, true ); } self::save_scan_data( self::VERDICT_CACHE_KEY, self::$verdict_cache ); self::$verdict_cache_dirty = false; } /** * Cached front door for scan_file_uncached(). Returns 'clean' or a findings * array, reusing a remembered verdict when the file + signatures are unchanged. */ /** * ACG-083 (audit 2026-06-27): the no-follow contract for every scanner read/hash of an attacker-controllable * site file. Prefers the shared GuardPress_FS_Helpers primitive (the canonical home, ACG-083-H1); falls back to a * self-contained, trusted-root-aware copy when FS_Helpers is unavailable (e.g. an isolated harness). Returns true * ONLY for a REGULAR file (no symlink, FIFO, dir, socket, device — so a FIFO can never reach a blocking read) with * NO symlink component below the deepest trusted root (ABSPATH / WP_CONTENT_DIR / uploads basedir — a host may * legitimately symlink those, but not a deeper component) and a realpath that stays under that root. * * @param string $path Absolute filesystem path. * @return bool */ private static function is_safe_regular_file( $path ) { if ( class_exists( 'GuardPress_FS_Helpers' ) && method_exists( 'GuardPress_FS_Helpers', 'regular_file_in_abspath_no_symlink_components' ) ) { return GuardPress_FS_Helpers::regular_file_in_abspath_no_symlink_components( $path ); } $path = (string) $path; if ( '' === $path || ! defined( 'ABSPATH' ) ) { return false; } clearstatcache( false, $path ); if ( @is_link( $path ) || ! @is_file( $path ) ) { return false; } $norm = static function ( $p ) { return str_replace( '\\', '/', (string) $p ); }; $full = $norm( $path ); $roots = array(); if ( function_exists( 'wp_upload_dir' ) ) { $u = @wp_upload_dir( null, false ); if ( is_array( $u ) && ! empty( $u['basedir'] ) ) { $roots[] = $u['basedir']; } } if ( defined( 'WP_CONTENT_DIR' ) ) { $roots[] = WP_CONTENT_DIR; } $roots[] = ABSPATH; $base = null; foreach ( $roots as $r ) { $rn = rtrim( $norm( $r ), '/' ); if ( '' !== $rn && 0 === strpos( $full, $rn . '/' ) ) { $base = $rn; break; } } if ( null === $base ) { $ra = @realpath( ABSPATH ); $rp = @realpath( $path ); return ( false !== $ra && false !== $rp && 0 === strpos( $norm( $rp ), rtrim( $norm( $ra ), '/' ) . '/' ) ); } $rel = substr( $full, strlen( $base ) + 1 ); $cur = $base; foreach ( explode( '/', $rel ) as $p ) { if ( '' === $p || '.' === $p ) { continue; } if ( '..' === $p ) { return false; } $cur .= '/' . $p; clearstatcache( false, $cur ); if ( @is_link( $cur ) ) { return false; } } $rp = @realpath( $path ); $rb = @realpath( $base ); if ( false === $rp || false === $rb ) { return false; } return ( 0 === strpos( $norm( $rp ), rtrim( $norm( $rb ), '/' ) . '/' ) ); } private static function scan_file( $filepath, $signatures, $core_checksums, &$plugin_cache, $malware_hashes, $hc_sigs = array() ) { // RC-118-04 (audit round 2, 2026-06-18): read the file's bytes ONCE and derive the // cache key (SHA-256), the Threat-Feed malware-hash lookup key (MD5) AND the content // scan all from that single buffer. Previously the SHA-256 (cache key), the MD5 and // the content read were THREE separate file opens, so a parallel writer could swap // malicious->clean->malicious across the windows and pin a 'clean' verdict under the // malicious hash (the round-1 pre/post re-hash was defeated by re-swapping back). One // read closes the TOCTOU completely: the hash and the scanned bytes are provably the // same bytes. Oversize files never reach scan_file (ajax_scan_batch handles // > MAX_FILE_SIZE before this), so a single capped in-memory read is bounded. // ACG-081-004 / ACG-082-003 / ACG-083-002 / ACG-083-004 (audit 2026-06-27, HIGH): never read THROUGH a symlink // — and not only the BASENAME. is_link($filepath) alone missed a symlinked ANCESTOR directory (e.g. // wp-content/uploads/d -> external): the final file is a regular file, so filesize()/file_get_contents() FOLLOW // the symlinked parent and scan an EXTERNAL target as an in-install file (ACG-083-002). A FIFO/special file also // slipped past is_link() and then BLOCKED file_get_contents() forever (ACG-083-004, a scan DoS). Gate on the // shared no-symlink-component + regular-file + realpath-contained contract; anything unsafe → the distinct // 'skipped' sentinel (a COVERAGE GAP, never verified-clean, and a non-regular file is never read so it can't hang). if ( ! self::is_safe_regular_file( $filepath ) ) { return 'skipped'; } // ACG-103 (2026-06-30): never scan/flag the plugin's OWN internal data store // (wp-content/guardpress-data/...). Its guarded .php storage (e.g. the event log) carries // strings that trip generic signatures — it was reported as a CRITICAL "Adminer Shell", a // self-false-positive. The store is integrity-protected by the plugin and is out of scope for // the malware scan. (Now that a Quick scan walks all of wp-content, the per-file gate is here // so the file is excluded no matter which discovery path reached it.) Symlink-hardened in // FS_Helpers: a symlinked store excludes nothing, so a malicious look-alike is still scanned. if ( class_exists( 'GuardPress_FS_Helpers' ) && GuardPress_FS_Helpers::is_internal_data_path( $filepath ) ) { return 'clean'; } self::verdict_cache_load(); $norm_path = self::verdict_cache_norm_path( $filepath ); $fsize = @filesize( $filepath ); $mtime = @filemtime( $filepath ); // SEC (audit 2026-06-19): the size+mtime "stat fast-path" was REMOVED. It let a content // tamper that preserved size+mtime (trivial with `touch -r`) pass a QUICK scan as clean // (false negative). The verdict cache below is keyed on the SHA-256 of the file's actual // bytes, so a repeat scan still skips the heavy signature matching for genuinely-unchanged // files — the sound speed-up — but every file is read + hashed, so a same-size/same-mtime // tamper can no longer slip through. (Quick vs Deep still differ in WHICH files are scanned; // that selection happens in the walker, not here.) $buf = @file_get_contents( $filepath, false, null, 0, self::MAX_FILE_SIZE ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- one bounded read; the verdict + both hashes must derive from identical bytes (TOCTOU-safe) if ( false === $buf ) { // Unreadable — scan directly (it will also fail to read) and do NOT cache. return self::scan_file_uncached( $filepath, $signatures, $core_checksums, $plugin_cache, $malware_hashes, $hc_sigs, false, null ); } $file_sha = hash( 'sha256', $buf ); $tuple = self::verdict_cache_tuple( $file_sha, $fsize, $mtime ); if ( isset( self::$verdict_cache[ $norm_path ] ) && is_array( self::$verdict_cache[ $norm_path ] ) && isset( self::$verdict_cache[ $norm_path ]['tuple'] ) && self::$verdict_cache[ $norm_path ]['tuple'] === $tuple ) { return self::$verdict_cache[ $norm_path ]['verdict']; // cached 'clean' } $file_md5 = md5( $buf ); // SAME bytes as the SHA-256 and the scan → no TOCTOU self::$last_verdict_cacheable = true; $result = self::scan_file_uncached( $filepath, $signatures, $core_checksums, $plugin_cache, $malware_hashes, $hc_sigs, $file_md5, $buf ); // Cache ONLY a 'clean' verdict (PERF-116-06: a flagged file must always re-run // scan_file_uncached so its MalwareBazaar re-confirmation isn't skipped, and the // cache file stays tiny). The tuple is the SHA-256 of the EXACT bytes just scanned // clean, so any later swap to different bytes changes the lookup hash → cache miss → // re-scan. No pre/post re-verify is needed because there was only one read. // (The un-cacheable flag still applies: e.g. a plugin scanned while WP.org checksums // were unavailable is left out so its integrity comparison runs once they arrive.) if ( self::$last_verdict_cacheable && 'clean' === $result ) { unset( self::$verdict_cache[ $norm_path ] ); // Content-hash tuple only (the unsound size+mtime 'st' shortcut was removed — see above). self::$verdict_cache[ $norm_path ] = array( 'tuple' => $tuple, 'verdict' => 'clean' ); self::$verdict_cache_dirty = true; } return $result; } /** * Map a file-ORIGIN classification (set in scan_file_uncached) to the user-facing * advice + whether one-click Quarantine should be offered. Centralises the * "what to do" guidance so the results UI warns correctly per origin: * uploads / other → safe to quarantine (not part of a loaded extension) * plugin_extra → likely injected; safest is to reinstall the plugin * plugin_modified → changed from the official copy; reinstall the plugin * plugin_unverifiable → premium plugin we can't verify; likely a false positive * theme / safe → don't quarantine * * @param string $origin * @param string $label Plugin/theme slug, when known. * @param string $severity Highest finding severity for the file (info|low|medium|high|critical). * @return array{can_quarantine:bool, advice:string} */ /** * ACG-116-T3 (2026-07-05, Yossi): "This file is legitimate — don't show it again". * Records a HASH-ANCHORED approval for a suspicious-class (NOT confirmed) file from * the last scan. The approval only silences the file while its bytes stay identical; * any change voids it automatically at finalize time (see the suppression pass there). * Guards: scanner nonce + manage_options + path containment under ABSPATH + the file * must exist in the last scan results WITHOUT any confirmed (malware-class) finding. */ public static function ajax_acknowledge_file() { check_ajax_referer( 'guardpress_batch_scan', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-cyberguard' ) ) ); } $rel = isset( $_POST['filepath'] ) ? wp_unslash( $_POST['filepath'] ) : ''; $rel = is_string( $rel ) ? ltrim( str_replace( '\\', '/', $rel ), '/' ) : ''; if ( '' === $rel || strlen( $rel ) > 512 || false !== strpos( $rel, chr( 0 ) ) ) { wp_send_json_error( array( 'message' => __( 'Invalid file path.', 'ai-cyberguard' ) ) ); } foreach ( explode( '/', $rel ) as $gp_seg ) { if ( '..' === $gp_seg ) { wp_send_json_error( array( 'message' => __( 'Invalid file path.', 'ai-cyberguard' ) ) ); } } $gp_root = realpath( ABSPATH ); $gp_real = realpath( ABSPATH . $rel ); if ( false === $gp_root || false === $gp_real || ! is_file( $gp_real ) || 0 !== strpos( $gp_real . DIRECTORY_SEPARATOR, rtrim( $gp_root, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR ) ) { wp_send_json_error( array( 'message' => __( 'Invalid file path.', 'ai-cyberguard' ) ) ); } if ( class_exists( 'GuardPress_FS_Helpers' ) && method_exists( 'GuardPress_FS_Helpers', 'is_safe_regular_file' ) && ! GuardPress_FS_Helpers::is_safe_regular_file( $gp_real ) ) { wp_send_json_error( array( 'message' => __( 'Invalid file path.', 'ai-cyberguard' ) ) ); } // The file must appear in the LAST scan results, and must not be a confirmed threat. $gp_last = GuardPress_File_Storage::load( 'malware-last-scan', null, 'cache' ); $gp_entry = null; if ( is_array( $gp_last ) && ! empty( $gp_last['file_findings'] ) && is_array( $gp_last['file_findings'] ) ) { foreach ( $gp_last['file_findings'] as $gp_ff ) { if ( isset( $gp_ff['filepath'] ) && (string) $gp_ff['filepath'] === $rel ) { $gp_entry = $gp_ff; break; } } } if ( null === $gp_entry ) { wp_send_json_error( array( 'message' => __( 'This file was not found in the last scan results.', 'ai-cyberguard' ) ) ); } foreach ( (array) ( $gp_entry['findings'] ?? array() ) as $gp_fnd ) { if ( 'malware' === self::finding_verdict_class( $gp_fnd ) ) { wp_send_json_error( array( 'message' => __( 'Confirmed threats cannot be approved.', 'ai-cyberguard' ) ) ); } } $gp_hash = @hash_file( 'sha256', $gp_real ); if ( ! is_string( $gp_hash ) || '' === $gp_hash ) { wp_send_json_error( array( 'message' => __( 'Could not read the file.', 'ai-cyberguard' ) ) ); } $gp_acks = GuardPress_File_Storage::load( 'acked_files', array(), 'scan' ); if ( ! is_array( $gp_acks ) ) { $gp_acks = array(); } // Bound the store: keep the newest 500 approvals (drop oldest first). if ( count( $gp_acks ) >= 500 && ! isset( $gp_acks[ $rel ] ) ) { uasort( $gp_acks, static function ( $a, $b ) { return (int) ( $a['t'] ?? 0 ) <=> (int) ( $b['t'] ?? 0 ); } ); while ( count( $gp_acks ) >= 500 ) { array_shift( $gp_acks ); // string keys of the remaining entries are preserved } } $gp_acks[ $rel ] = array( 'h' => $gp_hash, 't' => time() ); if ( ! GuardPress_File_Storage::save( 'acked_files', $gp_acks, 'scan' ) ) { wp_send_json_error( array( 'message' => __( 'Could not save the approval.', 'ai-cyberguard' ) ) ); } wp_send_json_success( array( 'filepath' => $rel ) ); } public static function origin_meta( $origin, $label = '', $severity = '', $confirmed = null ) { $label = ( '' !== (string) $label ) ? (string) $label : __( 'this extension', 'ai-cyberguard' ); $serious = in_array( strtolower( (string) $severity ), array( 'high', 'critical' ), true ); $can = false; $advice = ''; $warn = ''; // UX 2026-06-19: the crash-warning sentence, shown RED + separate in the popup $ext = ''; // 'plugin' | 'theme' | '' — lets the results popup link to the right manage screen switch ( $origin ) { case 'plugin_extra': $advice = sprintf( /* translators: %1$s: plugin folder name */ __( '🛑 This file is inside the “%1$s” plugin folder but is NOT part of the official plugin package. Legitimate plugin files are always part of the official package, so a file that does not belong there was almost certainly planted by an attacker and very likely IS a backdoor. Strongly recommended: REMOVE / REINSTALL the “%1$s” plugin from a clean copy now (reinstalling deletes the injected file too), or deactivate the plugin and then quarantine this file.', 'ai-cyberguard' ), $label ); break; case 'plugin_modified': $advice = sprintf( /* translators: %1$s: plugin folder name */ __( '📝 This file in the “%1$s” plugin differs from the official WordPress.org version. If you did not change it yourself, the plugin may have been tampered with — reinstall the “%1$s” plugin from a clean copy. Do not quarantine this file (that would break the plugin).', 'ai-cyberguard' ), $label ); break; case 'plugin_unverifiable': // ACG-113 (2026-07-04, Yossi): the wording is picked by VERDICT first, severity // second. The "may contain a backdoor / REMOVE-REINSTALL" text is CORRECT for a // CONFIRMED (malware-class) finding and stays untouched for it — softening that // would be malpractice. But serving it to a REVIEW-class item contradicted the // Review tier's own "not confirmed malware" promise and terrified users over a // premium plugin's documented feature. A serious-but-unconfirmed match now gets // an honest middle text: leads with what the engine actually concluded, then a // conditional escalation path. The 'danger' level (⚠️ Warning affordance) is // deliberately KEPT for serious review items — the row must stay distinguishable // at the top of the review list; only the popup's tone was wrong. if ( $serious && false === $confirmed ) { $advice = sprintf( /* translators: %1$s: plugin folder name */ __( '⚠️ This file is inside your active “%1$s” plugin (premium / not on WordPress.org, so it cannot be compared against an official copy) and uses a powerful code pattern (such as eval) that malware also uses. It is NOT confirmed malware — well-known plugins use such patterns as legitimate features, which is why this item is listed under Review and not as a threat. If you knowingly installed “%1$s” and this item also appeared in earlier scans, no action is needed — just keep the plugin updated. Treat it as suspicious only if it appeared suddenly on a plugin that used to scan clean, or if you do not recognise this plugin at all — in that case reinstall “%1$s” from the copy you purchased. Do not quarantine this file (that would break the plugin).', 'ai-cyberguard' ), $label ); } elseif ( $serious ) { $advice = sprintf( // ACG-149-153 (owner, 2026-07-27): added the "ask the developer" step. The owner's own // condition was "provided it is actually true that his file could be a way in for // attackers" — so the wording ASKS THE DEVELOPER TO CONFIRM rather than telling the // user to report a backdoor. This finding is explicitly not confirmed malware (it is a // Review item, and the sentence right after says it may be a false positive); sending // people to accuse a legitimate developer on that basis would be wrong, and would make // the accusation OUR fault. The stronger sentence is kept but made CONDITIONAL: it only // applies if the developer does not recognise the code, which is the one case where it // really would mean their release was tampered with. // ACG-149-R36-K: the translators comment MUST be the last comment before the // gettext call or the extractor drops it — it used to sit above this block. /* translators: %1$s: plugin folder name */ __( '⚠️ This file is inside your active “%1$s” plugin (premium / not on WordPress.org, so it cannot be checked against an official copy) and matched a high-risk pattern. Treat it as suspicious — it may contain a backdoor. Quarantining it could break the plugin, so the recommended action is to REMOVE / REINSTALL the “%1$s” plugin from the copy you purchased. Before that, it is worth contacting the plugin’s developer and asking them to confirm that this file is a legitimate part of “%1$s” — they can tell you in minutes. If they do NOT recognise the code, let them know: it would mean the copy you received was tampered with, and other customers may have it too. (If you installed and fully trust this plugin it may still be a false positive — some plugins use powerful patterns like eval legitimately.)', 'ai-cyberguard' ), $label ); } else { $advice = sprintf( /* translators: %1$s: plugin folder name */ __( 'ℹ️ This file is inside your active “%1$s” plugin (premium / not on WordPress.org, so it cannot be checked against an official copy). If you installed and trust this plugin, this is most likely a false positive — plugins sometimes use powerful patterns (eval, base64) legitimately. If you suspect it was hacked, reinstall the plugin from the copy you purchased. Do not quarantine (that would break the plugin).', 'ai-cyberguard' ), $label ); } break; case 'theme': $advice = __( 'ℹ️ This file is part of an active theme. If you suspect it is infected, reinstall the theme from a clean copy. Do not quarantine (that would break your site’s appearance).', 'ai-cyberguard' ); break; case 'core_modified': // A genuine core file that was altered — restore via re-install, // do NOT quarantine (removing a real core file breaks the site). $advice = __( '⚠️ This is a WordPress core file that does NOT match the official release. Core files should not change on their own. Re-install WordPress (Dashboard → Updates → “Re-install version”) to restore the original — do NOT quarantine it (that would break your site).', 'ai-cyberguard' ); break; case 'core_unknown': // An extra file inside a core folder — not part of WordPress, very // likely an injected back-door. RC-107-05 (audit 2026-06-17): the // Quarantine handler refuses ANY wp-admin/wp-includes path on // purpose, so we must NOT advertise quarantine here (it would just // fail). Advise re-installing WordPress (which removes the stray // file) or removing it manually after investigating. $advice = __( '🛑 This file is inside a WordPress core folder (wp-admin / wp-includes) but is NOT part of WordPress. Attackers hide back-doors here. Re-installing WordPress (Dashboard → Updates → “Re-install version”) removes any file that does not belong; or investigate and delete it manually over SFTP. (Quarantine is intentionally disabled for core folders.)', 'ai-cyberguard' ); break; case 'core_unverifiable': // Could not download the official checksums to verify — be cautious // but do not offer to quarantine a possibly-genuine core file. $advice = __( 'ℹ️ This file is in a WordPress core folder, but the official checksums could not be downloaded to verify it. Treat it with caution and re-scan once your site can reach WordPress.org. Re-installing WordPress core restores any genuine core file.', 'ai-cyberguard' ); break; case 'safe': $advice = ''; break; case 'uploads': $can = true; $advice = __( 'Executable files do not normally belong in the uploads folder. If you do not recognise it, quarantining it is safe.', 'ai-cyberguard' ); break; default: // 'other' or untagged $can = true; break; } // UX (2026-06-19): the crash-warning sentence is returned SEPARATELY (rendered RED in the // results popup) and the owning extension kind is exposed so the popup can link straight to // the right manage screen (deactivate the plugin / switch the theme) — making the "what to // do" guidance actionable instead of just text. if ( in_array( $origin, array( 'plugin_extra', 'plugin_modified', 'plugin_unverifiable' ), true ) ) { $ext = 'plugin'; /* translators: %1$s: plugin folder name */ $warn = sprintf( __( '⚠️ If you would rather delete just this one file yourself, you MUST first deactivate the “%1$s” plugin on the Plugins screen — deleting it while the plugin is still active can crash your site. ONLY after the plugin is deactivated is it safe to delete the file.', 'ai-cyberguard' ), $label ); } elseif ( 'theme' === $origin ) { $ext = 'theme'; $warn = __( '⚠️ If you would rather delete just this one file yourself, you MUST first switch to a different theme — deleting a file from the ACTIVE theme can break your site. ONLY after another theme is active is it safe to delete the file.', 'ai-cyberguard' ); } // Visual urgency for the results UI: a RED "Warning" affordance for genuinely // suspicious extension files (injected, or a high/critical pattern we can't // verify); a calm "Details" affordance otherwise. $level = $can ? 'ok' : ( ( 'plugin_extra' === $origin || $serious ) ? 'danger' : 'info' ); return array( 'can_quarantine' => $can, 'advice' => $advice, 'level' => $level, 'warn' => $warn, 'ext' => $ext ); } private static function scan_file_uncached( $filepath, $signatures, $core_checksums, &$plugin_cache, $malware_hashes, $hc_sigs = array(), $precomputed_md5 = null, $precomputed_content = null ) { // FIX (2026-06-13): normalize BOTH sides before stripping so the relative // display path is correct on Windows/mixed-slash hosts too (str_replace is // literal; a backslash $filepath vs forward-slash ABSPATH would not strip, // leaving an absolute path the Quarantine button could not resolve). $result = array( 'filepath' => str_replace( wp_normalize_path( ABSPATH ), '', wp_normalize_path( $filepath ) ), 'findings' => array(), 'risk_score' => 0 ); // PERF-116-04: reuse the md5 scan_file() already computed for the cache key // instead of re-hashing the whole file a second time. Falls back to hashing // only when called without one (other entry points / future callers). // ACG-086 sweep (audit 2026-06-28): the md5 fallback (when no precomputed hash is supplied) must never hash // THROUGH a symlink component or a non-regular file (FIFO would HANG md5_file). Unsafe path → empty md5 (the // path was already gated at scan_file's entry; this is defence-in-depth for any direct caller). $file_md5 = ( null !== $precomputed_md5 ) ? $precomputed_md5 : ( self::is_safe_regular_file( $filepath ) ? (string) @md5_file( $filepath ) : '' ); $ext = strtolower( pathinfo( $filepath, PATHINFO_EXTENSION ) ); $php_ext = self::php_family_exts(); // RC-108-01: single source (incl. pht/php8/phps/inc) if ( $file_md5 && isset( $malware_hashes[ $file_md5 ] ) ) { $result['findings'][] = array( 'type' => 'hash', 'severity' => 'critical', 'name' => 'Known Malware: ' . ( $malware_hashes[ $file_md5 ]['name'] ?? 'Unknown' ), 'description' => 'Matches known malware hash' ); return $result; } $info = self::classify_file( $filepath ); // RC-111-04: also treat a multi-extension name carrying a PHP-family suffix // (e.g. shell.php.jpg) as a PHP-in-uploads file — Apache may execute it as PHP // via the earlier suffix even though the last extension is .jpg. Without this it // would fall through to the "return clean" path below, unscanned. if ( $info['type'] === 'uploads' && ( in_array( $ext, $php_ext, true ) || self::has_php_family_suffix( basename( $filepath ) ) ) ) { $legitimate = self::is_legitimate_upload_php( $filepath ); if ( $legitimate['is_legitimate'] ) { $result['findings'][] = array( 'type' => 'location', 'severity' => 'info', 'name' => '🛡️ Security File (Safe)', 'description' => $legitimate['reason'], 'recommendation' => '✅ No action needed. This file was created by a plugin to protect your site.' ); $result['origin'] = 'safe'; return $result; } else { $result['findings'][] = array( 'type' => 'location', 'severity' => 'high', 'name' => '⚠️ PHP File in Uploads', 'description' => 'PHP files should not normally be in the uploads folder. If this file is inside a subfolder created by a plugin (e.g. cache, fonts, backups), it is likely safe. If you don\'t recognize it — investigate or delete it.', 'recommendation' => '🔍 Verify whether this file belongs to a known plugin or theme.' ); $result['origin'] = 'uploads'; self::scan_content( $filepath, $signatures, $result, $precomputed_content ); } return $result; } if ( $info['type'] === 'uploads' ) { $scan_ext = array( 'svg', 'html', 'htm', 'js' ); if ( in_array( $ext, $scan_ext, true ) ) { $result['origin'] = 'uploads'; // PERF FIX (v8.2): Use pre-computed hc_sigs instead of rebuilding per file self::scan_content( $filepath, $hc_sigs, $result, $precomputed_content ); return empty( $result['findings'] ) ? 'clean' : $result; } return 'clean'; } if ( $info['type'] === 'core' ) { // RC-106-01 FIX (audit 2026-06-17): do NOT blanket-clean every file that // merely SITS under wp-admin/ or wp-includes/. A back-door planted at // e.g. wp-includes/images/shell.php would otherwise be classified "core" // and returned clean without its content ever being scanned. Verify the // file against the official WordPress.org core checksums — exactly like // the plugin path below. $relative = $info['relative']; $result['origin_label'] = 'WordPress core'; if ( empty( $core_checksums ) ) { // Checksums unavailable (network failure / brand-new release). We // cannot verify, so the verdict must NOT be cached and we must NOT // short-circuit to clean — content-scan so an injected file is still // caught. self::$last_verdict_cacheable = false; $result['origin'] = 'core_unverifiable'; self::scan_content( $filepath, $signatures, $result, $precomputed_content ); return empty( $result['findings'] ) ? 'clean' : $result; } if ( isset( $core_checksums[ $relative ] ) ) { if ( $file_md5 && $file_md5 === $core_checksums[ $relative ] ) { return 'clean'; // VERIFIED original core file } // Hash mismatch — a modified core file. Core files should never // change on their own; report it and scan content for evidence. $result['origin'] = 'core_modified'; $result['findings'][] = array( 'type' => 'modified', 'severity' => 'high', 'name' => '⚠️ Modified WordPress Core File', 'description' => "This WordPress core file ('{$relative}') does not match the official release. Core files should not change on their own — this can be a sign of infection.", 'recommendation' => '🔧 Re-install WordPress (Dashboard → Updates → "Re-install version") to restore the original file, then investigate how it changed.', ); self::scan_content( $filepath, $signatures, $result, $precomputed_content ); return $result; } // Inside a core directory but NOT part of the official release = an // extra/injected file. Attackers commonly hide back-doors here. $result['origin'] = 'core_unknown'; $result['findings'][] = array( 'type' => 'location', 'severity' => 'high', 'name' => '⚠️ Unexpected File in WordPress Core Folder', 'description' => "This file is inside a WordPress core folder (wp-admin / wp-includes) but is not part of the official WordPress release. Legitimate files almost never live here — back-doors often do.", 'recommendation' => '🔍 Re-install WordPress (Dashboard → Updates → "Re-install version") to remove any file that does not belong, or investigate and delete it manually over SFTP. (Quarantine is intentionally disabled for core folders.)', ); self::scan_content( $filepath, $signatures, $result, $precomputed_content ); return $result; } if ( $info['type'] === 'plugin' && ! empty( $info['slug'] ) && ! empty( $info['version'] ) ) { $cache_key = $info['slug'] . '_' . $info['version']; if ( ! isset( $plugin_cache[ $cache_key ] ) ) { $plugin_cache[ $cache_key ] = self::get_plugin_checksums( $info['slug'], $info['version'] ); } $checksums = $plugin_cache[ $cache_key ]; // FIX (2026-06-13): tag the file's ORIGIN so the UI can tailor the // warning + action (see origin_meta()). $info['slug'] is the folder. $result['origin_label'] = $info['slug']; if ( empty( $checksums ) ) { // WP.org checksums unavailable (network failure, or not yet // published for a brand-new release). We cannot run the integrity // comparison, so this file's verdict must NOT be cached — it could // change to "Modified Plugin File" once the checksums arrive. self::$last_verdict_cacheable = false; } if ( ! empty( $checksums ) && isset( $checksums[ $info['relative'] ] ) ) { if ( $file_md5 === $checksums[ $info['relative'] ] ) return 'clean'; // VERIFIED original $result['origin'] = 'plugin_modified'; $result['findings'][] = array( 'type' => 'modified', 'severity' => 'medium', 'name' => '📝 Modified Plugin File', 'description' => "This file in '{$info['slug']}' differs from the WordPress.org version.", 'recommendation' => '💡 This is often normal! Themes frequently modify plugin files for compatibility.' ); // PERF FIX (v8.2): Use pre-computed hc_sigs instead of rebuilding per file self::scan_content( $filepath, $hc_sigs, $result, $precomputed_content ); return $result; } // Not matched to an official file: either an EXTRA file (checksums ARE // available but this path isn't in them → not part of the plugin = // likely injected) or UNVERIFIABLE (no checksums → premium plugin not // on WordPress.org, e.g. ad-inserter-pro). This drives the tailored // warning so a legit-but-risky premium file isn't shown as a scary HIGH. $result['origin'] = ! empty( $checksums ) ? 'plugin_extra' : 'plugin_unverifiable'; self::scan_content( $filepath, $signatures, $result, $precomputed_content ); return empty( $result['findings'] ) ? 'clean' : $result; } if ( $info['type'] === 'theme' ) { $result['origin'] = 'theme'; if ( ! empty( $info['slug'] ) ) { $result['origin_label'] = $info['slug']; } // PERF FIX (v8.2): Use pre-computed hc_sigs instead of rebuilding per file self::scan_content( $filepath, $hc_sigs, $result, $precomputed_content ); return empty( $result['findings'] ) ? 'clean' : $result; } self::scan_content( $filepath, $signatures, $result, $precomputed_content ); if ( is_array( $result ) && ! empty( $result['findings'] ) ) { self::confirm_with_malwarebazaar( $filepath, $result ); } return empty( $result['findings'] ) ? 'clean' : $result; } /** * Quick pre-screen: does file content contain ANY malware indicator strings? * * Uses fast strpos() instead of regex. A single strpos() on a 500KB file * takes ~0.01ms. Even 100 checks = ~1ms — vs ~50ms for one preg_match(). * * If ZERO indicators are found, the file cannot match ANY malware signature, * so all 11,000+ regex checks can be safely skipped. * * The indicator list is intentionally BROAD to avoid false negatives: * - "exec" will match "exec(" but also "execute" → clean file gets full scan * unnecessarily, but malware is NEVER missed. * - Missing an indicator would mean missing malware → we err on inclusion. * * @since 8.2.0 * @param string $content File content (raw, not lowered). * @return bool True if file needs deep regex scanning. */ // ==================== PERF-121-01: MULTI-PATTERN LITERAL INDEX ==================== // A large opt-in Threat Feed ships thousands of PURE-LITERAL signatures (URLs, domains, // strings). Testing every one against every file is O(files × signatures) — the ~1-hour // 11K-file scan the auditor measured. Instead we build ONE chunked multi-pattern index of all // sound literals and find, in ~O(content) per file, WHICH literals are present; a literal // signature whose literal is ABSENT cannot match and is skipped in the loop. SOUND by // construction: only provably-pure-ASCII literals are indexed (no /u, no non-ASCII byte, no // metacharacter), so "literal absent (case-insensitively)" ⟺ "the /i regex cannot match". // Non-literal / Unicode / regex signatures are NEVER indexed and always run. Behind a feature // flag; the legacy engine (flag OFF) is the differential oracle — findings are identical. /** Feature flag (default ON). Constant GUARDPRESS_SCAN_MULTIPATTERN=false or the * guardpress_scan_multipattern filter disables it (falls back to running every signature). */ private static function scan_multipattern_enabled() { // Kill-switch for the SOUND per-literal strpos gate (see the loop in scan_content). DEFAULT // ON: unlike the removed combined-regex index, this gate is per-signature and independent // (a literal's presence is tested in isolation by strpos), so it has no prefix/substring // false negative and no PCRE compile-size limit — it can only skip a pure-literal signature // whose literal is genuinely absent, which the regex could not have matched anyway. // Turn OFF (constant GUARDPRESS_SCAN_MULTIPATTERN = false, or the filter) to force the // exhaustive engine — used as the differential oracle in testing. if ( defined( 'GUARDPRESS_SCAN_MULTIPATTERN' ) ) { return (bool) GUARDPRESS_SCAN_MULTIPATTERN; } return function_exists( 'apply_filters' ) ? (bool) apply_filters( 'guardpress_scan_multipattern', true ) : true; } /** The sound, lowercased pure-ASCII literal of a signature pattern, or '' if it is not safely * a pure literal. Rejects /x, /u, non-ASCII bytes, class/octal/backref escapes and unescaped * metacharacters; needs >=4 chars. Memoised per pattern. */ private static function scan_pattern_literal( $pattern ) { static $memo = array(); if ( array_key_exists( $pattern, $memo ) ) { return $memo[ $pattern ]; } $lit = ''; $p = (string) $pattern; $len = strlen( $p ); if ( $len >= 3 ) { $delim = $p[0]; if ( ! ctype_alnum( $delim ) && '\\' !== $delim && ' ' !== $delim ) { $close = strrpos( $p, $delim ); if ( false !== $close && $close > 0 ) { $inner = substr( $p, 1, $close - 1 ); $flags = (string) substr( $p, $close + 1 ); if ( false === stripos( $flags, 'x' ) && false === stripos( $flags, 'u' ) ) { if ( '' !== $inner && '^' === $inner[0] ) { $inner = substr( $inner, 1 ); } if ( '' !== $inner && '$' === substr( $inner, -1 ) ) { $inner = substr( $inner, 0, -1 ); } $out = ''; $ilen = strlen( $inner ); $ok = true; for ( $i = 0; $i < $ilen; $i++ ) { $c = $inner[ $i ]; if ( ord( $c ) > 127 ) { $ok = false; break; } // non-ASCII → unsound if ( '\\' === $c ) { if ( $i + 1 >= $ilen ) { $ok = false; break; } $n = $inner[ $i + 1 ]; if ( ctype_alpha( $n ) || ctype_digit( $n ) || ord( $n ) > 127 ) { $ok = false; break; } $out .= $n; $i++; continue; } if ( false !== strpos( '.*+?()[]{}|^$', $c ) ) { $ok = false; break; } // unescaped metachar $out .= $c; } if ( $ok && strlen( $out ) >= 4 ) { $lit = strtolower( $out ); } } } } } $memo[ $pattern ] = $lit; return $lit; } /** * ACG-138-R2-02a (reviewer 2, 2026-07-17): does this signature describe the file's NAME * rather than its CONTENT? * * The signature schema had no way to say so, so a rule about a filename was written as a * rule about bytes and evaluated against them. wpfeed_1 (/wp-feed.php|wp-tmp\.php/i, * critical, is_malware_name => never_downgrade) therefore reported STOCK WORDPRESS CORE as * CRITICAL MALWARE, because core legitimately mentions the name in two places: * wp-includes/canonical.php:477 'wp-feed.php' => $default_feed, (legacy redirect map) * wp-admin/includes/update-core.php // Don't delete, yet: 'wp-feed.php', (a COMMENT) * never_downgrade meant not even the vendor/library allowlist could rescue it — a clean site * was told to reinstall WordPress. This is the missing concept, not a patch for one rule: * ONE key, defaulting to 'content', so all 117 other rules keep their exact behaviour. * * The single source of truth for the question. Both the literal index (which must never gate * a name rule on the content) and the match site (which must feed it the name) ask it here, * so the two can never disagree about what a signature's subject is. * * @param array $sig Signature definition. * @return bool True if the signature matches against the file's basename. */ private static function sig_matches_filename( $sig ) { return isset( $sig['match_target'] ) && 'filename' === strtolower( (string) $sig['match_target'] ); } /** Built once per signature-set (constant within a scan): a chunked combined regex of every * pure literal (for the cheap "is ANY literal present?" prefilter) plus the SUBSET of * signatures that are NOT pure literals (the only ones that must still run when the prefilter * proves no literal is present — iterating just these removes the per-signature loop overhead * for thousands of literal feed sigs). Memoised by sig-set fingerprint. */ private static function scan_literal_index( $signatures ) { static $cache_key = null, $cache = null; // GP-REL-013 (audit 2026-06-19): key the memo on a content hash of EVERY pattern, // not count|first|last. The old key collided whenever two distinct sig-sets shared // the same length and endpoints (returning a stale/wrong index), and it thrashed — // recomputing the whole index — when the malware scan alternated between the full // signature set and the high-confidence subset within one request. The hash changes // iff any pattern changes, so the index is a pure, correctly-memoised function of the // set. Detection is unaffected: the produced chunks/non_literal_sigs are identical. // ACG-138-R2-02a: match_target is part of the index's identity. Two sig-sets can share // every pattern and still index differently (a filename-target sig is never a skippable // literal), so the memo key must change when a target changes — otherwise a stale index // could be returned for a set that indexes differently. $key = count( $signatures ) . '|' . md5( implode( "\n", array_column( $signatures, 'pattern' ) ) ) . '|' . md5( implode( "\n", array_map( static function ( $s ) { return (string) ( $s['match_target'] ?? '' ); }, $signatures ) ) ); if ( $key === $cache_key ) { return $cache; } $non_literal_sigs = array(); $literals = array(); foreach ( $signatures as $sig ) { // ACG-138-R2-02a: this prefilter asks "is this literal present in the CONTENT?" and // skips the signature when it is not. That question is meaningless — and the skip is a // FALSE NEGATIVE — for a signature whose subject is the file's NAME: a backdoor named // wp-feed.php need not mention its own name in its bytes. A filename-target signature // is therefore never indexed as a skippable literal; it always runs. $lit = self::sig_matches_filename( $sig ) ? '' : self::scan_pattern_literal( $sig['pattern'] ?? '' ); if ( '' !== $lit ) { $literals[ $lit ] = true; // pure literal → can be skipped when proven absent } else { $non_literal_sigs[] = $sig; // regex / Unicode / metachar / too-short / filename-target → always runs } } $chunks = array(); if ( ! empty( $literals ) ) { foreach ( array_chunk( array_keys( $literals ), 256 ) as $grp ) { $alts = array(); foreach ( $grp as $l ) { $alts[] = preg_quote( $l, '/' ); } $chunks[] = '/' . implode( '|', $alts ) . '/'; // content is pre-lowercased → no /i } } $cache_key = $key; $cache = array( 'chunks' => $chunks, 'non_literal_sigs' => $non_literal_sigs ); return $cache; } /** TRUE only if it is PROVEN that none of the indexed pure literals appear in $content_lc, in * which case every pure-literal signature can be skipped. FALSE (fail open → scan everything) * if any chunk matches OR any chunk fails to compile/run ("regex too large"). Uses presence- * only preg_match (never the match list), so the combined-regex prefix/substring bug — which * only affected COUNTING which literals matched — cannot cause a false "absent" here. */ private static function scan_no_literals_present( $content_lc, $chunks ) { foreach ( $chunks as $re ) { $r = @preg_match( $re, $content_lc ); if ( false === $r ) { return false; } // compile/exec failure → fail open if ( $r > 0 ) { return false; } // some literal IS present → cannot skip } return true; // every chunk matched nothing → no pure literal present } private static function content_has_indicators( $content ) { // Lowercase ONCE — faster than 100× stripos() $lower = strtolower( $content ); // Static: build indicator list once per PHP request, reuse for all files static $indicators = null; if ( $indicators === null ) { // AV-SAFE: indicator tokens stored base64-encoded, decoded in memory. $indicators = explode( "\n", self::_d( 'ZXZhbAphc3NlcnQKc3lzdGVtKApleGVjKApwYXNzdGhydQpzaGVsbF9leGVjCnBvcGVuKApwcm9jX29wZW4KcGNudGxfZXhlYwpjcmVhdGVfZnVuY3Rpb24KY2FsbF91c2VyX2Z1bmMKcHJlZ19yZXBsYWNlCmJhc2U2NF9kZWNvZGUKYmFzZTY0X2VuY29kZQpnemluZmxhdGUKZ3p1bmNvbXByZXNzCmd6ZGVjb2RlCnN0cl9yb3QxMwpyYXd1cmxkZWNvZGUKaGV4MmJpbgpwYWNrKAp1bnBhY2soCmNocigKXHgKJF9wb3N0CiRfZ2V0CiRfcmVxdWVzdAokX2Nvb2tpZQokX2ZpbGVzCiRnbG9iYWxzCnBocDovL2lucHV0CmV4dHJhY3QoCnBhcnNlX3N0cigKJHskCmdvdG8gCm1haWwoCmZpbGVfcHV0X2NvbnRlbnRzCmZ3cml0ZSgKZnB1dHMoCm1vdmVfdXBsb2FkZWRfZmlsZQpjdXJsX2V4ZWMKZnNvY2tvcGVuCnN0cmVhbV9zb2NrZXRfY2xpZW50CnNvY2tldF9jcmVhdGUKaW5jbHVkZSgkCmluY2x1ZGVfb25jZSgkCnJlcXVpcmUoJApyZXF1aXJlX29uY2UoJAppbmNsdWRlICgkXwpyZXF1aXJlICgkXwppbmNsdWRlKCdodHRwCmluY2x1ZGUoImh0dHAKcmVxdWlyZSgnaHR0cApyZXF1aXJlKCJodHRwCnVuc2VyaWFsaXplCl9fd2FrZXVwCl9fZGVzdHJ1Y3QKYzk5c2hlbGwKcjU3c2hlbGwKd3NvX3ZlcnNpb24Kd3NvCmIzNzRrCmZpbGVzbWFuCndlZXZlbHkKaW5kb3hwbG9pdApwaHBzcHkKc2ltYXR0YWNrZXIKc29zdGVsCmFsZmFzaGVsbAphbGZhXwp3cF9jZF9jb2RlCndwLXZjZAp3cF9mZWVkCndwLWZlZWQKYmFsYWRhCnNpZ24xCnNvY2dob2xpc2gKY29pbmhpdmUKY3J5cHRvbG9vdApqc2Vjb2luCmNyeXB0b25pZ2h0CnhtcmlnCnN0cmF0dW0rdGNwCndlYm1pbmVyCm1pbmV4bXIKaGFzaHZhdWx0CmxlYWZtYWlsZXIKa2luZ21haWxlcgphbGZhbWFpbGVyCmhhY2tlZCBieQpoYWNrZWRfYnkKMHduZWQKMHduM2QKcHduM2QKZGlzcGxheTpub25lCmRpc3BsYXk6IG5vbmUKdmlzaWJpbGl0eTpoaWRkZW4KdmlzaWJpbGl0eTogaGlkZGVuCnZpYWdyYQpjaWFsaXMKcGhhcm1hY3kKZ29vZ2xlYm90CmRvY3VtZW50LndyaXRlCmV2YWwoYXRvYgpldmFsKGZ1bmN0aW9uCjxpZnJhbWUKcGF5cGFsCmJhbmsKcGhwaW5mbygpCm9wZW5zc2xfZW5jcnlwdApyYW5zb20KQGluY2x1ZGUKLmljbycpCi5pY28iKQpyZXdyaXRlcnVsZQpsb2NhdGlvbjoKaHR0cDovLzEKaHR0cDovLzIKaHR0cHM6Ly8xCmh0dHBzOi8vMgp1cmxoYXVz' ) ); } foreach ( $indicators as $indicator ) { if ( strpos( $lower, $indicator ) !== false ) { return true; } } return false; } /** * ACG-149-001: the SINGLE source of truth for socket ingress functions. * * A socket is an ingress channel - bytes arriving on it are attacker-controlled. THREE places * must agree on which functions open one: the trigger gate (which decides whether a file is * tokenized at all), the reverse-shell arm (which records the handle), and the coverage-notice * regex (which stops a budget-skipped file from reporting a silent clean verdict). * * Keeping three hand-written copies is exactly what produced the v1.0.148 defect: the arm * accepted `stream_socket_accept`, but the gate listed only the CLIENT openers, so a streams * bind shell (stream_socket_server -> stream_socket_accept -> read -> shell_exec) never opened * the gate, was never tokenized, and scanned CLEAN while the arm sat unreachable 2,400 lines * away. All three now read this list, so they cannot drift apart again. * * The gate matches by SUBSTRING, so 'fsockopen' also covers 'pfsockopen' and 'socket_accept' * also covers 'stream_socket_accept'; the arm matches EXACTLY, so every name is listed. * * @return array Lowercase names of functions yielding an attacker-controlled socket handle. */ /** * ACG-149-016: the ONE place a "partially scanned" coverage notice is raised. * * Three call sites carried their own copy of these eight lines, differing only in the sentence * that explains WHY the file could not be finished. The truncation flag, the verdict-cache veto, * the risk floor and the finding shape were duplicated, so any change had to be made three times * or the copies would drift. This release exists because two hand-kept copies of an ingress list * drifted (ACG-149-001); the same shape is not left standing. * * The notice is deliberately fail-VISIBLE: it floors the risk score so the file clears the batch * record threshold, and vetoes the verdict cache, so a file we could not finish never presents as * a confident clean result. * * @param array $result Scan result, by reference. * @param string $description Why this particular file could not be finished. * @return void */ /** * ACG-149-017: charge one unit of paren-scan work and report whether budget remains. * * Replaces the bare `++self::$scan_work < 2000000` guard at every sink-argument scan. When the * per-file budget is spent it sets self::$analysis_truncated so the file cannot end as a silent * clean verdict, and returns false so the loop stops (the DoS bound is preserved). * * @return bool true while budget remains. */ private static function scan_budget_ok() { if ( ++self::$scan_work < 2000000 ) { return true; } self::$analysis_truncated = true; return false; } private static function add_coverage_notice( &$result, $description ) { $result['scan_truncated'] = true; self::$last_verdict_cacheable = false; $result['risk_score'] = max( (int) ( $result['risk_score'] ?? 0 ), 50 ); $result['findings'][] = array( 'type' => 'coverage', 'severity' => 'medium', 'name' => __( 'File only partially scanned', 'ai-cyberguard' ), 'description' => $description, 'recommendation' => __( 'Review this file manually; it was not fully verified as clean.', 'ai-cyberguard' ), ); } private static function socket_ingress_fns() { return array( // client side: the classic reverse shell dials out to the attacker 'fsockopen', 'pfsockopen', 'stream_socket_client', // server side: a bind shell listens and accepts. `stream_socket_server` was the // v1.0.148 omission that made the whole streams branch of the arm dead code. 'stream_socket_server', 'stream_socket_accept', 'socket_create', 'socket_accept', ); } /** * ACG-042-001 (audit 2026-06-21, HIGH): produce a normalized view of file content for an * additional signature-matching pass, so trivial syntactic obfuscation between tokens cannot * evade a behaviour-based built-in signature. Three normalizations, all of which only REMOVE or * FUSE characters (they cannot manufacture a malware token that the raw bytes did not contain * the pieces of): * 1. strip /* ... *​/ block comments (eval/**​/(...), $_GET["a"]/**​/(...)) * 2. fuse same-quote string concatenations ("php:" . "//input" -> "php://input") * 3. collapse runs of whitespace to a single space * Returns the normalized string, or null when content is empty or too large to normalize cheaply * (the raw pass still runs in that case). NOTE: this is intentionally NOT a full PHP tokenizer — * it must work on arbitrary, possibly-invalid files and is only ever used to ADD detections. * * @param string $content raw file bytes * @return string|null */ /** * ACG-149-131b: the UTF-8 bytes of one codepoint, for PHP's `\u{...}` escape. Written out rather than * calling mb_* or IntlChar, neither of which is guaranteed present on a shared host. */ private static function gp_utf8_chr( $cp ) { $cp = (int) $cp; if ( $cp < 0x80 ) { return chr( $cp ); } if ( $cp < 0x800 ) { return chr( 0xC0 | ( $cp >> 6 ) ) . chr( 0x80 | ( $cp & 0x3F ) ); } if ( $cp < 0x10000 ) { return chr( 0xE0 | ( $cp >> 12 ) ) . chr( 0x80 | ( ( $cp >> 6 ) & 0x3F ) ) . chr( 0x80 | ( $cp & 0x3F ) ); } return chr( 0xF0 | ( $cp >> 18 ) ) . chr( 0x80 | ( ( $cp >> 12 ) & 0x3F ) ) . chr( 0x80 | ( ( $cp >> 6 ) & 0x3F ) ) . chr( 0x80 | ( $cp & 0x3F ) ); } private static function detect_execution_sinks_tokenized( $content ) { self::$scan_work = 0; // ACG-149-007: per-FILE bound on the sink-argument scans self::$analysis_truncated = false; // ACG-149-017: reset the fail-visible truncation flag $content = (string) $content; self::$tokenizer_skipped = false; if ( '' === $content || ! function_exists( 'token_get_all' ) ) { return array(); } $lc = strtolower( $content ); // Cheap trigger gate: if none of the sink-relevant tokens appear at all, there is nothing to do. // ACG-106 fresh-eyes (2026-07-01): the gate must admit EVERY request-ingress marker the downstream // predicates recognise, or a sink fed only by that marker is unreachable. The request BODY stream // ('php://input', read via file_get_contents/fopen/fread) and the request HEADER readers // (getallheaders/apache_request_headers, in $req_read) were missing — so e.g. a bare // system(file_get_contents('php://input')) (no $_ / eval token anywhere) skipped the tokenizer and // shipped invisible. The eval() form was already caught only because the literal 'eval' opened the gate. // ACG-148-007: this list IS the set of ingress channels the detector knows about. Every marker // below used to name the same one - the HTTP request - so a backdoor fed from anywhere else was // unreachable: a complete reverse shell (socket in, command out, no `$_` anywhere) skipped the // tokenizer entirely and scanned clean. Any arm that teaches the detector a NEW source of // attacker-controlled data MUST add its marker here, or that arm is dead code. $gp_gate_cs = array( '$_', '$GLOBALS', '${' ); // case-sensitive: variable names $gp_gate_lc = array_merge( array( // -- channel: the HTTP request (body, headers, superglobals) and the code-entry sinks 'eval', 'assert', 'extract', 'parse_str', 'call_user_func', 'filter_input', 'php://input', 'getallheaders', 'apache_request_headers', 'include', 'require', // ACG-149-039 (siege 5 #3): raw-socket stream wrappers - fopen("tcp://...") opens a socket, // and none of the function names above appear in an fopen-based reverse shell. 'tcp://', 'ssl://', 'tls://', 'udp://', ), // -- channel: a raw network socket (reverse shells, socket-fed C2). ACG-148-005. // ACG-149-001: read from the SINGLE source of truth, so the gate can never again know // FEWER socket openers than the arm that depends on it (the v1.0.148 dead-arm defect). self::socket_ingress_fns() ); $gp_gate_open = false; foreach ( $gp_gate_cs as $gp_gm ) { if ( false !== strpos( $content, $gp_gm ) ) { $gp_gate_open = true; break; } } if ( ! $gp_gate_open ) { foreach ( $gp_gate_lc as $gp_gm ) { if ( false !== strpos( $lc, $gp_gm ) ) { $gp_gate_open = true; break; } } } // ACG-149-053 (siege 7 #2/#4): string-splitting is the most common webshell obfuscation, and the // downstream wrapper resolver (ACG-149-046, $const_str) already reassembles a split/variable-held // socket wrapper - but only if the gate lets the file reach the tokenizer. The contiguous strpos above // misses `fopen("tc"."p://...")` and `$a="tcp";$u=$a."://..."`, so that resolver was dead code for the // exact obfuscation it exists to defeat. FUSE adjacent quoted string literals (drop `"."`), then look // for any transport scheme within a short, single-line window of `://` (this admits both the split // literal and the two-variable assembly). A false open here costs only a tokenizer pass, never a // false finding. if ( ! $gp_gate_open ) { $gp_fused = preg_replace( '/["\x27]\s*\.\s*["\x27]/', '', $lc ); if ( ! is_string( $gp_fused ) ) { $gp_fused = $lc; } if ( preg_match( '/(?:tcp|ssl|tls|udp)[^\r\n]{0,40}?:\/\//i', $gp_fused ) ) { $gp_gate_open = true; } } // ACG-149-063 (siege 8 #2/#3): the same fopen-socket resolver ALSO folds a wrapper produced by a DECODER // (base64_decode/str_rot13/strrev/gz*/hex2bin/...) - base64 is the commonest webshell obfuscation and the // 40-char proximity above misses it entirely (the scheme is encoded away) - and a wrapper whose scheme // literal sits far from `://` (a long variable name or a multi-line assembly). When fopen co-occurs with a // decoder, OR with a transport scheme word plus a `://`, open the gate and let the resolver decide. A false // open costs only a tokenizer pass, never a false finding. if ( ! $gp_gate_open && false !== strpos( $lc, 'fopen' ) ) { static $gp_wrap_dec = null; if ( null === $gp_wrap_dec ) { $gp_wrap_dec = array( 'base64_decode', 'str_rot13', 'strrev', 'gzinflate', 'gzuncompress', 'gzdecode', 'hex2bin', 'convert_uudecode' ); } foreach ( $gp_wrap_dec as $gp_wd ) { if ( false !== strpos( $lc, $gp_wd ) ) { $gp_gate_open = true; break; } } // ACG-149-069 (siege 10 #3): a scheme split INSIDE the 3-letter word through a VARIABLE (`"tc".$x` // with $x="p://...") leaves no contiguous scheme word for the check above, but the "://" authority // separator survives in the variable's literal. fopen (checked above) co-occurring with "://" anywhere // opens the gate; the const_str resolver then spans the variable and decides. A false open is only a // tokenizer pass, never a false finding. if ( ! $gp_gate_open && false !== strpos( $lc, '://' ) ) { $gp_gate_open = true; } } if ( ! $gp_gate_open ) { return array(); } // ACG-148-009 (self-review, second siege): the MEMORY-budget check runs AFTER the trigger gate, not // before it. A file with NO ingress marker has nothing for the tokenizer to find, so declining to // tokenize it costs no coverage and must not raise a "partially scanned" notice — doing that before // the gate flagged clean, benign large files (compiled config, generated code) as not-fully-scanned // on ordinary low-memory shared hosts (128M budget ~= 317 KB), flooring their risk and blocking the // green all-clear. Only a file that WOULD be tokenized (an indicator opened the gate — e.g. a padded // webshell whose system/$_POST is present) and is too large for the memory left is recorded skipped; // that is the exact "padded webshell reports clean" case the notice exists to make visible. if ( strlen( $content ) > self::tokenizer_budget_bytes() ) { self::$tokenizer_skipped = true; return array(); } $raw = @token_get_all( $content ); // tolerant of invalid PHP; non-PHP bytes → T_INLINE_HTML if ( ! is_array( $raw ) || count( $raw ) < 3 ) { return array(); } // Build a compact CODE token list — DROP comments, whitespace and inline HTML so the matching is // immune to them; a string literal stays ONE token (so request text inside a documentation string // is never mistaken for executable code). Entries: array(int $id, string $text) | array('c', $char). // ACG-148-009: $raw, $tok and $col were all alive at once - three copies of the same file at // ~100x its size each. Each raw token is released as soon as it has been converted, so peak // memory is one array instead of three. Nothing reads $raw out of order, so this is safe. $tok = array(); $gp_nraw = count( $raw ); for ( $gp_ri = 0; $gp_ri < $gp_nraw; $gp_ri++ ) { $t = $raw[ $gp_ri ]; $raw[ $gp_ri ] = 0; if ( is_array( $t ) ) { $id = $t[0]; if ( T_COMMENT === $id || T_DOC_COMMENT === $id || T_WHITESPACE === $id || T_INLINE_HTML === $id ) { continue; } // ACG-149-059 (siege 8 #5): PHP 8's nullsafe method operator ?-> (T_NULLSAFE_OBJECT_OPERATOR) is, // for every method-vs-global decision in this file, identical to -> . Normalising it here means all // ~14 `->`/`::` guards (the upload sanitizer allowance, the callee arm, $prev_op, the callback APIs) // treat `$o?->m()` exactly like `$o->m()` with no per-site change and no risk of a missed guard. if ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $id ) { $id = T_OBJECT_OPERATOR; } $tok[] = array( $id, (string) $t[1] ); } else { $tok[] = array( 'c', (string) $t ); } } unset( $raw, $t ); $n = count( $tok ); // ACG-106b fresh-eyes (2026-07-01): $GLOBALS is request data ONLY when it ALIASES a request superglobal // ($GLOBALS['_POST'] === $_POST). A plain $GLOBALS['tgmpa'] is an ordinary APPLICATION global, not attacker // input — treating every $GLOBALS[..] as a superglobal false-positived legit library code such as // call_user_func( array( get_class( $GLOBALS['tgmpa'] ), 'get_instance' ) ) (TGM-Plugin-Activation, bundled in // thousands of themes) as a request-driven CRITICAL call. Collapse $GLOBALS[''] into a synthetic // superglobal token so the alias obfuscation is still caught, and drop bare $GLOBALS from $supers below so a // non-super index is just a normal variable. $alias_supers = array( '_GET'=>'$_GET','_POST'=>'$_POST','_REQUEST'=>'$_REQUEST','_COOKIE'=>'$_COOKIE','_SERVER'=>'$_SERVER','_FILES'=>'$_FILES','_ENV'=>'$_ENV' ); $col = array(); for ( $ci = 0; $ci < $n; $ci++ ) { $c0 = $tok[ $ci ]; if ( is_int( $c0[0] ) && T_VARIABLE === $c0[0] && '$GLOBALS' === $c0[1] && $ci + 3 < $n && array( 'c', '[' ) === $tok[ $ci + 1 ] && is_int( $tok[ $ci + 2 ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $ci + 2 ][0] && array( 'c', ']' ) === $tok[ $ci + 3 ] ) { $key = trim( $tok[ $ci + 2 ][1], "\"'" ); if ( isset( $alias_supers[ $key ] ) ) { $col[] = array( T_VARIABLE, $alias_supers[ $key ] ); $ci += 3; continue; } } $col[] = $c0; } $tok = $col; unset( $col ); $n = count( $tok ); // Request-tainted SUPERGLOBALS. ($GLOBALS is NOT a blanket super — see the alias-collapse above.) $supers = array( '$_GET' => 1, '$_POST' => 1, '$_REQUEST' => 1, '$_COOKIE' => 1, '$_SERVER' => 1, '$_FILES' => 1, '$_ENV' => 1 ); // Functions whose RESULT is request data (their output is tainted). $req_read = array( 'filter_input' => 1, 'filter_input_array' => 1, 'getallheaders' => 1, 'apache_request_headers' => 1 ); // Functions that READ an external stream/file — eval/assert of their result is the classic RCE sink // (covers a php://input read however the stream argument is assembled: literal, concat, join, chr(), variable). $stream_read = array( 'file_get_contents' => 1, 'fopen' => 1, 'stream_get_contents' => 1, 'fread' => 1, 'readfile' => 1 ); // ACG-148-004 (self-review, agent 3): filename sanitizers that REMOVE path traversal. A request // value wrapped in one of these can no longer escape a fixed directory, so a move_uploaded_file() // destination built with it is the ordinary import/media idiom, not an upload-shell drop. // Two ways a request value stops being able to steer an upload path. (a) FILENAME SANITISERS // strip traversal; (b) ACG-149-009 VALUE NARROWERS return a token drawn from a fixed alphabet - // hex or digits - which can carry neither a '/' nor a '.php', so the destination is fixed by // construction. Without (b), `$dir . md5($_POST['name']) . '.jpg'` and `(int)$_POST['id']` - // textbook media/import code - were reported as CRITICAL malware. $upload_sanitizers = array( // (a) filename sanitisers 'sanitize_file_name' => 1, 'basename' => 1, 'wp_basename' => 1, 'wp_unique_filename' => 1, 'sanitize_key' => 1, 'sanitize_title' => 1, // (b) value narrowers - hex or numeric output only 'md5' => 1, 'sha1' => 1, 'crc32' => 1, 'hash' => 1, 'dechex' => 1, 'bin2hex' => 1, 'intval' => 1, 'absint' => 1, 'floatval' => 1, 'doubleval' => 1, ); /** * PHP's OWN escape processing for a double-quoted string / heredoc body. * * ACG-149-131b (adversarial pass): this used to be `stripcslashes()`, which is a C unescaper and NOT * PHP's. Ground-truthed against the interpreter over every printable character: they agree on 13 of 90. * The three ways that mattered, all proven by running real PHP: * \assert PHP keeps the backslash ("\assert", which IS the global assert) stripcslashes -> BEL."ssert" * \wp-content PHP keeps it (a Windows path) stripcslashes -> "wp-content" * \u{73}ystem PHP decodes the codepoint -> "system" stripcslashes -> literal * \exec PHP reads \e as ESC -> ESC."xec" (harmless) stripcslashes -> "exec" (!) * The first two are FALSE NEGATIVES (a real dangerous name stops resolving), the last a FALSE POSITIVE * on harmless text. PHP's rule is simple and is implemented here exactly: a known escape is replaced, * and ANY other character after a backslash keeps BOTH the backslash and the character. */ $gp_php_unescape = static function ( $s ) { $s = (string) $s; if ( false === strpos( $s, '\\' ) ) { return $s; } $out = ''; $len = strlen( $s ); for ( $p = 0; $p < $len; $p++ ) { if ( '\\' !== $s[ $p ] || $p + 1 >= $len ) { $out .= $s[ $p ]; continue; } $c = $s[ ++$p ]; switch ( $c ) { case 'n': $out .= "\n"; break; case 't': $out .= "\t"; break; case 'r': $out .= "\r"; break; case 'v': $out .= "\v"; break; case 'f': $out .= "\f"; break; case 'e': $out .= "\x1b"; break; case '\\': $out .= '\\'; break; case '$': $out .= '$'; break; case '"': $out .= '"'; break; case 'x': if ( preg_match( '/^[0-9A-Fa-f]{1,2}/', substr( $s, $p + 1, 2 ), $m ) ) { $out .= chr( hexdec( $m[0] ) ); $p += strlen( $m[0] ); } else { $out .= '\\x'; } break; case 'u': if ( preg_match( '/^\{([0-9A-Fa-f]+)\}/', substr( $s, $p + 1, 12 ), $m ) ) { $cp = hexdec( $m[1] ); // the codepoint form is UTF-8; anything above the BMP-safe range is left alone $out .= ( $cp >= 0 && $cp <= 0x10FFFF ) ? self::gp_utf8_chr( $cp ) : ( '\\u' . $m[0] ); $p += strlen( $m[0] ); } else { $out .= '\\u'; } break; default: if ( $c >= '0' && $c <= '7' ) { preg_match( '/^[0-7]{1,3}/', substr( $s, $p, 3 ), $m ); $out .= chr( octdec( $m[0] ) & 0xFF ); $p += strlen( $m[0] ) - 1; } else { $out .= '\\' . $c; // PHP keeps BOTH - this is the case stripcslashes got wrong } } } return $out; }; $decode = static function ( $lit ) use ( $gp_php_unescape ) { $lit = (string) $lit; if ( strlen( $lit ) < 2 ) { return ''; } $q = $lit[0]; $inner = substr( $lit, 1, -1 ); return ( "'" === $q ) ? str_replace( array( '\\\\', "\\'" ), array( '\\', "'" ), $inner ) : $gp_php_unescape( $inner ); }; // ACG-149-124 (round 24): TOTAL on any input. It was called with a null (an out-of-range $tok[...] read on a // truncated file) from more than one site, each emitting "Trying to access array offset on null". Guarding the // primitive fixes the whole class at once instead of one caller at a time. $is_char = static function ( $e, $c ) { return 'c' === $e[0] && $c === $e[1]; }; $is_super = static function ( $e ) use ( $supers ) { return is_int( $e[0] ) && T_VARIABLE === $e[0] && isset( $supers[ $e[1] ] ); }; $is_fn = static function ( $e, $set ) { return is_int( $e[0] ) && T_STRING === $e[0] && isset( $set[ strtolower( $e[1] ) ] ); }; // ACG-149-054 (siege 7 #6 + finder-I): a superglobal that is ONLY a boolean CONDITION - the argument of // isset()/empty(), or an operand of a comparison - contributes NO bytes to a path or command. The request // merely SELECTS among fixed literals (`isset($_POST['big']) ? $bigDir : $smallDir`, // `system("x".($_POST['e']==='png'?'png':'jpg'))`). Firing on it re-opens the ordinary-handler FP class. $gp_sink_names = array( 'system' => 1, 'exec' => 1, 'shell_exec' => 1, 'passthru' => 1, 'popen' => 1, 'proc_open' => 1, 'pcntl_exec' => 1, 'eval' => 1, 'assert' => 1, 'call_user_func' => 1, 'call_user_func_array' => 1, 'create_function' => 1, 'extract' => 1, 'parse_str' => 1 ); // ACG-149-085 (siege 18 #3/#4): a super that is a sink's direct ARGUMENT is executed, never condition-only $gp_super_is_cond = static function ( $pos, $gp_asgn_rhs = false ) use ( &$tok, $n, $is_char, $gp_sink_names ) { $gp_cmp = array( T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, T_SPACESHIP ); $gp_af = $pos + 1; // ACG-149-058 (siege 8 #8): charge these walks to the global work budget so a file that stacks the // helper into a hot O(N*M) path (nested exec() around many superglobals) trips the fail-visible // coverage notice instead of hanging silently. A budget-out ends the walk (-> "not a condition"). while ( $gp_af < $n && $is_char( $tok[ $gp_af ], '[' ) && self::scan_budget_ok() ) { $gp_ad = 1; $gp_af++; while ( $gp_af < $n && $gp_ad > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_af ], '[' ) ) { $gp_ad++; } elseif ( $is_char( $tok[ $gp_af ], ']' ) ) { $gp_ad--; } $gp_af++; } } if ( $gp_af < $n && ( $is_char( $tok[ $gp_af ], '<' ) || $is_char( $tok[ $gp_af ], '>' ) || ( is_int( $tok[ $gp_af ][0] ) && in_array( $tok[ $gp_af ][0], $gp_cmp, true ) ) ) ) { return true; } // ACG-149-058 (siege 8 #9): a bare-truthiness ternary condition selects among two fixed branches - the // super contributes no output bytes. EXCLUDE the Elvis `?:` (super IS the value if truthy); `??` is // T_COALESCE, a different token, so it is likewise not matched. if ( $gp_af < $n && $is_char( $tok[ $gp_af ], '?' ) && ! ( $gp_af + 1 < $n && $is_char( $tok[ $gp_af + 1 ], ':' ) ) ) { return true; } // ACG-149-086-fix (siege 19 adversarial review, FP #5): a super that is an OPERAND of a SYMBOL-FORM logical // connective (&& ||) is used in a BOOLEAN context - only its truthiness propagates, never its bytes - so // `system("backup.sh ".($_GET['full'] && $cfg['allow'] ? '--full':'--quick'))` contributes zero request bytes. // ONLY && and || (T_BOOLEAN_*) qualify: they bind TIGHTER than `=`, so `$x = $_GET[a] && $b` assigns a boolean. // The WORD forms and/or/xor (T_LOGICAL_*) bind LOOSER than `=`, so `$cmd = $_GET['c'] or die()` parses as // `($cmd = $_GET['c']) or die()` - $cmd receives the RAW request bytes - and must NOT be treated as // condition-only (siege-20 adversarial review: doing so silenced the classic `... or die()` backdoor guard, // because $gp_super_is_cond is also consulted by the $rhs_src assignment-taint tracker). if ( $gp_af < $n && is_int( $tok[ $gp_af ][0] ) && in_array( $tok[ $gp_af ][0], array( T_BOOLEAN_AND, T_BOOLEAN_OR ), true ) ) { return true; } // Word forms and/or/xor (T_LOGICAL_*) also booleanise the super and ARE condition-only in an EXPRESSION // context (`system("x".($_GET['f'] or $d ? 'a':'b'))`), EXCEPT when the caller is analysing an ASSIGNMENT // RHS ($gp_asgn_rhs): word ops bind LOOSER than `=`, so `$cmd = <..> $_GET['c'] or die()` is // `($cmd = <..>$_GET['c']) or die()` - $cmd captures the raw super regardless of how far it sits from the // `=` (a leading concat, cast, etc.). The context flag is passed true ONLY by the $rhs_src taint caller; // every command/callable/condition caller leaves it false, so a word-form super there stays condition-only. // (siege-20 adversarial review: replaced a fragile "immediately after `=`" heuristic that missed // `$cmd = $prefix . $_GET['c'] or die()`.) if ( $gp_af < $n && is_int( $tok[ $gp_af ][0] ) && in_array( $tok[ $gp_af ][0], array( T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR ), true ) && ! $gp_asgn_rhs ) { return true; } // ACG-149-084 (siege 17 #2): a super WRAPPED IN A FUNCTION that forms the ternary CONDITION - // `wp_verify_nonce($_POST['n']) ? $fixedA : $fixedB` - contributes no bytes to the selected value (both // branches are the developer's fixed maps). Walk OUT of the call(s) enclosing the super; if a BARE `?` // (not Elvis `?:`, not `??`) follows at the expression top level before any branch/arg/statement boundary, // the super is condition-only. This fixes a v1.0.147->v1.0.149 regression that branded the nonce-guarded // dispatch-map idiom (LOCAL var or property) as request-controlled malware. // ACG-149-085 (siege 18 #3/#4) + ACG-149-086 (siege 19 #7/#2/#4/#6): a super that is EXECUTED by a SINK // (`system($_POST['c']) ? A : B`, and CRUCIALLY the obfuscated `system(base64_decode($_POST['c'])) ? A : B`) // is NOT condition-only even when the sink's RESULT is the ternary condition. Walk back through EVERY // enclosing call up to the statement/argument boundary - not just the innermost one - and if ANY of them is // a GLOBAL sink (system/exec/eval/... , not a method/static that merely shares the name: `$o->extract(..)` / // `Cls::exec(..)` are benign), the super is executed -> leave it a live request source (skip the forward-walk). // Build the ENCLOSING calls (innermost first) and flag each that is a GLOBAL sink. `[` subscripts are // recorded as non-sink levels so the forward-walk's level index stays aligned. $gp_encl = array(); $gp_ek = $pos - 1; $gp_ed = 0; $gp_es = 0; while ( $gp_ek >= 0 && $gp_es++ < 400 ) { $gp_eec = $tok[ $gp_ek ]; if ( $is_char( $gp_eec, ')' ) || $is_char( $gp_eec, ']' ) ) { $gp_ed++; } elseif ( $is_char( $gp_eec, '(' ) || $is_char( $gp_eec, '[' ) ) { if ( 0 === $gp_ed ) { $gp_encl[] = ( $is_char( $gp_eec, '(' ) && $gp_ek - 1 >= 0 && is_int( $tok[ $gp_ek - 1 ][0] ) && isset( $tok[ $gp_ek - 1 ][1] ) && isset( $gp_sink_names[ ltrim( strtolower( (string) $tok[ $gp_ek - 1 ][1] ), '\\' ) ] ) && ! ( $gp_ek - 2 >= 0 && is_int( $tok[ $gp_ek - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_ek - 2 ][0] || T_DOUBLE_COLON === $tok[ $gp_ek - 2 ][0] || ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $tok[ $gp_ek - 2 ][0] ) ) ) ); } else { $gp_ed--; } } // ACG-149-086-fix (siege 19 FN #4) REVERTED after siege-20 adversarial review: removing the `,`-stop so // the enclosing-walk could reach a sink past a wrapper's argument comma ALSO let the forward-walk return // "executed" BEFORE the pre-existing isset()/empty() and comparison-operand condition-only rules (below) // could fire, so `system(sprintf("... --debug=%d", (int)!empty($_GET['x'])))` and // `exec(sprintf("... --gz=%d", (int)($size > $_POST['max'])))` - MAINSTREAM 0/1-flag-into-a-shell-command // idioms - were branded CRITICAL shell malware (owner's #1 fear). The FN it closed (a request value // wrapped in a MULTI-ARG function whose sink RESULT is only a ternary condition) is a contrived // scanner-evasion whose DIRECT form is caught, so the `,`-stop is restored and that FN is a documented // residual. A `,` at depth 0 bounds the walk to the super's own argument. elseif ( 0 === $gp_ed && ( $is_char( $gp_eec, ';' ) || $is_char( $gp_eec, ',' ) || $is_char( $gp_eec, '{' ) || $is_char( $gp_eec, '}' ) ) ) { break; } $gp_ek--; } // Forward-walk from the super. As its value EXITS each enclosing call: if that call is a GLOBAL SINK the super // was EXECUTED by it (`system(base64_decode($_POST))?A:B`) -> NOT condition-only (return false). If a bare `?` // is reached first, the super only fed a ternary CONDITION whose fixed branches carry no request bytes // (`system('ls '.($o->exec($_GET)?'a':'b'))`) -> condition-only (return true). $gp_ck = $gp_af; $gp_cd = 0; $gp_cs = 0; while ( $gp_ck < $n && $gp_cs++ < 300 && self::scan_budget_ok() ) { $gp_cc = $tok[ $gp_ck ]; if ( $is_char( $gp_cc, '(' ) || $is_char( $gp_cc, '[' ) ) { $gp_cd++; } elseif ( $is_char( $gp_cc, ')' ) || $is_char( $gp_cc, ']' ) ) { $gp_cd--; if ( $gp_cd < 0 ) { $gp_lvl = -$gp_cd - 1; if ( isset( $gp_encl[ $gp_lvl ] ) && $gp_encl[ $gp_lvl ] ) { return false; } } } elseif ( $gp_cd < 0 ) { // exited the call(s) enclosing the super, without reaching a sink if ( $is_char( $gp_cc, '?' ) && ! ( $gp_ck + 1 < $n && $is_char( $tok[ $gp_ck + 1 ], ':' ) ) ) { return true; } if ( $is_char( $gp_cc, ';' ) || $is_char( $gp_cc, ',' ) || $is_char( $gp_cc, ':' ) || ( is_int( $gp_cc[0] ) && defined( 'T_COALESCE' ) && T_COALESCE === $gp_cc[0] ) ) { break; } } $gp_ck++; } if ( $pos - 1 >= 0 && ( $is_char( $tok[ $pos - 1 ], '<' ) || $is_char( $tok[ $pos - 1 ], '>' ) || $is_char( $tok[ $pos - 1 ], '!' ) || ( is_int( $tok[ $pos - 1 ][0] ) && ( in_array( $tok[ $pos - 1 ][0], $gp_cmp, true ) // ACG-149-086-fix (siege 19 adversarial review, FP #5): the super is the RIGHT operand of a logical // connective (`$cfg && $_GET['f']`, `$x or $_GET['f']`) - a boolean context, bytes never reach a // command. Word forms are safe here too: a right operand of and/or/xor is never an assignment target // ( `$cmd = $x or $_GET['a']` assigns $x, not the super ), so no assignment guard is needed. || in_array( $tok[ $pos - 1 ][0], array( T_BOOLEAN_AND, T_BOOLEAN_OR, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR ), true ) ) ) ) ) { return true; } $gp_bk = $pos - 1; $gp_bd = 0; $gp_bs = 0; while ( $gp_bk >= 1 && $gp_bs++ < 200 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_bk ], ')' ) || $is_char( $tok[ $gp_bk ], ']' ) ) { $gp_bd++; } elseif ( $is_char( $tok[ $gp_bk ], '(' ) || $is_char( $tok[ $gp_bk ], '[' ) ) { if ( 0 === $gp_bd ) { // isset/empty are LANGUAGE CONSTRUCTS (T_ISSET/T_EMPTY), not T_STRING - match on text. But // ACG-149-058 (siege 8 #4): an attacker-defined METHOD named isset/empty reached via ->/::/?-> // is NOT the language construct and must not suppress the sink - mirror ACG-149-055. if ( $gp_bk - 1 >= 0 && is_int( $tok[ $gp_bk - 1 ][0] ) && isset( $tok[ $gp_bk - 1 ][1] ) && in_array( strtolower( (string) $tok[ $gp_bk - 1 ][1] ), array( 'isset', 'empty' ), true ) && ! ( $gp_bk - 2 >= 0 && is_int( $tok[ $gp_bk - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_bk - 2 ][0] || T_DOUBLE_COLON === $tok[ $gp_bk - 2 ][0] || ( defined( 'T_NULLSAFE_OBJECT_OPERATOR' ) && T_NULLSAFE_OBJECT_OPERATOR === $tok[ $gp_bk - 2 ][0] ) ) ) ) { return true; } break; } $gp_bd--; } elseif ( 0 === $gp_bd && ( $is_char( $tok[ $gp_bk ], ';' ) || $is_char( $tok[ $gp_bk ], '{' ) || $is_char( $tok[ $gp_bk ], '}' ) ) ) { break; } $gp_bk--; } return false; }; // ===== variable-variable superglobal rewrite ===== // Collapse ${"_GET"} and ${$alias} (where $alias was assigned a superglobal NAME) into a single // synthetic superglobal T_VARIABLE token, so all later analysis treats them as $_GET et al. $name_alias = array(); $rt = array(); for ( $i = 0; $i < $n; $i++ ) { if ( is_int( $tok[ $i ][0] ) && T_VARIABLE === $tok[ $i ][0] && $i + 2 < $n && $is_char( $tok[ $i + 1 ], '=' ) && is_int( $tok[ $i + 2 ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $i + 2 ][0] ) { $nm = trim( $tok[ $i + 2 ][1], "'\"" ); if ( isset( $supers[ '$' . $nm ] ) ) { $name_alias[ $tok[ $i ][1] ] = '$' . $nm; } } if ( $is_char( $tok[ $i ], '$' ) && $i + 3 < $n && $is_char( $tok[ $i + 1 ], '{' ) && $is_char( $tok[ $i + 3 ], '}' ) ) { $in = $tok[ $i + 2 ]; $res = ''; if ( is_int( $in[0] ) && T_CONSTANT_ENCAPSED_STRING === $in[0] && isset( $supers[ '$' . trim( $in[1], "'\"" ) ] ) ) { $res = '$' . trim( $in[1], "'\"" ); } elseif ( is_int( $in[0] ) && T_VARIABLE === $in[0] && isset( $name_alias[ $in[1] ] ) ) { $res = $name_alias[ $in[1] ]; } if ( '' !== $res ) { $rt[] = array( T_VARIABLE, $res ); $i += 3; continue; } } $rt[] = $tok[ $i ]; } $tok = $rt; $n = count( $tok ); /** Index of the '}' matching the '{' at $open, or -1. Interpolation opens with an ARRAY token * (T_CURLY_OPEN) and closes with a plain '}', so both forms must be counted here. */ $gp_match_brace = static function ( $open ) use ( &$tok, $n, $is_char ) { $d = 0; for ( $k = $open; $k < $n; $k++ ) { $x = $tok[ $k ]; if ( $is_char( $x, '{' ) || ( is_int( $x[0] ) && ( T_CURLY_OPEN === $x[0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $x[0] ) ) ) ) { $d++; continue; } if ( $is_char( $x, '}' ) ) { $d--; if ( 0 === $d ) { return $k; } } } return -1; }; // ACG-143-001 (reviewer 2, 2026-07-17): MINIMAL PHP NAME RESOLUTION. // // Every "is this PHP's own class?" guard so far compared the class TOKEN TEXT to a name. That is not // what PHP does, and it was wrong in BOTH directions at once: // namespace Opis; Closure::fromCallable('system')(...) -> we said \Closure. It is Opis\Closure. // (CRITICAL false positive on vendor code) // (new \ReflectionFunction('system'))->invoke($_POST) -> we said "not the global class". // (missed entirely - false negative) // For a CLASS name PHP has NO global fallback: inside `namespace X`, an unqualified `Closure` always // means `X\Closure`, never `\Closure`, unless a `use` import says otherwise. That single rule fixes // the false positive and the false negative together, which is why it belongs here as a shared // primitive rather than as another per-arm condition. // ACG-143-010 (adversarial review, 2026-07-19): the first cut of this prescan was FILE-GLOBAL -- // one namespace ("last declaration wins") and one flat alias map for the whole file. That was // wrong in both directions at once, and it produced three REGRESSIONS against v1.0.142: // namespace App { } namespace { Closure::fromCallable('system')($_POST['a']); } // the second block is the GLOBAL namespace, but the prescan still held "app" -> MISSED. // namespace\Closure::fromCallable('system')($_POST['a']); // PHP 8 emits this as one T_NAME_RELATIVE token; nothing handled it -> MISSED. // class _x { use A\Closure; } Closure::fromCallable('system')($_POST['a']); // a TRAIT use inside a class body is not an import, but it registered an alias that made // `Closure` resolve to A\Closure -> MISSED. One attacker-supplied line anywhere in a file // silenced the entire Closure/ReflectionFunction family. That is a door, not a bug. // and, in the false-positive direction, an import in ONE namespace block leaked into every other. // Namespace scope is POSITIONAL, so resolution has to be positional too. $gp_regions = array(); // each: array( 'start' => int, 'end' => int|-1, 'ns' => string ) for ( $pi = 0; $pi < $n; $pi++ ) { if ( ! ( is_int( $tok[ $pi ][0] ) && T_NAMESPACE === $tok[ $pi ][0] ) ) { continue; } $q = $pi + 1; if ( $q >= $n ) { break; } // `namespace { ... }` -- an explicit GLOBAL block. if ( $is_char( $tok[ $q ], '{' ) ) { $gp_regions[] = array( 'start' => $pi, 'end' => $gp_match_brace( $q ), 'ns' => '' ); continue; } // A NAME must follow for this to be a declaration. Anything else (a separator) means this // is the `namespace\Foo` OPERATOR, which is an expression, not a declaration. if ( ! is_int( $tok[ $q ][0] ) ) { continue; } if ( ! ( T_STRING === $tok[ $q ][0] || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $q ][0] ) ) ) { continue; } $gp_nm = strtolower( ltrim( (string) $tok[ $q ][1], chr( 92 ) ) ); $gp_regions[] = array( 'start' => $pi, 'end' => ( $q + 1 < $n && $is_char( $tok[ $q + 1 ], '{' ) ) ? $gp_match_brace( $q + 1 ) : -1, 'ns' => $gp_nm, ); } /** Innermost namespace region containing a token index; -1 means the implicit global region. */ $gp_region_of = static function ( $idx ) use ( &$gp_regions ) { $best = -1; foreach ( $gp_regions as $ri => $r ) { if ( $idx < $r['start'] ) { continue; } if ( $r['end'] >= 0 && $idx > $r['end'] ) { continue; } $best = $ri; } return $best; }; // Alias maps, one per region: lowercased alias => lowercased fully-qualified name. $gp_use = array(); // ACG-146-001: lowercased alias => lowercased fully-qualified FUNCTION name, per region; and the // set of function names DECLARED in each region. Both shadow the global fallback. $gp_use_fn = array(); $gp_local_fn = array(); // ACG-149-123 (round 23, R22-003): `use const A\F as G` -> G => F (LAST SEGMENT). Declared HERE, with the other // import maps, because the `use` pre-scan below FILLS it - declaring it further down with the constant maps // re-initialised it to empty after it had been filled, which silently lost every alias. $gp_uconst_alias = array(); $gp_uconst_ns = array(); // ACG-149-124: CONST-name => the namespace it was DECLARED in $gp_bstack = array(); $gp_await_cls = false; $gp_await_ns = false; // ACG-146-004: PHP's ALTERNATIVE syntax (`if ( ... ): ... endif;`) opens a block with NO brace, // so a declaration inside one looked top-level and suppressed detection. Counted separately. $gp_alt = 0; $gp_alt_pending = false; $gp_paren = 0; for ( $pi = 0; $pi < $n; $pi++ ) { $pt = $tok[ $pi ]; if ( is_int( $pt[0] ) && ( T_CLASS === $pt[0] || T_TRAIT === $pt[0] || T_INTERFACE === $pt[0] || ( defined( 'T_ENUM' ) && T_ENUM === $pt[0] ) ) ) { $gp_await_cls = true; continue; } // ACG-146-003: a `namespace X { }` brace is NOT an ordinary block - a declaration directly // inside it is still top-level. Marked 3 so the two can be told apart below. if ( is_int( $pt[0] ) && T_NAMESPACE === $pt[0] ) { $gp_await_ns = true; continue; } // alternative-syntax bookkeeping if ( is_int( $pt[0] ) && ( T_IF === $pt[0] || T_ELSEIF === $pt[0] || T_WHILE === $pt[0] || T_FOR === $pt[0] || T_FOREACH === $pt[0] || T_SWITCH === $pt[0] ) ) { $gp_alt_pending = true; $gp_paren = 0; continue; } if ( is_int( $pt[0] ) && ( T_ELSE === $pt[0] || T_DECLARE === $pt[0] ) ) { $gp_alt_pending = true; continue; } if ( is_int( $pt[0] ) && ( T_ENDIF === $pt[0] || T_ENDWHILE === $pt[0] || T_ENDFOR === $pt[0] || T_ENDFOREACH === $pt[0] || T_ENDSWITCH === $pt[0] || T_ENDDECLARE === $pt[0] ) ) { if ( $gp_alt > 0 ) { $gp_alt--; } continue; } if ( $gp_alt_pending ) { if ( $is_char( $pt, '(' ) ) { $gp_paren++; } elseif ( $is_char( $pt, ')' ) ) { $gp_paren--; } elseif ( 0 === $gp_paren && $is_char( $pt, ':' ) ) { $gp_alt++; $gp_alt_pending = false; } elseif ( 0 === $gp_paren && ( $is_char( $pt, '{' ) || $is_char( $pt, ';' ) ) ) { $gp_alt_pending = false; } } // ACG-146-003: an UNBRACED `namespace Foo;` ends at the semicolon. Without clearing the flag // here the next ordinary block - typically `if ( false ) {` - was marked as a namespace brace, // which re-opened the very evasion this rule closes. if ( $is_char( $pt, ';' ) ) { $gp_await_ns = false; continue; } if ( $is_char( $pt, '{' ) ) { $gp_bstack[] = $gp_await_ns ? 3 : ( $gp_await_cls ? 1 : 0 ); $gp_await_cls = false; $gp_await_ns = false; continue; } if ( is_int( $pt[0] ) && ( T_CURLY_OPEN === $pt[0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $pt[0] ) ) ) { $gp_bstack[] = 0; continue; } if ( $is_char( $pt, '}' ) ) { array_pop( $gp_bstack ); continue; } // ACG-146-001: a function DECLARED in this namespace shadows the global one. Only a // statement-level declaration counts: a method lives in a class body, and an anonymous // function has '(' where the name would be. if ( is_int( $pt[0] ) && T_FUNCTION === $pt[0] ) { $fn2 = $pi + 1; if ( $fn2 >= $n || ! is_int( $tok[ $fn2 ][0] ) || T_STRING !== $tok[ $fn2 ][0] ) { continue; } // ACG-146-003: TOP LEVEL only. Every open brace must belong to a `namespace X { }` block; // anything else means the declaration sits inside a class body, a function body, a closure // or a conditional, none of which reliably shadows the global function. $gp_top = ( 0 === $gp_alt ); foreach ( $gp_bstack as $gp_bs ) { if ( 3 !== (int) $gp_bs ) { $gp_top = false; break; } } if ( ! $gp_top ) { continue; } // ...and only inside a REAL namespace. Redeclaring a PHP built-in at global scope is a // fatal, so such a declaration is dead code and can only ever be an evasion attempt. $gp_frid = $gp_region_of( $pi ); $gp_fns = ( $gp_frid >= 0 && isset( $gp_regions[ $gp_frid ] ) ) ? $gp_regions[ $gp_frid ]['ns'] : ''; if ( '' === $gp_fns ) { continue; } $gp_local_fn[ $gp_frid ][ strtolower( (string) $tok[ $fn2 ][1] ) ] = 1; continue; } if ( ! ( is_int( $pt[0] ) && T_USE === $pt[0] ) ) { continue; } // Inside a CLASS-like body this is a TRAIT use, not an import. if ( ! empty( $gp_bstack ) && 1 === (int) end( $gp_bstack ) ) { continue; } $q = $pi + 1; if ( $q >= $n ) { break; } if ( $is_char( $tok[ $q ], '(' ) ) { continue; } // closure capture: function () use ($x) if ( ! is_int( $tok[ $q ][0] ) ) { continue; } // ACG-149-123 (round 23, R22-003): `use const A\F;` / `use const A\F as G;` / `use const A\{F as G};` // imports a CONSTANT - never a class and never a function. Record alias => imported LAST SEGMENT; the // aliases are applied once the const pre-scan has finished, because a `use` line may sit above OR below the // declaration it imports. A no-alias import needs no entry: the maps are keyed by the bare name already. if ( defined( 'T_CONST' ) && T_CONST === $tok[ $q ][0] ) { $gp_ucn = array( T_STRING ); foreach ( array( 'T_NAME_QUALIFIED', 'T_NAME_FULLY_QUALIFIED' ) as $gp_ucnn ) { if ( defined( $gp_ucnn ) ) { $gp_ucn[] = constant( $gp_ucnn ); } } $gp_ucskip = array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ); $gp_ucq = $q + 1; $gp_ucs = 0; $gp_ucgp = ''; while ( $gp_ucq < $n && $gp_ucs++ < 400 && ! $is_char( $tok[ $gp_ucq ], ';' ) && ! ( is_int( $tok[ $gp_ucq ][0] ) && T_CLOSE_TAG === $tok[ $gp_ucq ][0] ) && self::scan_budget_ok() ) { if ( ! is_int( $tok[ $gp_ucq ][0] ) || ! in_array( $tok[ $gp_ucq ][0], $gp_ucn, true ) ) { $gp_ucq++; continue; } $gp_ucnx = $gp_ucq + 1; while ( $gp_ucnx < $n && is_int( $tok[ $gp_ucnx ][0] ) && in_array( $tok[ $gp_ucnx ][0], $gp_ucskip, true ) ) { $gp_ucnx++; } // the GROUP PREFIX (the `A` of `use const A\{ … }`) is a name followed by a namespace separator, // not an import of its own. The members after the `{` are read by the next iterations. if ( $gp_ucnx < $n && is_int( $tok[ $gp_ucnx ][0] ) && defined( 'T_NS_SEPARATOR' ) && T_NS_SEPARATOR === $tok[ $gp_ucnx ][0] ) { $gp_ucgp = ltrim( rtrim( (string) $tok[ $gp_ucq ][1], chr( 92 ) ), chr( 92 ) ); // ACG-149-124: the group prefix $gp_ucq = $gp_ucnx + 1; continue; } $gp_ucfq = ltrim( (string) $tok[ $gp_ucq ][1], chr( 92 ) ); if ( '' !== $gp_ucgp && false === strpos( $gp_ucfq, chr( 92 ) ) ) { $gp_ucfq = $gp_ucgp . chr( 92 ) . $gp_ucfq; } $gp_ucsp = strrpos( $gp_ucfq, chr( 92 ) ); $gp_uctg = ( false !== $gp_ucsp ) ? substr( $gp_ucfq, $gp_ucsp + 1 ) : $gp_ucfq; $gp_ucpf = ( false !== $gp_ucsp ) ? substr( $gp_ucfq, 0, $gp_ucsp ) : ''; $gp_ucal = $gp_uctg; if ( $gp_ucnx < $n && is_int( $tok[ $gp_ucnx ][0] ) && T_AS === $tok[ $gp_ucnx ][0] ) { $gp_ucaz = $gp_ucnx + 1; while ( $gp_ucaz < $n && is_int( $tok[ $gp_ucaz ][0] ) && in_array( $tok[ $gp_ucaz ][0], $gp_ucskip, true ) ) { $gp_ucaz++; } if ( $gp_ucaz < $n && is_int( $tok[ $gp_ucaz ][0] ) && T_STRING === $tok[ $gp_ucaz ][0] ) { $gp_ucal = (string) $tok[ $gp_ucaz ][1]; $gp_ucq = $gp_ucaz; } } // ACG-149-124 (round 24, self-found FP): the import's NAMESPACE PREFIX travels with the alias. The // constant maps are name-flattened, so without it the alias binds to whatever same-named const the // file declares - in a different namespace, with a different value. $gp_ucpf was captured from the // NAME token above, before the `as` clause moved the cursor onto the alias. if ( '' !== $gp_ucal && '' !== $gp_uctg && $gp_ucal !== $gp_uctg ) { $gp_uconst_alias[ $gp_ucal ] = array( $gp_uctg, strtolower( $gp_ucpf ) ); } $gp_ucq++; } continue; } // ACG-146-001: `use function ...` is not a class alias, but it IS the thing that decides // whether a later unqualified call means the global function. It used to be skipped // outright, which is why `use function \system as run; run($_POST[..])` was invisible. if ( T_FUNCTION === $tok[ $q ][0] ) { $fq2 = $q + 1; // ACG-146-004: GROUP form `use function Foo\{ a, b as c };`. The class-import path has // had this expansion since ACG-143; the function path was written without it, so every // member of a group import was invisible. Same asymmetry, one round later. $gp_gk = $fq2; while ( $gp_gk < $n && $gp_gk < $fq2 + 3 && ! $is_char( $tok[ $gp_gk ], '{' ) && ! $is_char( $tok[ $gp_gk ], ';' ) ) { $gp_gk++; } if ( $gp_gk < $n && $is_char( $tok[ $gp_gk ], '{' ) && is_int( $tok[ $fq2 ][0] ) ) { $gp_gpfx = rtrim( ltrim( (string) $tok[ $fq2 ][1], chr( 92 ) ), chr( 92 ) ); $gp_gr = $gp_gk + 1; while ( $gp_gr < $n && ! $is_char( $tok[ $gp_gr ], '}' ) && self::scan_budget_ok() ) { if ( is_int( $tok[ $gp_gr ][0] ) && ( T_STRING === $tok[ $gp_gr ][0] || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $gp_gr ][0] ) ) ) { $gp_gsub = ltrim( (string) $tok[ $gp_gr ][1], chr( 92 ) ); $gp_gal = $gp_gsub; $gp_gsp = strrpos( $gp_gal, chr( 92 ) ); if ( false !== $gp_gsp ) { $gp_gal = substr( $gp_gal, $gp_gsp + 1 ); } if ( $gp_gr + 2 < $n && is_int( $tok[ $gp_gr + 1 ][0] ) && T_AS === $tok[ $gp_gr + 1 ][0] && is_int( $tok[ $gp_gr + 2 ][0] ) ) { $gp_gal = (string) $tok[ $gp_gr + 2 ][1]; $gp_gr += 2; } $gp_gfq = ( '' !== $gp_gpfx ) ? ( $gp_gpfx . chr( 92 ) . $gp_gsub ) : $gp_gsub; $gp_use_fn[ $gp_region_of( $pi ) ][ strtolower( $gp_gal ) ] = strtolower( $gp_gfq ); } $gp_gr++; } continue; } if ( $fq2 < $n && is_int( $tok[ $fq2 ][0] ) ) { $gp_ffq = ltrim( (string) $tok[ $fq2 ][1], chr( 92 ) ); if ( '' !== $gp_ffq ) { $gp_fal = $gp_ffq; $gp_fsp = strrpos( $gp_fal, chr( 92 ) ); if ( false !== $gp_fsp ) { $gp_fal = substr( $gp_fal, $gp_fsp + 1 ); } if ( $fq2 + 2 < $n && is_int( $tok[ $fq2 + 1 ][0] ) && T_AS === $tok[ $fq2 + 1 ][0] && is_int( $tok[ $fq2 + 2 ][0] ) ) { $gp_fal = (string) $tok[ $fq2 + 2 ][1]; } $gp_use_fn[ $gp_region_of( $pi ) ][ strtolower( $gp_fal ) ] = strtolower( $gp_ffq ); } } continue; } $gp_rid = $gp_region_of( $pi ); $gp_pfx = ltrim( (string) $tok[ $q ][1], chr( 92 ) ); if ( '' === $gp_pfx ) { continue; } // GROUP use: use Foo\{ A, B as C }; ACG-149-101 (round 11, R10-001): the prefix `Foo\` tokenises as the // name token (`Foo` / `Foo\Bar`) followed by a LONE T_NS_SEPARATOR, then `{` - so the brace is at $q+2, not // $q+1. The old check looked only at $q+1 (the `\`), so EVERY group class-import (`use A\{C as D}`) was // invisible. Skip the trailing separator before testing for `{`. $gp_bpos = $q + 1; if ( $gp_bpos < $n && is_int( $tok[ $gp_bpos ][0] ) && T_NS_SEPARATOR === $tok[ $gp_bpos ][0] ) { $gp_bpos++; } if ( $gp_bpos < $n && $is_char( $tok[ $gp_bpos ], '{' ) ) { $r = $gp_bpos + 1; while ( $r < $n && ! $is_char( $tok[ $r ], '}' ) && self::scan_budget_ok() ) { if ( is_int( $tok[ $r ][0] ) && ( T_STRING === $tok[ $r ][0] || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $r ][0] ) ) ) { $sub = ltrim( (string) $tok[ $r ][1], chr( 92 ) ); $al = $sub; $sp = strrpos( $al, chr( 92 ) ); if ( false !== $sp ) { $al = substr( $al, $sp + 1 ); } if ( $r + 2 < $n && is_int( $tok[ $r + 1 ][0] ) && T_AS === $tok[ $r + 1 ][0] && is_int( $tok[ $r + 2 ][0] ) ) { $al = (string) $tok[ $r + 2 ][1]; $r += 2; } $gp_use[ $gp_rid ][ strtolower( $al ) ] = strtolower( rtrim( $gp_pfx, chr( 92 ) ) . chr( 92 ) . $sub ); } $r++; } continue; } $alias = $gp_pfx; $seg = strrpos( $alias, chr( 92 ) ); if ( false !== $seg ) { $alias = substr( $alias, $seg + 1 ); } if ( $q + 2 < $n && is_int( $tok[ $q + 1 ][0] ) && T_AS === $tok[ $q + 1 ][0] && is_int( $tok[ $q + 2 ][0] ) ) { $alias = (string) $tok[ $q + 2 ][1]; } $gp_use[ $gp_rid ][ strtolower( $alias ) ] = strtolower( $gp_pfx ); } /** * Does the class-name token at $idx refer to the PHP GLOBAL class $want? * Fully qualified \Closure -> yes when it equals $want * Relative namespace\Closure -> current namespace + the rest * Qualified Opis\Closure -> never (namespace-relative) * Unqualified Closure -> its REGION's import, else global only outside a namespace */ $class_is_global = static function ( $text, $want, $idx ) use ( &$gp_regions, &$gp_use, &$gp_region_of ) { $t = trim( (string) $text ); if ( '' === $t ) { return false; } $want = strtolower( $want ); $rid = $gp_region_of( $idx ); $ns = ( $rid >= 0 && isset( $gp_regions[ $rid ] ) ) ? $gp_regions[ $rid ]['ns'] : ''; $lt = strtolower( $t ); $sep = chr( 92 ); if ( 0 === strpos( $lt, 'namespace' . $sep ) ) { // the `namespace\X` OPERATOR return '' === $ns && substr( $lt, 10 ) === $want; } if ( $sep === $t[0] ) { return ltrim( $lt, $sep ) === $want; } if ( false !== strpos( $lt, $sep ) ) { return false; } if ( isset( $gp_use[ $rid ][ $lt ] ) ) { return $gp_use[ $rid ][ $lt ] === $want; } if ( '' !== $ns ) { return false; } return $lt === $want; }; // ===== param-forwarding pre-pass ===== // function f(...,$cb,...){ ... $cb(...) ... } forwards a request-controlled callback when CALLED with // request data in $cb's position. Record lower(fn-name) => set of forwarding parameter indices. $fwd = array(); for ( $i = 0; $i + 2 < $n; $i++ ) { if ( ! ( is_int( $tok[ $i ][0] ) && T_FUNCTION === $tok[ $i ][0] ) ) { continue; } $j = $i + 1; $fname = ( $j < $n && is_int( $tok[ $j ][0] ) && T_STRING === $tok[ $j ][0] ) ? strtolower( $tok[ $j ][1] ) : ''; if ( '' === $fname ) { continue; } // anonymous closures are not tracked here while ( $j < $n && ! $is_char( $tok[ $j ], '(' ) && self::scan_budget_ok() ) { $j++; } if ( $j >= $n ) { continue; } $params = array(); $pi = 0; $d = 1; $j++; for ( ; $j < $n && $d > 0 && self::scan_budget_ok(); $j++ ) { $x = $tok[ $j ]; if ( $is_char( $x, '(' ) ) { $d++; } elseif ( $is_char( $x, ')' ) ) { $d--; } elseif ( 1 === $d && $is_char( $x, ',' ) ) { $pi++; } elseif ( 1 === $d && is_int( $x[0] ) && T_VARIABLE === $x[0] && ! isset( $params[ $x[1] ] ) ) { $params[ $x[1] ] = $pi; } } while ( $j < $n && ! $is_char( $tok[ $j ], '{' ) && ! $is_char( $tok[ $j ], ';' ) && self::scan_budget_ok() ) { $j++; } if ( $j >= $n || ! $is_char( $tok[ $j ], '{' ) ) { continue; } $bd = 1; $j++; for ( ; $j < $n && $bd > 0 && self::scan_budget_ok(); $j++ ) { $x = $tok[ $j ]; if ( $is_char( $x, '{' ) ) { $bd++; } elseif ( $is_char( $x, '}' ) ) { $bd--; } elseif ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $params[ $x[1] ] ) && $j + 1 < $n && $is_char( $tok[ $j + 1 ], '(' ) ) { $fwd[ $fname ][ $params[ $x[1] ] ] = 1; } } } // ===== merged scope-aware taint + sink pass ===== // Taint is per SCOPE: the global scope plus each function/closure body. A function parameter is a FRESH // local. A clean reassignment KILLS taint only at the scope's BASE brace depth (an UNCONDITIONAL // statement); a reassignment inside a nested block (if/loop) does not kill (it may not run). $kw = array( 'if'=>1,'elseif'=>1,'while'=>1,'for'=>1,'foreach'=>1,'switch'=>1,'catch'=>1,'function'=>1,'fn'=>1,'array'=>1,'list'=>1,'isset'=>1,'unset'=>1,'empty'=>1,'return'=>1,'echo'=>1,'print'=>1,'and'=>1,'or'=>1,'xor'=>1,'match'=>1,'declare'=>1,'new'=>1,'clone'=>1,'throw'=>1,'yield'=>1,'instanceof'=>1,'exit'=>1,'die'=>1 ); // ACG-137-B3 (self-review round 2, 2026-07-17): the descriptor model (fixed|last|array_value| // option_key) that replaced this table has been REVERTED. It was not the blocker, and an // adversarial review of my own diff proved it shipped a mass FALSE POSITIVE on an everyday // WordPress idiom plus a usable EVASION, because my argument splitter mis-tracked PHP's // ASYMMETRIC tokens: `"a{$x}b"` opens with T_CURLY_OPEN (an array token) but closes with a // plain '}' char; `#[Attr]` opens with T_ATTRIBUTE and closes with ']'. Only the close was // counted, the depth counters went NEGATIVE, and every later argument merged into one range: // call_user_func("wp_{$type}_handler", $_POST['data']); -> CRITICAL MALWARE (false) // preg_replace_callback("/x{$p}/", $_POST['f'], $s); -> nothing at all (evasion) // The clean corpus could not gate it — it contains ZERO instances of these shapes, so the // before/after diff was byte-identical and proved nothing. Structurally modelling the callable // position (the u-family, preg_replace_callback_array, FILTER_CALLBACK, ob_start) is still the // right thing to do and is still unfixed; it needs its own round, with the modern idioms added // to the clean-vendor corpus FIRST so the rule can actually be gated. Shipping a red malware // alarm on legitimate code is worse than the coverage gap it would close. // callback-API name => 0-based index of the CALLABLE argument. $cb_apis = array( 'array_map'=>0,'call_user_func'=>0,'call_user_func_array'=>0,'register_shutdown_function'=>0,'register_tick_function'=>0,'forward_static_call'=>0,'forward_static_call_array'=>0,'set_error_handler'=>0,'set_exception_handler'=>0,'spl_autoload_register'=>0,'array_filter'=>1,'array_walk'=>1,'array_walk_recursive'=>1,'usort'=>1,'uasort'=>1,'uksort'=>1,'array_reduce'=>1,'preg_replace_callback'=>1,'iterator_apply'=>1 ); // ACG-105 fresh-eyes (2026-06-30): unconditionally-dangerous literal callables. When one of these // is the callable passed to a callback API (call_user_func/array_map/array_walk/register_shutdown_function/…) // together with request data, it is a confirmed request-driven backdoor — wrapping a command function in // call_user_func runs that command on the request value just the same. The command-execution family // (system/exec/shell_exec/passthru/popen/proc_open/pcntl_exec) was previously MISSING here, so the // callback-wrapped form escaped BOTH this detector and the bd_*_input signatures (which only match the // direct request-fed call). No legitimate plugin routes a request value into these functions, so this is // false-positive-free. $danger = array( 'extract'=>1,'parse_str'=>1,'assert'=>1,'eval'=>1,'create_function'=>1,'call_user_func'=>1,'call_user_func_array'=>1, 'system'=>1,'exec'=>1,'shell_exec'=>1,'passthru'=>1,'popen'=>1,'proc_open'=>1,'pcntl_exec'=>1 ); // ACG-106 fresh-eyes (2026-07-01): the command-execution family, for the DIRECT-call taint branch (sink 7). // The flat bd_* regexes only catch system($_GET[..]) with the superglobal as the literal first token, so a // single variable hop ($c=$_GET[..]; system($c)), a non-GET/POST superglobal ($_COOKIE/$_SERVER/$_ENV/$_FILES/ // $GLOBALS), concatenation (system("ping ".$_GET[..])), filter_input, or php://input all evaded detection. // This taint-aware branch mirrors the eval/assert branch (sink 3) for these commands. The VALUE is the // highest argument index that carries the command, so only command-bearing args are inspected (popen()'s // 2nd "mode" arg and system()/exec()'s by-ref output args are NOT commands → no false positive). pcntl_exec // is special: its 2nd argument is the ARGS array (e.g. pcntl_exec('/bin/sh', array('-c', ))), so // args 0 AND 1 are command-bearing. $shell_fns = array( 'system'=>0,'exec'=>0,'shell_exec'=>0,'passthru'=>0,'popen'=>0,'proc_open'=>0,'pcntl_exec'=>1 ); // ACG-149-085 (siege 18 #2): functions that FILL a by-reference output var from an input the taint tracker sees. // If the INPUT arg is request-derived, the OUTPUT var captures request data and must be tainted (the tracker // otherwise models only `$v = ` and never by-ref out-params, so `parse_str($_SERVER['QUERY_STRING'],$m)` / // `preg_match($re,$_SERVER['..'],$m)` left $m untainted). Value = array( in-arg-index, out-arg-index ) 0-based. // NOTE (self-review): preg_match/preg_match_all are DELIBERATELY excluded. Their $matches are request captures, // but the ubiquitous legit idiom is `preg_match("#^$rule#", $request_path, $m)` in a router/rewrite engine (WP // core's own class-wp.php), whose $m flows into query building and parse_str - tainting it cascaded to a CRITICAL // tk_extract_superglobal FALSE POSITIVE on WP core. parse_str/mb_parse_str fill a request KEY=>VALUE map directly, // a far narrower and clearer request source, so only those are modelled. (The preg_match-into-dispatch evasion is // a documented residual, like the interprocedural-param case.) $gp_byref_fns = array( 'parse_str'=>array(0,1), 'mb_parse_str'=>array(0,1) ); // ACG-140-002 (adversarial review of ACG-139-002, 2026-07-17): does a path literal NAME the // WP-VCD backdoor? Compares the final path SEGMENT, not a raw substring. `strpos` alone reported // `include(__DIR__.'/cache/wp-feed.php.html')` — an ordinary cache fragment — as CRITICAL malware // (a defect inherited from the old wpfeed_2 regex). Only an include whose target basename IS the // dropped backdoor matters; `wp-includes/feed.php` (real WordPress core) must never match. $names_backdoor = static function ( $s ) { // trim FIRST: a heredoc/nowdoc body arrives as "…/wp-feed.php\n", so an untrimmed basename // compare silently missed the heredoc form (caught by the adversarial pass). $s = strtolower( trim( str_replace( chr( 92 ), '/', (string) $s ) ) ); $p = strrpos( $s, '/' ); $b = ( false === $p ) ? $s : substr( $s, $p + 1 ); return ( 'wp-feed.php' === $b || 'wp-tmp.php' === $b ); }; // ACG-141-001 (reviewer 2, 2026-07-17): THE SINGLE DEFINITION of "does this literal name a dangerous // GLOBAL function?" — and the reason it exists is the reviewer's meta-point, which was correct: // fixing one shape at a time means the next shape ships. Three separate sites used to answer this // question with `isset( $danger[ $lit ] )` on a raw first literal, so every site independently missed: // call_user_func( "\\system", $_POST['a'] ); // \system IS system — a leading namespace // array_map( "\\system", $_POST['items'] ); // separator resolves to the global function // call_user_func( "sys" . "tem", $_POST['a'] ); // one name split across two literals // Normalisation lives HERE, once, and every consumer routes through it: the callback APIs, // Closure::fromCallable, and the PHP 8.1 first-class-callable form. $danger_name = static function ( $s ) use ( $danger ) { $s = ltrim( strtolower( trim( (string) $s ) ), '\\' ); return '' !== $s && isset( $danger[ $s ] ); }; // ACG-149-130 (FP round, self-found): the INVERSE question, and the one that decides whether a // dynamic callee is bounded — "can any dangerous name CONTAIN this literal?" A callee assembled // by concatenation necessarily contains every literal part of that concatenation as a substring, // so if no dangerous name contains the literal, the callee can never BE a dangerous name, no // matter what the attacker supplies for the rest. That is a proof, not a heuristic: // $fn = "su_ajax_" . sanitize_key( $_POST['act'] ); // can never be system/exec/eval/... // $fn = "sys" . $_POST['f']; // CAN be system → stays malware // $fn = $_POST['f'] . "tem"; // CAN be system → stays malware // Position is deliberately NOT modelled: substring containment is weaker than prefix/suffix // matching, so this bounds strictly fewer callees than a positional test would. Weaker in the // safe direction is the whole point — an over-eager bound is a false negative. $gp_lit_bounds = static function ( $s ) use ( $danger ) { $s = strtolower( (string) $s ); if ( '' === $s ) { return false; } // "" . $_POST['f'] bounds nothing foreach ( $danger as $gp_dnm => $gp_dv ) { if ( false !== strpos( (string) $gp_dnm, $s ) ) { return false; } } return true; }; /** * The lowercased GLOBAL function name being CALLED at token $idx, or '' when this is not a * global-function call position. ACG-145-001: recognising only T_STRING meant one leading * backslash bypassed the callback-API model, the shell-command model and extract/parse_str. */ $called_fn = static function ( $idx ) use ( &$tok, $n, $is_char, &$gp_regions, &$gp_region_of, &$gp_use_fn, &$gp_local_fn ) { if ( $idx < 0 || $idx >= $n ) { return ''; } $x = $tok[ $idx ]; if ( ! is_int( $x[0] ) ) { return ''; } if ( ! ( $idx + 1 < $n && $is_char( $tok[ $idx + 1 ], '(' ) ) ) { return ''; } // A method, a static call or a declaration is never a global function call. Token-based, // so `$pdo -> exec(` and `Foo :: exec(` with any whitespace are excluded too. if ( $idx > 0 && is_int( $tok[ $idx - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $idx - 1 ][0] || T_DOUBLE_COLON === $tok[ $idx - 1 ][0] || T_FUNCTION === $tok[ $idx - 1 ][0] || T_NEW === $tok[ $idx - 1 ][0] ) ) { return ''; } $t = (string) $x[1]; if ( T_STRING === $x[0] ) { // ACG-146-001: an unqualified FUNCTION name is the global one only after an import and a // local declaration have both been ruled out. v1.0.145 returned the bare name here, which // reported `namespace Foo; function system(){} system($_POST)` as CRITICAL malware and // missed `use function \system as run; run($_POST)` entirely. $lt = strtolower( $t ); $rid = $gp_region_of( $idx ); if ( isset( $gp_use_fn[ $rid ][ $lt ] ) ) { $fq = $gp_use_fn[ $rid ][ $lt ]; // An import of a NAMESPACED function (Safe\system) is not the global function. return ( false === strpos( $fq, chr( 92 ) ) ) ? $fq : ''; } if ( isset( $gp_local_fn[ $rid ][ $lt ] ) ) { return ''; } return $lt; // global fallback } if ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) { return strtolower( ltrim( $t, chr( 92 ) ) ); } if ( defined( 'T_NAME_RELATIVE' ) && T_NAME_RELATIVE === $x[0] ) { $rid = $gp_region_of( $idx ); $ns = ( $rid >= 0 && isset( $gp_regions[ $rid ] ) ) ? $gp_regions[ $rid ]['ns'] : ''; return '' === $ns ? strtolower( substr( $t, 10 ) ) : ''; } return ''; // Foo\\f is namespaced, not global }; // ACG-141-004 (adversarial review): the previous fix normalised the callable NAME but still matched // the SHAPE at fixed token offsets, so a single wrapping paren or a rebinding call walked straight // past it. These two helpers make invocation detection POSITIONAL-INDEPENDENT. // // How many pure GROUPING parens immediately precede $start? A '(' is grouping only when the token // before it is not a name/variable/closer — otherwise it opens a CALL's argument list and its ')' // must not be skipped (that would let `foo()(...)` be misread as invoking ). $wrap_before = static function ( $start ) use ( &$tok, $is_char ) { $w = 0; $p = $start - 1; while ( $p >= 0 && $is_char( $tok[ $p ], '(' ) ) { $b = $p - 1; // ACG-141-005 (adversarial review): the break-list must name EVERY token that can precede a // CALL's argument list, or that call's ')' is misread as a grouping paren and the caller's // return-value invocation is attributed to this expression. On PHP 8 a qualified callee is // T_NAME_FULLY_QUALIFIED / T_NAME_QUALIFIED / T_NAME_RELATIVE (NOT T_STRING), and // `$o->{'m'}(` ends in '}' — so ` oo( Closure::fromCallable('system') )( $_POST['a'] )` // reported CRITICAL malware while the unqualified `foo(...)` form was correctly clean: the // scanner contradicted itself on the same code. Language constructs that take a // parenthesised operand are listed for the same reason. // ACG-141-006: T_EXIT / T_PRINT REMOVED - they take an EXPRESSION, so the parens in // `print ( )( ... )` really are grouping and the call executes; listing them was a // false negative, the same reasoning that correctly keeps require/include off the list. // T_CONSTANT_ENCAPSED_STRING ADDED - `'foo'( ... )( ... )` is valid string-literal invocation, // so that paren opens a CALL's argument list, not a grouping. $gp_bk = array( T_STRING, T_VARIABLE, T_ARRAY, T_ISSET, T_EMPTY, T_EVAL, T_UNSET, T_LIST, T_CONSTANT_ENCAPSED_STRING ); foreach ( array( 'T_NAME_FULLY_QUALIFIED', 'T_NAME_QUALIFIED', 'T_NAME_RELATIVE' ) as $gp_nm ) { if ( defined( $gp_nm ) ) { $gp_bk[] = constant( $gp_nm ); } } $gp_brk = false; if ( $b >= 0 ) { if ( is_int( $tok[ $b ][0] ) && in_array( $tok[ $b ][0], $gp_bk, true ) ) { $gp_brk = true; } elseif ( $is_char( $tok[ $b ], ')' ) || $is_char( $tok[ $b ], ']' ) || $is_char( $tok[ $b ], '"' ) ) { $gp_brk = true; } elseif ( $is_char( $tok[ $b ], '}' ) ) { // ACG-141-006: a '}' is a CALLEE only when it closes a NAME expression - // `$o->{'m'}(`, `Foo::{'b'}(`, `${'x'}(`. Breaking on EVERY '}' meant one brace // belonging to the PREVIOUS statement (`if (1) {}`, `function zz(){}`) collapsed the // wrap count to zero and restored the exact bypass this helper was written to close - // and an attacker fully controls that brace. Match back to the '{' and inspect what // introduced it. $gp_q = $b; $gp_bd = 0; while ( $gp_q >= 0 ) { if ( $is_char( $tok[ $gp_q ], '}' ) ) { $gp_bd++; } elseif ( $is_char( $tok[ $gp_q ], '{' ) ) { $gp_bd--; if ( 0 === $gp_bd ) { break; } } $gp_q--; } if ( $gp_q > 0 ) { $gp_pre = $tok[ $gp_q - 1 ]; if ( ( is_int( $gp_pre[0] ) && ( T_OBJECT_OPERATOR === $gp_pre[0] || T_DOUBLE_COLON === $gp_pre[0] ) ) || $is_char( $gp_pre, '$' ) ) { $gp_brk = true; } } } } if ( $gp_brk ) { break; } $w++; $p--; } return $w; }; // Where do the INVOCATION arguments of a callable-producing expression begin? Returns 0 if it is // never invoked. Skips the grouping parens counted above, and follows a ->bindTo()/->bind() chain // because those RETURN a Closure — `fromCallable('system')->bindTo(null)($_POST['a'])` executes. $invocation_args = static function ( $end, $wrap ) use ( &$tok, $n, $is_char ) { $p = $end + 1; while ( $wrap > 0 && $p < $n && $is_char( $tok[ $p ], ')' ) ) { $p++; $wrap--; } $guard = 0; while ( $p < $n && $guard++ < 20 ) { if ( $is_char( $tok[ $p ], '(' ) ) { return $p + 1; } if ( $p + 2 < $n && is_int( $tok[ $p ][0] ) && T_OBJECT_OPERATOR === $tok[ $p ][0] && is_int( $tok[ $p + 1 ][0] ) && T_STRING === $tok[ $p + 1 ][0] && $is_char( $tok[ $p + 2 ], '(' ) ) { $m = strtolower( $tok[ $p + 1 ][1] ); if ( in_array( $m, array( '__invoke', 'call', 'invoke', 'invokeargs' ), true ) ) { return $p + 3; } // ACG-143-002: getClosure() RETURNS a Closure for the same function, so it is a chain // link exactly like bindTo() - `(new \ReflectionFunction('system'))->getClosure()(...)`. if ( in_array( $m, array( 'bindto', 'bind', 'getclosure' ), true ) ) { $q = $p + 3; $d2 = 1; while ( $q < $n && $d2 > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $q ], '(' ) ) { $d2++; } elseif ( $is_char( $tok[ $q ], ')' ) ) { $d2--; } $q++; } $p = $q; continue; } } return 0; } return 0; }; // ACG-143-003 (reviewer 2): `$f = "system"; $f($_POST['a']);` is the SIMPLEST form of the whole // family and it was still only a review item, while the exotic factory forms had been closed. The // reviewer's point is exact: you cannot detect Closure::fromCallable("system")(...) as malware and // leave the plain string version as "review". Returns the fused, normalised literal name when a // token range is nothing but string literals joined by '.', else ''. $literal_name_at = static function ( $start ) use ( &$tok, $n, $is_char, $decode ) { $k = $start; $steps = 0; // ACG-143-004: tolerate redundant grouping parens. `$f = ( 'system' );` is identical in // meaning to `$f = 'system';`, and one paren used to defeat the whole rule. $paren = 0; while ( $k < $n && $steps++ < 8 && $is_char( $tok[ $k ], '(' ) ) { $paren++; $k++; } $name = ''; $want_lit = true; for ( ; $k < $n && $steps++ < 200; $k++ ) { $x = $tok[ $k ]; if ( $want_lit ) { if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $name .= trim( $decode( $x[1] ) ); $want_lit = false; continue; } return ''; // anything else -> not a pure literal } if ( $is_char( $x, '.' ) ) { $want_lit = true; continue; } break; // run finished } if ( $want_lit || '' === $name ) { return ''; } // a trailing '.' means it was not pure while ( $paren > 0 && $k < $n && $is_char( $tok[ $k ], ')' ) ) { $paren--; $k++; } if ( $paren > 0 ) { return ''; } // unbalanced -> not a plain value // ACG-143-004 (adversarial review, 2026-07-19): THE RUN MUST BE THE WHOLE VALUE. // The previous version returned the accumulated name on ANY trailing token, so any // expression merely STARTING with a dangerous literal was treated as `$v = `: // $cb = 'exec' === $mode ? 'gp_a' : 'gp_b'; // Yoda comparisons are the WordPress Coding Standards house style, so this reported // idiomatic plugin code as CRITICAL malware -- and it overrode the bounded-callable // guard even when both branches were array( $this, 'method' ). Requiring a real value // terminator is what makes "this literal IS the assigned value" a sound claim. if ( $k >= $n ) { return $name; } $t = $tok[ $k ]; if ( $is_char( $t, ';' ) || $is_char( $t, ',' ) || $is_char( $t, ')' ) || $is_char( $t, ']' ) ) { return $name; } if ( is_int( $t[0] ) && T_CLOSE_TAG === $t[0] ) { return $name; } return ''; }; // ACG-147-001 (P1): the shared operand resolver. See the axis note above $literal_name_at. // Pure transforms whose output is decidable from a literal argument. Real webshells assemble // callable names this way; each is a total function of its input, so folding is sound. // ACG-149-128 (round 24e, R24D-001): hex2bin was listed in the OBFUSCATION detector's decoder set at two other // sites but never here, in the table the shared NAME resolver uses - so `hex2bin("73797374656d")`, which is // simply "system", resolved to nothing. One table, every consumer. $gp_xform = array( 'strrev' => 1, 'strtolower' => 1, 'strtoupper' => 1, 'ucfirst' => 1, 'lcfirst' => 1, 'trim' => 1, 'base64_decode' => 1, 'str_rot13' => 1, 'hex2bin' => 1 ); $gp_apply_xform = static function ( $fn, $arg ) { switch ( $fn ) { case 'strrev': return strrev( $arg ); case 'strtolower': return strtolower( $arg ); case 'strtoupper': return strtoupper( $arg ); case 'ucfirst': return ucfirst( $arg ); case 'lcfirst': return lcfirst( $arg ); case 'trim': return trim( $arg ); case 'str_rot13': return str_rot13( $arg ); case 'base64_decode': $d = base64_decode( $arg, true ); return ( false === $d ) ? null : $d; case 'hex2bin': // hex2bin throws on odd length or non-hex input; a name we cannot decode is simply unknown. if ( '' === $arg || 0 !== strlen( $arg ) % 2 || ! ctype_xdigit( $arg ) ) { return null; } $h = @hex2bin( $arg ); return ( false === $h ) ? null : $h; } return null; }; // ACG-149-133 (round 27, R26-001..004) — THE PURE-LITERAL EVALUATOR, and it is an answer to the // reviewer's standing objection rather than another entry on a list. // // Rounds 24e and 26 each closed a batch of name builders by writing per-function semantics, and he is // right that this cannot terminate: `implode`, then `sprintf`, then `pack`, then `urldecode`, then // `strtr`, then `substr`... every round is one alternative away from the next. The MECHANISM was the // defect, not the list. // // So the LIST is now data and the MECHANISM is generic: for a call whose function is a PURE, // side-effect-free string function and whose every argument resolves to a LITERAL, the value is computed // by CALLING THE REAL PHP FUNCTION. That removes the whole class of modelling error - there is no // hand-written `%s` loop left to get wrong, so `sprintf("%1$s%1$s","a")`, `pack("A6",...)` and // `str_replace(["_"],"",...)` are simply correct - and adding a function becomes ONE TABLE ROW with no // new code, which the cross-product matrix then multiplies automatically. // // WHY CALLING IT IS SOUND: the function is pure, the arguments are literals taken from the file, and the // result is used only to ask "is this a dangerous NAME?". Nothing runs on the site's behalf. // // WHY IT IS SAFE TO CALL: every guard below exists so a hostile file cannot make the SCANNER the victim - // a bounded argument count, integer arguments bounded to +/-4096, every string argument and the result // bounded to 256 bytes (a function name is short, so the bound costs nothing), and the call wrapped so a // TypeError or a warning yields "unknown" instead of noise in the site's error log. // // ⚠ ACG-149-R39: THIS PARAGRAPH USED TO SAY preg_replace AND ITS FAMILY WERE DELIBERATELY EXCLUDED // as a DoS boundary (RES2701). THAT WAS TRUE IN ROUND 26 AND FALSE FROM ROUND 27 ONWARD — see the // preg_replace/preg_filter rows below, which admit them WITH bounds (128-byte pattern, 256-byte // subject, backtrack limit dropped to 10,000 around the call). The stale text survived directly // above the code that contradicts it, and in round 38 I read it, believed it, and told the owner I // was rejecting preg_split on a principled security ground that the code had abandoned two rounds // earlier. A comment is not evidence. Corrected here rather than left to mislead the next reader. // // value = array( min args, max args ). A function the table does not name is never evaluated. $gp_pure = array( // decoders and encoders 'base64_decode' => array( 1, 2 ), 'hex2bin' => array( 1, 1 ), 'urldecode' => array( 1, 1 ), 'rawurldecode' => array( 1, 1 ), 'html_entity_decode' => array( 1, 3 ), 'htmlspecialchars_decode' => array( 1, 2 ), 'str_rot13' => array( 1, 1 ), // ACG-149-134 (round 28, found by my own adversarial pass on the R27-004 fix): these are IDENTITY on // a bare function name - urlencode("system") IS "system" - and the crude literal run used to catch // them by accident. Poisoning that run turned the accident into a false negative, so they are PROVEN // here instead. Strictly better: `urlencode("sys tem")` is "sys+tem" and correctly not a name. 'urlencode' => array( 1, 1 ), 'rawurlencode' => array( 1, 1 ), 'htmlspecialchars' => array( 1, 4 ), 'htmlentities' => array( 1, 4 ), 'addslashes' => array( 1, 1 ), 'stripslashes' => array( 1, 1 ), 'quotemeta' => array( 1, 1 ), 'strip_tags' => array( 1, 2 ), 'basename' => array( 1, 2 ), // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R38 (external review ACG-101-PUB-001/003). Three rows, verified against the real // functions before being admitted — the reviewer's list was not accepted wholesale. // // stripcslashes: the exact sibling of `stripslashes` two rows above, which was already here. // stripcslashes("sys\x74em") === "system", confirmed on real WordPress: the file scanned // clean before this row and is malware after it. A genuine one-row gap. // // strtok: admitted ONLY in its TWO-argument form, and the arity range is what enforces that — // the same device used for array_filter's no-callback form. The ONE-argument form continues // a previous tokenisation from GLOBAL state, so its result depends on whatever ran before // it; that is not a pure literal transform and must never be evaluated here. // // str_getcsv: returns an ARRAY, which the constant-subscript support already indexes exactly // as it does for pathinfo/parse_url/json_decode. Same family, same code, no new machinery. 'stripcslashes' => array( 1, 1 ), 'strtok' => array( 2, 2 ), 'str_getcsv' => array( 1, 4 ), // ACG-149-135 (round 29, R28-001..005). Each of these is one row, which is what round 27's mechanism // change was for. array_filter is admitted ONLY in its NO-CALLBACK form - the arity range below is // what enforces that, so the boundary stays data rather than a special case. 'strval' => array( 1, 1 ), // ACG-149-R44: declared (1,4) until the new machine check compared the row against PHP's own // signature — filter_var takes THREE parameters. A four-argument call would have thrown // ArgumentCountError into the evaluator's catch and returned null: harmless, wrong, and // invisible for as long as a person rather than a machine was reading the table. 'filter_var' => array( 1, 3 ), // ACG-149-136 (R29-003/004): ONE argument is legal and returns an ARRAY - `pathinfo("system.php")` // and `parse_url("system")` - which the constant-subscript support then indexes, exactly as it // already did for json_decode. Same family, same code. 'pathinfo' => array( 1, 2 ), 'parse_url' => array( 1, 2 ), 'json_decode' => array( 1, 4 ), 'array_filter' => array( 1, 1 ), // ACG-149-136 (R29 optional list): one row each, which is the whole point of the mechanism. // var_export's second argument must be TRUE to return rather than print - the real function is // called, so a wrong second argument simply yields null and the name stays unknown. 'var_export' => array( 2, 2 ), 'sscanf' => array( 2, 2 ), 'array_keys' => array( 1, 3 ), 'array_flip' => array( 1, 1 ), 'array_combine' => array( 2, 2 ), 'str_word_count' => array( 2, 3 ), 'convert_uudecode' => array( 1, 1 ), 'quoted_printable_decode' => array( 1, 1 ), 'chr' => array( 1, 1 ), 'pack' => array( 2, 2 ), // case and trim 'strrev' => array( 1, 1 ), 'strtolower' => array( 1, 1 ), 'strtoupper' => array( 1, 1 ), 'ucfirst' => array( 1, 1 ), 'lcfirst' => array( 1, 1 ), 'ucwords' => array( 1, 2 ), 'trim' => array( 1, 2 ), 'ltrim' => array( 1, 2 ), 'rtrim' => array( 1, 2 ), // assembly and substitution 'implode' => array( 1, 2 ), 'join' => array( 1, 2 ), 'sprintf' => array( 1, 8 ), 'vsprintf' => array( 2, 2 ), 'str_replace' => array( 3, 3 ), 'str_ireplace' => array( 3, 3 ), 'strtr' => array( 2, 3 ), 'substr' => array( 2, 3 ), 'substr_replace' => array( 3, 4 ), 'str_pad' => array( 2, 4 ), 'str_repeat' => array( 2, 2 ), 'nl2br' => array( 1, 2 ), 'wordwrap' => array( 1, 4 ), 'strstr' => array( 2, 3 ), 'strrchr' => array( 2, 2 ), // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R39 (external review ACG-101-PUB-002/-003/-004). All three verified against the // real functions and against what the resolver already does, before being admitted. // // stristr: the case-insensitive twin of `strstr`, which was already one row above. NOTE the // reviewer's DIAGNOSIS for this one was wrong — he reported it as a case-NORMALISATION gap // ("the resolver does not lowercase the result"). Measured: strtoupper("system") through // the same resolver IS detected, and so is the bare literal "SYSTEM", so normalisation // already works. The symptom was real; the cause was simply that stristr was not in the // table. Fixing what he described would have changed code that is correct. // // array_key_first / array_column: array-literal builders, the same shape as `array_keys`, // which was already here and which I wrongly told the owner in round 38 needed machinery // the resolver did not have. array_keys(["system"=>1])[0] has always resolved. 'stristr' => array( 2, 3 ), 'array_key_first' => array( 1, 1 ), 'array_column' => array( 2, 3 ), // ACG-149-R40 (external review ACG-101-PUB38-001/-003/-004). Three more one-row siblings, // each verified against the real function first. array_key_last is array_key_first's twin; // chunk_split is a pure (string,int,string) transform in the same family as str_pad/substr; // dirname completes the path pair whose other half (basename) was already here, so the // chained basename(dirname("/tmp/system/file.php")) now resolves through existing machinery // rather than needing a special case for the chain. 'array_key_last' => array( 1, 1 ), 'chunk_split' => array( 1, 3 ), 'dirname' => array( 1, 2 ), // ═════════════════════════════════════════════════════════════════════════════════════════ // ACG-149-R40 — THE DECLARED BOUNDARY OF THIS TABLE. Read this before adding another row. // // This list is a CURATED SET, not a claim of completeness, and the difference is the whole // point. PHP ships hundreds of functions that can return a string from literal input; any // review that goes looking will always find another one, and rounds 38, 39 and 40 each // produced a fresh batch of "close siblings". That is not evidence of a defect — it is what // an unbounded space looks like. readme.txt has said since round 30 that this product aims // for "high-confidence detection with documented boundaries rather than a promise to catch // everything", and this table is where that promise is kept honest. // // ADMISSION TEST — a candidate belongs here only if ALL of these hold: // 1. PURE: same inputs, same output, no global or per-request state. // 2. LITERAL: every argument is resolvable from the source text alone. // 3. BOUNDED: input and result are capped, and it cannot execute or fetch anything. // 4. It is reached by the existing evaluator without new machinery. // // DECLARED RESIDUALS — deliberately OUT, with the reason, so they are a boundary and not an // oversight, and so the next reviewer gets an answer instead of a new round: // · STATEFUL ITERATION — key()/current()/next()/prev() after reset()/end() — is out of THIS // TABLE, because it reads a variable's internal array pointer rather than evaluating a // literal, and rule 1 excludes it. It is NOT out of the engine: $gp_arr_valret has modelled // the ordered key layout and the pointer since round 23, and answers for every one of them. // // ⚠ THE ROUND-40 WORDING OF THIS BULLET WAS A REAL DEFECT, not just an imprecision, and it // cost a release. It said the whole family was a declared residual — while current(), next() // and prev() had been detected for seventeen rounds. So it described THIS TABLE's boundary // in language that read as THE ENGINE's boundary, and round 38 then wrote a harness fixture // (MS4004a) pinning `["system"=>1]; reset($cb); call_user_func(key($cb), $_POST[...])` as // CLEAN — on the strength of the note rather than of any decision to leave a webshell // undetected. An external reviewer reported it as a live bypass in round 42 and was right: // key() was simply MISSING from $VR, and it was missing because this paragraph made its // absence look deliberate. A green test defended the gap; the gap outlived three reviews. // // Two rules come out of it. A boundary note must name the SUBSYSTEM it bounds — "outside // this table" and "outside this product" are different sentences. And a fixture that pins // an absence must cite the decision, never the note: if the only evidence that something is // residual is a comment, it is an oversight wearing a label. (ACG-101-PUB38-002 → R42-001.) // · unserialize() — it can instantiate objects and trigger __wakeup. Never evaluated here. // · preg_replace_callback and the /e family — they invoke code, not transform a string. // · anything whose argument comes from a superglobal, a constant defined elsewhere, a // property, or a function this table does not name. // // The FP budget is the reason for the discipline: every row is an evaluator that runs while // scanning a customer's site. Rounds 38-40 added ten rows for a measured cost of ZERO new // findings across a 12,705-file clean corpus and ~434,000 matrix cases — that is the bar a // new row has to clear, and "a reviewer found it" is not by itself a reason to add one. // ACG-149-133b: preg_replace IS included, with its own bounds. I excluded it first as a DoS surface // (the pattern comes from the scanned file), then bounded the exposure instead of leaving a gap: the // pattern is capped at 128 bytes, the subject at 256, and PCRE's backtrack limit is lowered to 10,000 // around the call, so a catastrophic pattern returns null in microseconds rather than hanging. 'preg_replace' => array( 3, 3 ), // ACG-149-134 (round 28, R27-002): preg_filter returns exactly what preg_replace returns WHEN IT // MATCHES, and null when it does not - so it needs the identical treatment and the identical bounds, // and the null case is already "undecidable" to the evaluator. 'preg_filter' => array( 3, 3 ), // ACG-149-R39 (external review ACG-101-PUB-001): preg_split is the same family and gets the // IDENTICAL bounds and the identical guarded call — it returns an ARRAY, which the constant // subscript support already indexes exactly as it does for explode/str_split/array_keys. I // rejected this in round 38 citing a DoS exclusion; measurement showed preg_replace and // preg_filter were already being evaluated, so the exposure was open and refusing the sibling // bought nothing. The reviewer's premise was right and mine was a stale code comment. 'preg_split' => array( 2, 4 ), 'preg_quote' => array( 1, 2 ), // ACG-149-134 (round 28, R27-003): pure builders that RETURN AN ARRAY, for the implode/join shapes. // These are as literal as the rest - `explode("_", "sys_tem")` has no runtime input at all. 'explode' => array( 2, 3 ), 'str_split' => array( 1, 2 ), 'array_reverse' => array( 1, 2 ), 'array_values' => array( 1, 1 ), 'array_slice' => array( 2, 4 ), 'array_unique' => array( 1, 2 ), // ACG-149-R43-001 (external review ACG-102-MS-001). Five more array builders of exactly the same // kind, reported as live bypasses and confirmed: `call_user_func(array_fill(0,1,"system")[0], $_POST[..])` // really is a webshell and really read clean. What decided this was not "a reviewer found it" — // rounds 38-40 established that alone is not a reason — it was MEASURING the neighbourhood. Of the // fourteen sibling builders probed, TWELVE already resolved (array_values, array_slice, array_unique, // array_keys, array_key_first, array_column, array_combine, array_reverse, json_decode, pathinfo, // str_split, explode). A set that answers for twelve of fourteen is not a boundary, it is an // omission with a boundary note attached, and rule 4 of the admission test is satisfied by // construction: they need no new machinery at all, only a row. 'array_fill' => array( 3, 3 ), 'array_pad' => array( 3, 3 ), 'array_chunk' => array( 2, 3 ), 'array_replace' => array( 2, 8 ), 'array_merge' => array( 1, 8 ), // ⚠⚠ array_map IS NOT AN ORDINARY ROW, AND THE NEXT PERSON MUST NOT TREAT IT AS ONE. ⚠⚠ // This table is evaluated by CALLING THE REAL PHP FUNCTION (round 27). array_map's first argument // is a CALLABLE, so a plain row would mean that scanning a file containing // array_map("system", ["rm -rf /"]) // makes THIS SCANNER run that command on the customer's server. A security product that executes // the malware it is inspecting is the worst defect available here, and it would have arrived // dressed as a one-line table addition. The reviewer asked for array_map and did not mention this. // It is admitted ONLY through the hard callback allowlist in $gp_pure_eval below — see there. // The same reasoning permanently excludes array_filter, array_walk, usort/uasort/uksort, // array_reduce, call_user_func(_array) and preg_replace_callback: every one of them takes code. 'array_map' => array( 2, 2 ), // ACG-149-R44 — THE LAST ENUMERATION. The reviewer named three more (array_search, // array_intersect, array_diff) and then said the honest thing: "if we fix these, more pure // builders can always be found; I would rather define a formal boundary than continue for // ever." He is right about the treadmill and wrong about where the boundary goes. The // treadmill exists because the set was being extended ONE NAME AT A TIME, by whoever looked // last. So the whole candidate space was enumerated ONCE, by reflection over PHP's own // function list, and everything that passes a MECHANICAL test is admitted here together. // That test is now enforced by _dev-harness/harness-pure-table.php, which fails the build if // any row in this table ever takes a callback, a by-reference parameter, or an untyped // variadic. The boundary stopped being a paragraph and became a gate. 'array_search' => array( 2, 3 ), // returns a KEY - the R42 axis, reached through the table 'array_intersect' => array( 2, 8 ), 'array_intersect_key' => array( 2, 8 ), 'array_intersect_assoc' => array( 2, 8 ), 'array_diff' => array( 2, 8 ), 'array_diff_key' => array( 2, 8 ), 'array_diff_assoc' => array( 2, 8 ), 'array_fill_keys' => array( 2, 2 ), 'array_count_values' => array( 1, 1 ), 'array_change_key_case' => array( 1, 2 ), 'array_merge_recursive' => array( 1, 8 ), 'array_replace_recursive' => array( 2, 8 ), // ⛔ THE SWEEP'S MOST IMPORTANT RESULT, and it was a defect in MY OWN mechanical test. // A first pass classified functions by "does a parameter have a callable type or a callback-ish // name". Under that rule ELEVEN functions came back ADMISSIBLE that must never be here: // array_udiff array_uintersect array_udiff_assoc array_udiff_uassoc // array_uintersect_assoc array_uintersect_uassoc array_diff_uassoc array_diff_ukey // array_intersect_uassoc array_intersect_ukey (and array_multisort by another route) // Every one of them takes a COMPARISON CALLBACK as its last argument — and PHP's reflection // reports that argument as an UNTYPED VARIADIC `...$rest`, so a type-based detector sees // nothing. Measured: array_udiff really does invoke it. Admitting them would have been the // array_map RCE eleven times over, arrived at by a rule that looked rigorous. // Hence the real rule: an UNTYPED VARIADIC is disqualifying on its own, because the signature // does not let us prove what the function will accept. Also excluded, for reasons the same // sweep surfaced: str_shuffle and array_rand are NON-DETERMINISTIC (measured: str_shuffle // returns a different string each call, so it breaks rule 1); compact() reads the caller's // variable scope; iterator_to_array takes an object; range() and preg_grep() would each need // their own bound, which is new machinery and rule 4 excludes it. ); // The NAMED-argument labels per function, so the SHARED splitter can map `separator:` / `format:` and the // rest. An unrecognised label makes the whole call undecidable rather than guessed. $gp_pure_named = array( 'implode' => array( 'separator', 'array' ), 'join' => array( 'separator', 'array' ), 'sprintf' => array( 'format' ), 'vsprintf' => array( 'format', 'values' ), 'pack' => array( 'format', 'values' ), 'str_replace' => array( 'search', 'replace', 'subject' ), 'str_ireplace' => array( 'search', 'replace', 'subject' ), 'strtr' => array( 'string', 'from', 'to' ), 'substr' => array( 'string', 'offset', 'length' ), 'substr_replace' => array( 'string', 'replace', 'offset', 'length' ), 'str_pad' => array( 'string', 'length', 'pad_string', 'pad_type' ), 'str_repeat' => array( 'string', 'times' ), 'chr' => array( 'codepoint' ), 'strval' => array( 'value' ), 'filter_var' => array( 'value', 'filter', 'options' ), 'pathinfo' => array( 'path', 'flags' ), 'parse_url' => array( 'url', 'component' ), 'json_decode' => array( 'json', 'associative', 'depth', 'flags' ), 'array_filter' => array( 'array' ), 'explode' => array( 'separator', 'string', 'limit' ), 'str_split' => array( 'string', 'length' ), 'array_reverse' => array( 'array', 'preserve_keys' ), // ACG-149-R43-001. array_replace/array_merge are variadic, so there is no useful named form. 'array_fill' => array( 'start_index', 'count', 'value' ), 'array_pad' => array( 'array', 'length', 'value' ), 'array_chunk' => array( 'array', 'length', 'preserve_keys' ), 'array_map' => array( 'callback', 'array' ), 'base64_decode' => array( 'string', 'strict' ), 'hex2bin' => array( 'string' ), 'urldecode' => array( 'string' ), 'rawurldecode' => array( 'string' ), 'html_entity_decode' => array( 'string', 'flags', 'encoding' ), 'htmlspecialchars_decode' => array( 'string', 'flags' ), 'strrev' => array( 'string' ), 'strtolower' => array( 'string' ), 'strtoupper' => array( 'string' ), 'ucfirst' => array( 'string' ), 'lcfirst' => array( 'string' ), 'trim' => array( 'string', 'characters' ), 'ltrim' => array( 'string', 'characters' ), 'rtrim' => array( 'string', 'characters' ), 'str_rot13' => array( 'string' ), ); /** * Evaluate ONE whitelisted pure call over already-resolved literal arguments. Returns the string value, * or null for "not decidable" - which is always the fail-clean direction. */ $gp_pure_eval = static function ( $fn, $args ) use ( $gp_pure ) { if ( ! isset( $gp_pure[ $fn ] ) || ! function_exists( $fn ) ) { return null; } $mn = $gp_pure[ $fn ][0]; $mx = $gp_pure[ $fn ][1]; $c = count( $args ); if ( $c < $mn || $c > $mx ) { return null; } // BOUNDS - so a hostile file cannot turn the scanner into the victim. $gp_bnd = null; $gp_bnd = static function ( $v ) use ( &$gp_bnd ) { if ( is_bool( $v ) || null === $v ) { return true; } // ACG-149-136: a flag argument is bounded by construction if ( is_int( $v ) ) { return ( $v >= -4096 && $v <= 4096 ); } if ( is_string( $v ) ) { return ( strlen( $v ) <= 256 ); } if ( is_array( $v ) ) { if ( count( $v ) > 32 ) { return false; } foreach ( $v as $gp_e ) { if ( ! $gp_bnd( $gp_e ) ) { return false; } } return true; } return false; }; foreach ( $args as $gp_a ) { if ( ! $gp_bnd( $gp_a ) ) { return null; } } // hex2bin throws and pack("H*") PADS on malformed input; an undecodable name is unknown, never guessed. if ( 'hex2bin' === $fn ) { $gp_h = (string) $args[0]; if ( '' === $gp_h || 0 !== strlen( $gp_h ) % 2 || ! ctype_xdigit( $gp_h ) ) { return null; } } if ( 'pack' === $fn ) { if ( ! is_string( $args[0] ) || ! preg_match( '/^(?:H\*|[AaZ][0-9]*)$/', $args[0] ) ) { return null; } if ( 'H*' === $args[0] ) { $gp_h = (string) $args[1]; if ( '' === $gp_h || 0 !== strlen( $gp_h ) % 2 || ! ctype_xdigit( $gp_h ) ) { return null; } } } // ACG-149-R39: preg_split runs the SAME guarded call with the SAME bounds. Its pattern also // comes from the scanned file, so it gets the 128-byte pattern cap, the 256-byte subject cap // and the lowered backtrack limit — a catastrophic pattern returns null in microseconds // instead of hanging the scan. It returns an array; every element must be a short string or // the whole result is undecidable, which keeps a huge split out of memory. if ( 'preg_split' === $fn ) { if ( ! is_string( $args[0] ) || ! is_string( $args[1] ) ) { return null; } if ( strlen( $args[0] ) > 128 || strlen( $args[1] ) > 256 ) { return null; } $gp_obt = ini_get( 'pcre.backtrack_limit' ); @ini_set( 'pcre.backtrack_limit', '10000' ); $gp_ps = null; try { set_error_handler( static function () { return true; } ); $gp_ps = @preg_split( $args[0], $args[1] ); restore_error_handler(); } catch ( \Throwable $gp_t ) { restore_error_handler(); } @ini_set( 'pcre.backtrack_limit', false === $gp_obt ? '1000000' : $gp_obt ); if ( ! is_array( $gp_ps ) || count( $gp_ps ) > 32 ) { return null; } foreach ( $gp_ps as $gp_pe ) { if ( ! is_string( $gp_pe ) || strlen( $gp_pe ) > 256 ) { return null; } } return $gp_ps; } if ( 'preg_replace' === $fn || 'preg_filter' === $fn ) { if ( ! is_string( $args[0] ) || ! is_string( $args[1] ) || ! is_string( $args[2] ) ) { return null; } if ( strlen( $args[0] ) > 128 || strlen( $args[2] ) > 256 ) { return null; } $gp_obt = ini_get( 'pcre.backtrack_limit' ); @ini_set( 'pcre.backtrack_limit', '10000' ); $gp_pr = null; try { set_error_handler( static function () { return true; } ); $gp_pr = ( 'preg_filter' === $fn ) ? @preg_filter( $args[0], $args[1], $args[2] ) : @preg_replace( $args[0], $args[1], $args[2] ); restore_error_handler(); } catch ( \Throwable $gp_t ) { restore_error_handler(); } @ini_set( 'pcre.backtrack_limit', false === $gp_obt ? '1000000' : $gp_obt ); if ( ! is_string( $gp_pr ) || '' === $gp_pr || strlen( $gp_pr ) > 256 ) { return null; } return $gp_pr; } // ACG-149-135 (R28-004): json_decode over a LITERAL. Bounded hard - a 256-byte subject and depth 8 - // and a result that is not a short string or a small array is simply undecidable. json_decode does not // execute anything (unlike unserialize, which is deliberately NOT here for that reason). if ( 'json_decode' === $fn ) { if ( ! is_string( $args[0] ) || strlen( $args[0] ) > 256 ) { return null; } $gp_jd = json_decode( $args[0], is_array( $args ) && isset( $args[1] ) ? (bool) $args[1] : null, 8 ); if ( JSON_ERROR_NONE !== json_last_error() ) { return null; } if ( is_string( $gp_jd ) ) { return ( '' === $gp_jd || strlen( $gp_jd ) > 256 ) ? null : $gp_jd; } if ( is_array( $gp_jd ) && count( $gp_jd ) <= 32 ) { foreach ( $gp_jd as $gp_je ) { if ( ! is_string( $gp_je ) || strlen( $gp_je ) > 256 ) { return null; } } return $gp_jd; } return null; } if ( 'base64_decode' === $fn ) { $gp_d = base64_decode( (string) $args[0], true ); // STRICT: reject non-base64 rather than guess return ( false === $gp_d || '' === $gp_d || strlen( $gp_d ) > 256 ) ? null : $gp_d; } // ───────────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R43-001 — array_map's CALLBACK IS CODE, AND THIS FUNCTION EXECUTES ITS TABLE. // // Everything below line "call_user_func_array( $fn, $args )" runs the REAL PHP function over // arguments taken from the file being scanned. For every other member of the table that is safe, // because the arguments are data. array_map's first argument is a CALLABLE, so without this gate // a file containing // array_map("system", ["rm -rf /"]) or array_map("eval", [$payload]) // would make the SCANNER execute it, as root-adjacent as whatever user PHP runs as, on a // customer's live site — turning a malware scanner into the delivery mechanism. Nothing else in // this file has that property, which is why the gate lives here and not in a shared bound. // // The callback must therefore be a LITERAL STRING drawn from this closed list. Every entry is a // pure value transform that cannot execute code, open a file, or reach the network; the list is // written out rather than derived from $gp_pure so that widening $gp_pure can never silently // widen what this evaluator is willing to CALL. A variable, an array callable, a closure, a // Closure::fromCallable, or null (array_map's zip form) all fail closed. if ( 'array_map' === $fn ) { $gp_map_cb = array( 'strval', 'trim', 'ltrim', 'rtrim', 'strtolower', 'strtoupper', 'ucfirst', 'lcfirst', 'strrev', 'str_rot13', 'urldecode', 'rawurldecode', 'stripslashes', 'stripcslashes', 'htmlspecialchars_decode', 'html_entity_decode', 'bin2hex' ); if ( ! is_string( $args[0] ) ) { return null; } $gp_cbn = ltrim( strtolower( trim( $args[0] ) ), chr( 92 ) ); if ( ! in_array( $gp_cbn, $gp_map_cb, true ) || ! function_exists( $gp_cbn ) ) { return null; } if ( ! isset( $args[1] ) || ! is_array( $args[1] ) || count( $args[1] ) > 32 ) { return null; } foreach ( $args[1] as $gp_me ) { if ( ! is_string( $gp_me ) ) { return null; } } $args = array( $gp_cbn, $args[1] ); // re-seat: only the vetted name is ever passed on } // ACG-149-R43-001: array_fill/array_pad take an attacker-chosen COUNT. $gp_bnd already caps an int // argument at 4096 and the RESULT at 32 elements, so an oversize call is rejected — but only after // it has been built. Cap the count first: nothing legitimate here needs more than a handful, and // "rejected after allocating" is a worse habit than "never allocated". if ( 'array_fill' === $fn || 'array_pad' === $fn ) { $gp_cnt = ( 'array_fill' === $fn ) ? $args[1] : $args[1]; if ( ! is_int( $gp_cnt ) || $gp_cnt > 64 || $gp_cnt < -64 ) { return null; } } $out = null; try { set_error_handler( static function () { return true; } ); // a warning must not reach the site's log $out = call_user_func_array( $fn, $args ); restore_error_handler(); } catch ( \Throwable $gp_t ) { restore_error_handler(); return null; } // ACG-149-134: an ARRAY result is legitimate for the array-returning members, and is bounded by the // same rule as an array argument. Everything else must still be a short non-empty string. if ( is_array( $out ) ) { return $gp_bnd( $out ) ? $out : null; } if ( ! is_string( $out ) || '' === $out || strlen( $out ) > 256 ) { return null; } return $out; }; $const_str = array(); // ACG-147-002 (P2): var-name => literal value $gp_arr_lit = array(); // ACG-149-048: var-name => 1 when assigned an ARRAY LITERAL (a fixed table) $gp_fc_arr = array(); // ACG-149-088: var-name => 1 when assigned the GLOBAL ["Closure","fromCallable"] ARRAY callable $gp_arr_danger = array(); // ACG-149-090 (reviewer round 3, MS-004): var-name => array(const-index => 1) when a // LITERAL array slot at a constant index holds a DANGEROUS global function name (`$cb=["system"]`) // ACG-149-091 (external reviewer ROUND 4, MS-002): user/class CONSTANTS that hold a dangerous callable name. // `const F="system"; (F)(..)`, `class C{const F="system";} call_user_func(C::F,..)`. Collected by the pre-scan // (order-independent) and resolved by $resolve_name, so EVERY factory path (fromCallable(C::F), RF(C::F)) and the // two callee sites see the value. $gp_uconst_int carries a numeric const for the MS-001 array-index resolver. $gp_uconst = array(); // CONST-name (case-sensitive) => resolved STRING value $gp_uconst_int = array(); // CONST-name => integer value (for `$cb[IDX]`) $gp_cconst = array(); // "classlower::CONST" => resolved STRING value // ACG-149-092 (external reviewer ROUND 5): a CONST/class-const whose VALUE is a literal ARRAY, subscripted // (`const CB=["system"]; (CB[0])(..)`, `class C{const CB=["system"];} call_user_func(C::CB[0],..)`). Stored as a // NESTED value map (a dangerous string leaf, or a nested map) so `$cb["a"]["b"]` and `CB[0]` descend uniformly. $gp_const_arr = array(); // CONST-name => nested danger-value map $gp_cconst_arr = array(); // "classlower::CONST" => nested danger-value map // ACG-149-115 (round 17, R16-002/003): the ORDERED LAYOUT and the INT value of a constant, so array_splice's // bounds and replacement can be resolved from a constant instead of only from a literal token. The engine already // resolved constants at a dozen other sites; the splice helper was written with its own narrow parser and so did // not benefit from any of them - the reviewer's point, and it is the same "route it through the ONE resolver" // lesson that was previously applied only to class-name parts. $gp_cconst_int = array(); // "classlower::CONST" => integer value // ACG-149-117 (round 18, R17-003): constants/class-constants whose value is NULL. `array_splice($a,$off,null)` // means "remove to the END", a documented spelling the round-17 int resolver did not know, so it retired. // Keyed 'c:NAME' for a global constant and 'k:classlower::NAME' for a class constant. $gp_isnull = array(); $gp_const_lay = array(); // CONST-name => ordered key layout of its array literal $gp_cconst_lay = array(); // "classlower::CONST" => ordered key layout // ACG-149-098 (external reviewer ROUND 10, R9-001): EVERY class const NAME defined, regardless of value or // danger. The inheritance post-pass must know a child DEFINED a const to let a child override win - but a SAFE // child value is stored in NEITHER $gp_cconst (only 'str' values) NOR $gp_cconst_arr (only DANGEROUS arrays), // so `class C extends P{const CB=["strlen"];}` looked undefined and wrongly inherited P's ["system"] (a // critical FP on legitimate code). This set records the override so it is never overwritten by an ancestor. $gp_cconst_defined = array(); // "classlower::CONST" => 1 (any const the class declares) // ACG-149-095 (external reviewer ROUND 8): the general $decode uses stripcslashes, which MANGLES a namespace // separator in a double-quoted class string (`"A\C"` -> "AC", losing the `\`). PHP keeps `\C` literal, so for // CLASS-NAME strings a decode that only unescapes `\\` / `\"` / `\'` matches PHP and preserves the separator. $gp_cdec = static function ( $lit ) { $lit = (string) $lit; if ( strlen( $lit ) < 2 ) { return ''; } $inner = substr( $lit, 1, -1 ); return ( false === strpos( $inner, chr( 92 ) ) ) ? $inner : str_replace( array( '\\\\', '\\"', "\\'" ), array( '\\', '"', "'" ), $inner ); // PERF: only unescape when a backslash is present }; $gp_var_cls = array(); // var-name => backslash-preserving CLASS-NAME string (`$cls="A\C"`) // ACG-149-093 (external reviewer ROUND 6, MS-001): lexical class context, so `self::F` / `static::F` / // `parent::F` resolve to the enclosing (or parent) class constant. The pre-scan fills [start, end, classlower, // parentlower]; $gp_class_at returns the innermost enclosing (class, parent) pair for a token position. $gp_class_ranges = array(); $gp_class_at = static function ( $pos ) use ( &$gp_class_ranges ) { $best = array( '', '' ); $best_start = -1; foreach ( $gp_class_ranges as $r ) { if ( $r[0] <= $pos && $pos <= $r[1] && $r[0] > $best_start ) { $best_start = $r[0]; $best = array( $r[2], $r[3] ); } } return $best; }; // ACG-149-093: map a class token (`C` / `self` / `static` / `parent`) at $pos to its class NAME (lowercased, // no leading '\'), using lexical context for the keywords. Returns '' when unknown (e.g. static:: with no class). $gp_class_ref = static function ( $tokval, $pos ) use ( &$gp_class_at ) { $lc = strtolower( ltrim( (string) $tokval, chr( 92 ) ) ); if ( 'self' === $lc || 'static' === $lc ) { $ctx = $gp_class_at( $pos ); return $ctx[0]; } if ( 'parent' === $lc ) { $ctx = $gp_class_at( $pos ); return $ctx[1]; } return $lc; }; // ACG-149-094 (external reviewer ROUND 7): resolve the CLASS PART of a `::CONST` access at $start to its // SHORT class name (lowercased). Handles a bareword (`C`), self/static/parent (lexical), a fully-qualified or // qualified name (`\A\C` / `A\C` -> last segment), a `use` alias (`D` -> its import), and a $var holding a // class-name string (`$cls="C"`). $gp_cconst is keyed by short name, so all spellings match. Returns [name,pos]. $gp_class_of = static function ( $start ) use ( &$tok, $n, &$gp_var_cls, &$gp_class_ref, &$gp_use, &$gp_region_of ) { if ( $start < 0 || $start >= $n ) { return array( '', $start ); } $t = $tok[ $start ]; if ( is_int( $t[0] ) && T_VARIABLE === $t[0] && isset( $gp_var_cls[ $t[1] ] ) ) { // ACG-149-095: raw (backslash-preserving) class-name string $parts = explode( chr( 92 ), strtolower( ltrim( (string) $gp_var_cls[ $t[1] ], chr( 92 ) ) ) ); return array( end( $parts ), $start + 1 ); } if ( is_int( $t[0] ) && defined( 'T_STATIC' ) && T_STATIC === $t[0] ) { return array( $gp_class_ref( $t[1], $start ), $start + 1 ); } if ( is_int( $t[0] ) && ( T_STRING === $t[0] || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $t[0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $t[0] ) ) ) { $lc = strtolower( ltrim( (string) $t[1], chr( 92 ) ) ); if ( 'self' === $lc || 'static' === $lc || 'parent' === $lc ) { return array( $gp_class_ref( $t[1], $start ), $start + 1 ); } $rid = $gp_region_of( $start ); if ( isset( $gp_use[ $rid ][ $lc ] ) ) { $lc = $gp_use[ $rid ][ $lc ]; } // use-alias -> imported FQN $parts = explode( chr( 92 ), $lc ); return array( end( $parts ), $start + 1 ); } return array( '', $start ); }; // ACG-149-095 (round 8): resolve a CLASS-NAME STRING operand (a string literal, a `"a"."b"` concat of literals, // or `X::class`) to a BACKSLASH-PRESERVING string, or '' if not statically a class-name string. Used to track // `$cls = "A\C"` and to read the argument of `constant("A\C::F")` without the stripcslashes mangling. $gp_cls_str = static function ( $start ) use ( &$tok, $n, $is_char, &$gp_cdec, &$gp_class_at, &$gp_class_of, &$gp_cconst ) { if ( $start < 0 || $start >= $n ) { return ''; } $k = $start; $val = ''; $want = true; $steps = 0; for ( ; $k < $n && $steps++ < 60; $k++ ) { $x = $tok[ $k ]; if ( $want ) { if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $val .= $gp_cdec( $x[1] ); $want = false; continue; } // ACG-149-096 (round 9): __CLASS__ / __NAMESPACE__ magic constants (compile-time). __CLASS__ -> the // enclosing class (short name, enough for the short-name lookup); __NAMESPACE__ -> '' (the following // `\C::...` still yields the short class name). So `constant(__CLASS__ . "::F")` resolves. if ( is_int( $x[0] ) && defined( 'T_CLASS_C' ) && T_CLASS_C === $x[0] ) { $gp_mc = $gp_class_at( $k ); $val .= $gp_mc[0]; $want = false; continue; } if ( is_int( $x[0] ) && defined( 'T_NS_C' ) && T_NS_C === $x[0] ) { $want = false; continue; } // __NAMESPACE__ -> '' (short-name lookup ignores the namespace) if ( is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_STATIC' ) && T_STATIC === $x[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $x[0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) ) && $k + 2 < $n && is_int( $tok[ $k + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $k + 1 ][0] && is_int( $tok[ $k + 2 ][0] ) && 'class' === strtolower( (string) $tok[ $k + 2 ][1] ) ) { // X::class // ACG-149-099/101 (round 10/11, R9-002/R10-002): resolve the class part through $gp_class_of, which // maps self/static -> enclosing, parent -> parent, a use ALIAS (incl. group `use A\{C as D}`) -> // the imported class, and a bareword / FQ -> its short name. `$cls = D::class` now yields the real // class, not the literal alias "D" (which matched nothing downstream). list( $gp_xcls, ) = $gp_class_of( $k ); if ( '' === $gp_xcls ) { return ''; } $val .= $gp_xcls; $want = false; $k += 2; continue; } // ACG-149-096 (round 9): a CLASS CONSTANT whose value is itself a class-name string - `$cls=C::NAME`. if ( is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_STATIC' ) && T_STATIC === $x[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $x[0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) ) && $k + 2 < $n && is_int( $tok[ $k + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $k + 1 ][0] && is_int( $tok[ $k + 2 ][0] ) && T_STRING === $tok[ $k + 2 ][0] && 'class' !== strtolower( (string) $tok[ $k + 2 ][1] ) ) { list( $gp_scls, $gp_scp ) = $gp_class_of( $k ); $gp_sck = $gp_scls . '::' . (string) $tok[ $k + 2 ][1]; if ( '' !== $gp_scls && isset( $gp_cconst[ $gp_sck ] ) ) { $val .= (string) $gp_cconst[ $gp_sck ]; $want = false; $k = $gp_scp + 1; continue; } return ''; } return ''; } if ( $is_char( $x, '.' ) ) { $want = true; continue; } break; } return $want ? '' : $val; }; // PHP array-key normalisation: a canonical decimal-integer STRING ("0","42") becomes an INT key, else a string. $gp_arrkey_norm = static function ( $s ) { $s = (string) $s; return ( '' !== $s && preg_match( '/^-?(?:0|[1-9][0-9]*)$/', $s ) ) ? (int) $s : $s; }; // ACG-149-092 (round 5): resolve ONE subscript key at $p to array( key|null, next_pos ). Handles an int literal, // a string literal (numeric-string normalised), a user CONSTANT (bareword) and a CLASS CONSTANT key `K::X`. $gp_key_at = static function ( $p ) use ( &$tok, $n, $decode, &$gp_arrkey_norm, &$gp_uconst, &$gp_uconst_int, &$gp_cconst, &$gp_class_of, &$const_str ) { if ( $p < 0 || $p >= $n ) { return array( null, $p ); } $t = $tok[ $p ]; if ( is_int( $t[0] ) && T_LNUMBER === $t[0] && ctype_digit( (string) $t[1] ) ) { return array( (int) $t[1], $p + 1 ); } if ( is_int( $t[0] ) && T_CONSTANT_ENCAPSED_STRING === $t[0] ) { return array( $gp_arrkey_norm( trim( $decode( $t[1] ) ) ), $p + 1 ); } if ( $p + 1 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] // PERF: gate on `::` before the class resolver && is_int( $t[0] ) && ( T_STRING === $t[0] || T_VARIABLE === $t[0] || ( defined( 'T_STATIC' ) && T_STATIC === $t[0] ) // ACG-149-093/094: self/static/parent/$cls/FQ::X key || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $t[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $t[0] ) ) ) { list( $gp_kcls, $gp_kcp ) = $gp_class_of( $p ); if ( '' !== $gp_kcls && $gp_kcp + 1 < $n && is_int( $tok[ $gp_kcp ][0] ) && T_DOUBLE_COLON === $tok[ $gp_kcp ][0] && is_int( $tok[ $gp_kcp + 1 ][0] ) && T_STRING === $tok[ $gp_kcp + 1 ][0] && 'class' !== strtolower( (string) $tok[ $gp_kcp + 1 ][1] ) ) { $ck = $gp_kcls . '::' . (string) $tok[ $gp_kcp + 1 ][1]; return array( isset( $gp_cconst[ $ck ] ) ? $gp_arrkey_norm( (string) $gp_cconst[ $ck ] ) : null, $gp_kcp + 2 ); } } if ( is_int( $t[0] ) && T_STRING === $t[0] ) { if ( isset( $gp_uconst_int[ (string) $t[1] ] ) ) { return array( (int) $gp_uconst_int[ (string) $t[1] ], $p + 1 ); } if ( isset( $gp_uconst[ (string) $t[1] ] ) ) { return array( $gp_arrkey_norm( (string) $gp_uconst[ (string) $t[1] ] ), $p + 1 ); } } // ACG-149-096 (round 9, R8-004): a VARIABLE key that holds a KNOWN constant STRING value - `$key=K::X; // $cb[$key]=..`. $const_str holds only fixed values (never request data), so this is a fixed key. if ( is_int( $t[0] ) && T_VARIABLE === $t[0] && isset( $const_str[ $t[1] ] ) && 'str' === $const_str[ $t[1] ][1] ) { return array( $gp_arrkey_norm( (string) $const_str[ $t[1] ][0] ), $p + 1 ); } return array( null, $p + 1 ); }; // ACG-149-092 (round 5): walk `[key][key]...` from $sub_start, descending a nested danger map. Returns // array( leaf|null, end_pos ): the STRING leaf when the whole chain lands on a dangerous name; null otherwise. $gp_arr_descend = static function ( $struct, $sub_start ) use ( &$tok, $n, $is_char, &$gp_key_at ) { $p = $sub_start; $node = $struct; $steps = 0; while ( $p < $n && $is_char( $tok[ $p ], '[' ) && $steps++ < 40 && self::scan_budget_ok() ) { if ( ! is_array( $node ) ) { return array( null, $p ); } list( $key, $after ) = $gp_key_at( $p + 1 ); if ( null === $key || $after >= $n || ! $is_char( $tok[ $after ], ']' ) ) { return array( null, $p ); } if ( ! array_key_exists( $key, $node ) ) { return array( null, $after + 1 ); } $node = $node[ $key ]; $p = $after + 1; } return array( ( is_string( $node ) ? $node : null ), $p ); }; /** * ACG-149-133: one element of an array literal, which may be a bare value or a `key => value` pair. * Returns array( ok, keyOrValue, valueOrNull ) - the third slot is null for a bare value. This is what * makes `strtr("sysXem", ["X" => "t"])` decidable, and it is why the map form did not need its own parser. */ $gp_pure_kv = null; $gp_pure_kv = static function ( $p, $depth ) use ( &$tok, $n, $is_char, &$gp_pure_arg ) { $d = 0; for ( $q = $p, $st = 0; $q < $n && $st < 200; $q++, $st++ ) { $t = $tok[ $q ]; if ( $is_char( $t, '(' ) || $is_char( $t, '[' ) ) { $d++; continue; } if ( $is_char( $t, ')' ) || $is_char( $t, ']' ) ) { $d--; if ( $d < 0 ) { break; } continue; } if ( 0 !== $d ) { continue; } if ( $is_char( $t, ',' ) || $is_char( $t, ';' ) ) { break; } if ( is_int( $t[0] ) && defined( 'T_DOUBLE_ARROW' ) && T_DOUBLE_ARROW === $t[0] ) { $kk = $gp_pure_arg( $p, $depth + 1 ); $vv = $gp_pure_arg( $q + 1, $depth + 1 ); if ( ! $kk[0] || ! $vv[0] ) { return array( false, null, null ); } if ( ! is_string( $kk[1] ) && ! is_int( $kk[1] ) ) { return array( false, null, null ); } return array( true, $kk[1], $vv[1] ); } } $bv = $gp_pure_arg( $p, $depth + 1 ); if ( ! $bv[0] ) { return array( false, null, null ); } return array( true, $bv[1], null ); }; /** * ACG-149-133: resolve ONE argument of a pure call to a literal PHP value. * * Returns array( ok, value ) where value is a string, an int, or a list of those. This exists because * $resolve_name answers "what NAME is this?" and a pure call also takes NUMBERS - `chr(115)`, * `substr($s, 2)`, `str_pad($s, 6, "tem")` - and ARRAYS, and a name resolver has no channel for either. * Everything it does not recognise is reported as not-ok, which makes the whole call undecidable. */ /** * ACG-149-139 (round 31, R30-001) — read a string ARGUMENT as EXACT BYTES. * * ONE FUNCTION WAS ANSWERING TWO QUESTIONS. The argument path used to end with * `$resolve_name( $q, ..., true )` and accept it only if it returned 'str'. But $resolve_name answers * "what CALLABLE NAME is this?", and to do that job it (a) requires the result to be name-shaped and * (b) TRIMS every literal it accumulates (line ~6121, and $literal_name_at likewise — added in round 30 * because a heredoc body token always ends in a newline). Both are right for a NAME and wrong for an * ARGUMENT, because `str_replace(" ", "", "sys tem")` is a perfectly ordinary call whose arguments are * neither name-shaped nor trimmable. * * That single confusion produced BOTH directions of error: * FALSE NEGATIVES (the reviewer's R30-001): any literal with INTERNAL whitespace was rejected, so * str_replace(" ", "", "sys tem") / ("\t") / ("\n") and the str_ireplace spelling all read clean. * FALSE POSITIVES (which the reviewer did not find, and which matter more here): a literal with * LEADING or TRAILING whitespace was silently TRIMMED, so the evaluator computed a value PHP never * produces. `substr(" systemX", 0, 6)` is " syste" in PHP — not callable, completely harmless — and * was reported as CONFIRMED MALWARE. Same for substr("Xsystem ", 1, 7) === "system ". * It also falsified round 30's stated boundary ("within the declared set the resolved name is EXACTLY * what PHP produces"): it was exactly what PHP produces AFTER trimming the inputs. * * NOTE ON THE REVIEWER'S DIAGNOSIS: he proposed "do not reject a whitespace-ONLY argument". That was * not the bug — a whitespace-only argument already worked (`str_replace(" ", "", "system")` fires, and * so does `trim(" system ")`). Fixing what he described would have changed working code and left both * defects in place. Verified before changing anything. * * So the two questions are separated: this reader returns the argument's bytes verbatim — no trim, no * name-shape test — for a literal or a concat run of literals. $resolve_name is left EXACTLY as it was * and stays the fallback for the exotic forms (constants, magic constants, class constants), so nothing * on the name axis moves. * * @return array{0:bool,1:?string} */ $gp_pure_str = static function ( $p ) use ( &$tok, $n, $is_char, $decode ) { $skip = array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ); $k = $p; $steps = 0; while ( $k < $n && is_int( $tok[ $k ][0] ) && in_array( $tok[ $k ][0], $skip, true ) ) { $k++; } // Tolerate redundant grouping parens, exactly as $literal_name_at does: `( "sys tem" )`. $paren = 0; while ( $k < $n && $steps++ < 8 && $is_char( $tok[ $k ], '(' ) ) { $paren++; $k++; } $val = ''; $want = true; $got = false; for ( ; $k < $n && $steps++ < 200; $k++ ) { $x = $tok[ $k ]; if ( is_int( $x[0] ) && in_array( $x[0], $skip, true ) ) { continue; } if ( $want ) { if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $val .= $decode( $x[1] ); // EXACT — the whole point of this reader $want = false; $got = true; // Bound the value like every other literal path (scanner-safety: 256 B). if ( strlen( $val ) > 256 ) { return array( false, null ); } continue; } return array( false, null ); // not a pure literal run } if ( $is_char( $x, '.' ) ) { $want = true; continue; } break; // run finished } if ( ! $got || $want ) { return array( false, null ); } // THE RUN MUST BE THE WHOLE ARGUMENT — the same discipline the nested-call path enforces above. // Without this, `"sys tem" ? "a" : "b"` or `"sys" + $x` would hand back a prefix as if it were the // whole value. Close any grouping parens we opened, then require an argument terminator. while ( $k < $n && is_int( $tok[ $k ][0] ) && in_array( $tok[ $k ][0], $skip, true ) ) { $k++; } while ( $paren > 0 && $k < $n && $is_char( $tok[ $k ], ')' ) ) { $paren--; $k++; while ( $k < $n && is_int( $tok[ $k ][0] ) && in_array( $tok[ $k ][0], $skip, true ) ) { $k++; } } if ( $paren > 0 ) { return array( false, null ); } if ( $k >= $n ) { return array( true, $val ); } if ( $is_char( $tok[ $k ], ',' ) || $is_char( $tok[ $k ], ')' ) || $is_char( $tok[ $k ], ']' ) || $is_char( $tok[ $k ], ';' ) ) { return array( true, $val ); } return array( false, null ); }; $gp_pure_arg = null; $gp_pure_arg = static function ( $p, $depth ) use ( &$tok, $n, $is_char, &$gp_mut_args, &$resolve_name, &$gp_pure_arg, &$gp_pure_kv, &$gp_pure, &$gp_pure_named, &$gp_pure_eval, &$gp_uconst_int, &$gp_uconst, &$gp_pure_str ) { if ( $depth > 4 || $p < 0 || $p >= $n ) { return array( false, null ); } $q = $p; while ( $q < $n && is_int( $tok[ $q ][0] ) && in_array( $tok[ $q ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $q++; } if ( $q >= $n ) { return array( false, null ); } // ACG-149-134 (round 28, R27-003): a NESTED PURE CALL. Evaluated by the SAME evaluator, so an array // returned by `explode(...)` reaches `implode(...)` with no per-shape code, and any future nesting // composes for free. This is the whole point of having made the mechanism generic in round 27. if ( is_int( $tok[ $q ][0] ) && ( T_STRING === $tok[ $q ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $q ][0] ) ) && $q + 1 < $n && $is_char( $tok[ $q + 1 ], '(' ) && isset( $gp_pure[ $gp_nn = ltrim( strtolower( (string) $tok[ $q ][1] ), chr( 92 ) ) ] ) && is_callable( $gp_mut_args ) && $depth < 4 ) { $gp_na = $gp_mut_args( $q, isset( $gp_pure_named[ $gp_nn ] ) ? $gp_pure_named[ $gp_nn ] : array() ); if ( null !== $gp_na && ! empty( $gp_na[3] ) && count( $gp_na[0] ) >= 1 && count( $gp_na[0] ) <= 8 ) { $gp_nargs = array(); $gp_nok = true; foreach ( $gp_na[0] as $gp_np ) { $gp_nv = $gp_pure_arg( $gp_np, $depth + 1 ); if ( ! $gp_nv[0] ) { $gp_nok = false; break; } $gp_nargs[] = $gp_nv[1]; } if ( $gp_nok ) { // ACG-149-135 (my own bug, found by my own test): THE CALL MUST BE THE WHOLE ARGUMENT. // Without this, `filter_var(chr(0x73) . "ystem", FILTER_DEFAULT)` evaluated only the // chr() and threw the `. "ystem"` away - the same "the run must BE the whole value" // discipline the string resolver has enforced since round 143. When it is not the whole // argument, fall through so $resolve_name handles the concatenation properly. $gp_nend = -1; for ( $gp_nz = $q + 1, $gp_nd2 = 0, $gp_ns = 0; $gp_nz < $n && $gp_ns < 400; $gp_nz++, $gp_ns++ ) { if ( $is_char( $tok[ $gp_nz ], '(' ) || $is_char( $tok[ $gp_nz ], '[' ) ) { $gp_nd2++; continue; } if ( $is_char( $tok[ $gp_nz ], ')' ) || $is_char( $tok[ $gp_nz ], ']' ) ) { $gp_nd2--; if ( 0 === $gp_nd2 ) { $gp_nend = $gp_nz; break; } } } $gp_nwhole = false; if ( $gp_nend > 0 ) { $gp_na2 = $gp_nend + 1; while ( $gp_na2 < $n && is_int( $tok[ $gp_na2 ][0] ) && in_array( $tok[ $gp_na2 ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_na2++; } $gp_nwhole = ( $gp_na2 >= $n ) || $is_char( $tok[ $gp_na2 ], ',' ) || $is_char( $tok[ $gp_na2 ], ')' ) || $is_char( $tok[ $gp_na2 ], ']' ) || $is_char( $tok[ $gp_na2 ], ';' ); } if ( $gp_nwhole ) { $gp_nres = $gp_pure_eval( $gp_nn, $gp_nargs ); if ( null !== $gp_nres ) { return array( true, $gp_nres ); } } } } // not decidable as a whole-argument pure call - fall through to the resolvers below rather // than declaring the argument unknown, so a CONCATENATION containing one still resolves. } // an ARRAY LITERAL, in either spelling. The SAME splitter reads `[` and `array(` as an argument list. $base = -1; if ( $is_char( $tok[ $q ], '[' ) && $q > 0 ) { $base = $q - 1; } elseif ( is_int( $tok[ $q ][0] ) && T_ARRAY === $tok[ $q ][0] ) { $base = $q; } if ( $base >= 0 && is_callable( $gp_mut_args ) ) { $lst = $gp_mut_args( $base, false ); if ( null === $lst || empty( $lst[3] ) || count( $lst[0] ) > 32 ) { return array( false, null ); } $out = array(); foreach ( $lst[0] as $sp ) { // an element may be `"k" => "v"`; $gp_mut_args hands back the VALUE start for that spelling // only when a label list was supplied, so a keyed element is read here as key => value. $kv = $gp_pure_kv( $sp, $depth ); if ( ! $kv[0] ) { return array( false, null ); } if ( null === $kv[2] ) { $out[] = $kv[1]; } else { $out[ $kv[1] ] = $kv[2]; } } return array( true, $out ); } // A NUMERIC literal, with an optional sign. Must be the WHOLE argument. // ACG-149-134 (round 28, R27-001): `0x73`, `0b1110011` and `0163` are all T_LNUMBER whose TEXT is // "0x73" / "0b1110011" / "0163", and a bare `(int)` cast reads those as 0 - which is exactly why the // hex, binary and octal spellings of one webshell scanned clean while the decimal spelling fired. // intval($text, 0) is PHP's own base-detecting conversion, so there is no second numeric model here. // A FLOAT (T_DNUMBER) is accepted when it is integral, matching chr()'s own coercion. $neg = false; $r = $q; if ( $is_char( $tok[ $r ], '-' ) ) { $neg = true; $r++; } elseif ( $is_char( $tok[ $r ], '+' ) ) { $r++; } while ( $r < $n && is_int( $tok[ $r ][0] ) && T_WHITESPACE === $tok[ $r ][0] ) { $r++; } $gp_isnum = ( $r < $n && is_int( $tok[ $r ][0] ) && ( T_LNUMBER === $tok[ $r ][0] || ( defined( 'T_DNUMBER' ) && T_DNUMBER === $tok[ $r ][0] ) ) ); if ( $gp_isnum ) { $after = $r + 1; while ( $after < $n && is_int( $tok[ $after ][0] ) && in_array( $tok[ $after ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $after++; } $ends = ( $after >= $n ) || $is_char( $tok[ $after ], ',' ) || $is_char( $tok[ $after ], ')' ) || $is_char( $tok[ $after ], ']' ) || $is_char( $tok[ $after ], ';' ); if ( $ends ) { $txt = (string) $tok[ $r ][1]; if ( defined( 'T_DNUMBER' ) && T_DNUMBER === $tok[ $r ][0] ) { $fv = (float) $txt; if ( $fv !== floor( $fv ) || abs( $fv ) > 1000000 ) { return array( false, null ); } $iv = (int) $fv; } else { $iv = intval( $txt, 0 ); // PHP's own 0x / 0b / 0 base detection } return array( true, $neg ? -$iv : $iv ); } } // ACG-149-136 (round 30, R29-004/005): the BOOLEAN and NULL literals. `true` / `false` / `null` are // T_STRING tokens, not a token type of their own, so the argument resolver rejected them - and that // single omission was the whole reason BOTH `json_decode('{"f":"system"}', true)["f"]` and // `var_export("system", true)` stayed clean. Their second argument IS the literal `true`. if ( is_int( $tok[ $q ][0] ) && T_STRING === $tok[ $q ][0] ) { $gp_ble = $q + 1; while ( $gp_ble < $n && is_int( $tok[ $gp_ble ][0] ) && in_array( $tok[ $gp_ble ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_ble++; } if ( ( $gp_ble >= $n ) || $is_char( $tok[ $gp_ble ], ',' ) || $is_char( $tok[ $gp_ble ], ')' ) || $is_char( $tok[ $gp_ble ], ']' ) || $is_char( $tok[ $gp_ble ], ';' ) ) { $gp_bl = strtolower( ltrim( (string) $tok[ $q ][1], chr( 92 ) ) ); if ( 'true' === $gp_bl ) { return array( true, true ); } if ( 'false' === $gp_bl ) { return array( true, false ); } if ( 'null' === $gp_bl ) { return array( true, null ); } } } // ACG-149-135 (round 29, R28-001/002/003): PHP'S OWN built-in constants. `FILTER_DEFAULT`, // `PATHINFO_FILENAME` and `PHP_URL_PATH` are the arguments that decide what filter_var / pathinfo / // parse_url return, and the resolver understood only integer literals and USER constants - which is // why `filter_var("system", FILTER_DEFAULT)` scanned clean. THE NAME LIST IS WRITTEN HERE, never taken // from the scanned file, so nothing an attacker writes can widen it; and because the real function is // then called with the real constant value, the answer is exact rather than modelled. if ( is_int( $tok[ $q ][0] ) && T_STRING === $tok[ $q ][0] ) { $gp_bce = $q + 1; while ( $gp_bce < $n && is_int( $tok[ $gp_bce ][0] ) && in_array( $tok[ $gp_bce ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_bce++; } if ( ( $gp_bce >= $n ) || $is_char( $tok[ $gp_bce ], ',' ) || $is_char( $tok[ $gp_bce ], ')' ) || $is_char( $tok[ $gp_bce ], ']' ) || $is_char( $tok[ $gp_bce ], ';' ) ) { $gp_bcn = strtoupper( ltrim( (string) $tok[ $q ][1], chr( 92 ) ) ); $gp_bcok = array( 'FILTER_DEFAULT' => 1, 'FILTER_UNSAFE_RAW' => 1, 'FILTER_SANITIZE_STRING' => 1, 'FILTER_SANITIZE_SPECIAL_CHARS' => 1, 'FILTER_SANITIZE_FULL_SPECIAL_CHARS' => 1, 'FILTER_SANITIZE_ENCODED' => 1, 'FILTER_SANITIZE_EMAIL' => 1, 'FILTER_SANITIZE_URL' => 1, 'FILTER_VALIDATE_REGEXP' => 1, 'FILTER_FLAG_NONE' => 1, 'PATHINFO_DIRNAME' => 1, 'PATHINFO_BASENAME' => 1, 'PATHINFO_EXTENSION' => 1, 'PATHINFO_FILENAME' => 1, 'PHP_URL_SCHEME' => 1, 'PHP_URL_HOST' => 1, 'PHP_URL_PORT' => 1, 'PHP_URL_USER' => 1, 'PHP_URL_PASS' => 1, 'PHP_URL_PATH' => 1, 'PHP_URL_QUERY' => 1, 'PHP_URL_FRAGMENT' => 1, 'JSON_OBJECT_AS_ARRAY' => 1, 'ENT_QUOTES' => 1, 'ENT_HTML5' => 1, 'ENT_COMPAT' => 1, 'STR_PAD_RIGHT' => 1, 'STR_PAD_LEFT' => 1, 'STR_PAD_BOTH' => 1, 'COUNT_NORMAL' => 1, ); if ( isset( $gp_bcok[ $gp_bcn ] ) && defined( $gp_bcn ) ) { $gp_bcv = constant( $gp_bcn ); if ( is_int( $gp_bcv ) ) { return array( true, $gp_bcv ); } } } } // ACG-149-134 (round 28, R27-001): a USER CONSTANT holding a number. `const S = 115; chr(S)` is 's', // and $gp_uconst_int already existed for exactly this - the argument resolver simply never asked it. // One map, every consumer; a numeric-STRING constant coerces the same way chr() itself would. if ( is_int( $tok[ $q ][0] ) && T_STRING === $tok[ $q ][0] ) { $gp_ce = $q + 1; while ( $gp_ce < $n && is_int( $tok[ $gp_ce ][0] ) && in_array( $tok[ $gp_ce ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_ce++; } $gp_cends = ( $gp_ce >= $n ) || $is_char( $tok[ $gp_ce ], ',' ) || $is_char( $tok[ $gp_ce ], ')' ) || $is_char( $tok[ $gp_ce ], ']' ) || $is_char( $tok[ $gp_ce ], ';' ); if ( $gp_cends ) { $gp_cn = (string) $tok[ $q ][1]; if ( isset( $gp_uconst_int[ $gp_cn ] ) ) { return array( true, (int) $gp_uconst_int[ $gp_cn ] ); } if ( isset( $gp_uconst[ $gp_cn ] ) && is_numeric( (string) $gp_uconst[ $gp_cn ] ) ) { return array( true, (int) $gp_uconst[ $gp_cn ] ); } } } // ACG-149-139 (round 31, R30-001): a plain string literal — or a concat run of them — is read as // EXACT BYTES first. This is the argument channel, so whitespace is data: " ", "\t", "sys tem" and // " systemX" must all arrive unmodified. See $gp_pure_str's header for the two-directional defect // this closes (internal whitespace rejected = FN; leading/trailing whitespace trimmed = FP). if ( is_callable( $gp_pure_str ) ) { $gp_sv = $gp_pure_str( $q ); if ( $gp_sv[0] ) { return array( true, (string) $gp_sv[1] ); } } // otherwise it must resolve as a STRING through the one shared resolver. `''` is a legitimate value // here (implode's glue, str_replace's replacement), so the CHANNEL decides, not the value. // Kept UNCHANGED as the fallback for the non-literal forms (constants, magic constants, class // constants), so the name axis and every earlier round's behaviour are untouched. $rr = $resolve_name( $q, $depth + 1, false, true ); if ( 'str' !== $rr[1] ) { return array( false, null ); } return array( true, (string) $rr[0] ); }; // ACG-149-132: FORWARD-DECLARED so $resolve_name can reuse the ONE argument splitter (assigned further down, // and only ever CALLED at scan time, long after both closures exist). Writing a second splitter here is the // exact "a model with its own narrow parser" defect this review has punished in rounds 17, 19, 21, 22 and 23. // Declaration order matters for anything a pre-scan fills - that trap cost a round already (ACG-149-128). $gp_mut_args = null; $resolve_name = null; // declared first so the closure can recurse $resolve_name = static function ( $start, $depth = 0, $gp_cls_pos = false, $gp_allow_empty = false ) use ( &$tok, $n, $is_char, $decode, $gp_php_unescape, &$const_str, &$resolve_name, &$gp_xform, &$gp_apply_xform, $gp_pure, $gp_pure_named, $gp_pure_eval, &$gp_pure_arg, &$gp_mut_args, &$gp_uconst, &$gp_cconst, &$gp_const_arr, &$gp_cconst_arr, &$gp_arr_descend, &$gp_class_ref, &$gp_class_of, &$gp_cls_str, &$gp_var_cls ) { if ( $depth > 4 || $start < 0 || $start >= $n ) { return array( '', '' ); } $k = $start; $steps = 0; $paren = 0; while ( $k < $n && $steps++ < 8 && $is_char( $tok[ $k ], '(' ) ) { $paren++; $k++; } $val = ''; $chan = ''; $want = true; for ( ; $k < $n && $steps++ < 200; $k++ ) { $x = $tok[ $k ]; if ( $want ) { // (a) a plain string literal if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $val .= trim( $decode( $x[1] ) ); $chan = 'str'; $want = false; continue; } // (b) a NOWDOC / non-interpolating HEREDOC body is a constant string too. // ACG-149-131 (FP round, self-found FN): a HEREDOC processes escape sequences and a NOWDOC does // not, and this arm took the raw token text for BOTH - so // $fn = << class name && isset( $gp_cconst[ $gp_scc . '::' . (string) $tok[ $k + 2 ][1] ] ) ) { $val .= $gp_cconst[ $gp_scc . '::' . (string) $tok[ $k + 2 ][1] ]; $chan = 'str'; $want = false; $k += 2; continue; } // (d1b) ACG-149-091 (reviewer round 4, MS-002): a bareword that is a known user CONSTANT holding a // callable string - `const F = "system"; (F)($_POST[..])`. MUST precede the bare class-name branch // (d2), which would otherwise treat F as a class SYMBOL. A constant's value is a fully-qualified // callable string ('str'). Excludes `F(` (that calls a FUNCTION named F, not the constant) and `F::`. if ( is_int( $x[0] ) && T_STRING === $x[0] && '' === $val && isset( $gp_uconst[ (string) $x[1] ] ) && ! ( $k + 1 < $n && is_int( $tok[ $k + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $k + 1 ][0] ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) ) ) { $val = $gp_uconst[ (string) $x[1] ]; $chan = 'str'; $want = false; continue; } // (d2) a BARE class-name token (`Closure`, `\Closure`, `Foo\Closure`). Same // compile-time channel as `X::class` - namespace-sensitive, so tagged 'sym'. // Only valid when it is the WHOLE operand: a name followed by '(' is a CALL, and // a name followed by '::' that is not '::class' is handled by the caller. if ( is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $x[0] ) || ( defined( 'T_NAME_RELATIVE' ) && T_NAME_RELATIVE === $x[0] ) ) && '' === $val && ! isset( $gp_pure[ strtolower( (string) $x[1] ) ] ) // ACG-149-136: $gp_pure is a SUPERSET of the retired $gp_xform, so this guard only widens // ACG-147-008: a bareword followed by '(' is the NAME AT THE HEAD OF A CALL, // and the operand's value is that call's RETURN VALUE - unknown. Without this // test `$cb = call_user_func( 'x', $y );` resolved to the string // 'call_user_func', which IS in the danger set, so every ordinary plugin // dispatcher, router and hook resolver was reported as CRITICAL MALWARE. // A following '::' is a static access whose value is the CONSTANT or METHOD, // not the class - `X::class` is handled by branch (d) above and never reaches // here. The CALLER decides whether a following '(' is a constructor, because // only the caller knows it is in class position (see the `new` and `::` arms). && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && ! $gp_cls_pos ) && ! ( ! $gp_cls_pos && $k + 1 < $n && is_int( $tok[ $k + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $k + 1 ][0] ) ) { $val = (string) $x[1]; $chan = 'sym'; $want = false; continue; } // (e) RETIRED in round 30 (ACG-149-136, R29-001). It was a SECOND model of the same // question: a single-argument transform table ($gp_xform) consulted before the generic // pure-literal evaluator below. Because `trim` was in BOTH, this arm modelled // `trim("__system__", "_")` as one-argument `trim("__system__")` - "__system__", harmless - // and then consumed the whole call, so the two-argument form could never reach the // evaluator. `ltrim`/`rtrim` were in $gp_pure only, which is precisely why the reviewer // observed they behaved better than `trim`; his observation was the diagnosis. // Every one of the nine $gp_xform names is in $gp_pure with a wider arity and the same // guards, so arm (e2) is a strict superset. TWO TABLES FOR ONE QUESTION is the defect class // this review has punished in rounds 17, 19, 21, 22, 23, 24d and 27 - the cure is deleting // the older model, not adding a condition to it. // (e2) ACG-149-133 (round 27, R26-001..004): a PURE-LITERAL CALL. One arm for the whole family - // every decoder, case/trim transform and assembly function in $gp_pure - because the arm asks a // GENERIC question ("do all arguments resolve to literals?") and then lets PHP itself supply the // answer. The argument list is split by the SHARED $gp_mut_args, so named arguments, the // `array(...)` and `[...]` spellings and PHP 8 attributes all come along; each argument is // resolved by THIS resolver recursively, so builders compose with each other and with the older // one-argument transforms for free. Fails clean: one unresolvable argument makes the name unknown. if ( is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && isset( $gp_pure[ $gp_bd_nm = ltrim( strtolower( (string) $x[1] ), chr( 92 ) ) ] ) && is_callable( $gp_mut_args ) ) { $gp_bnames = isset( $gp_pure_named[ $gp_bd_nm ] ) ? $gp_pure_named[ $gp_bd_nm ] : array(); $gp_bda = $gp_mut_args( $k, $gp_bnames ); if ( null === $gp_bda || empty( $gp_bda[3] ) ) { return array( '', '' ); } $gp_bs = $gp_bda[0]; if ( count( $gp_bs ) < 1 || count( $gp_bs ) > 8 ) { return array( '', '' ); } $gp_bargs = array(); foreach ( $gp_bs as $gp_bi => $gp_bp ) { $gp_bv = $gp_pure_arg( $gp_bp, $depth ); if ( ! $gp_bv[0] ) { return array( '', '' ); } $gp_bargs[] = $gp_bv[1]; } $gp_bout = $gp_pure_eval( $gp_bd_nm, $gp_bargs ); // ACG-149-135 (found by my OWN test of this round's fix): an ARRAY result is legitimate as an // ARGUMENT to another pure call - that is what makes implode(explode(..)) work - but it is NEVER // a resolved NAME. Appending it to $val produced a live "Array to string conversion" warning in // the customer's error log, which is exactly the class the E_ALL fuzzers exist to catch. A name // is a string; an array here means undecidable. // step over the call's own argument list $d3 = 1; $k3 = $k + 2; while ( $k3 < $n && $d3 > 0 && $steps++ < 500 ) { if ( $is_char( $tok[ $k3 ], '(' ) ) { $d3++; } elseif ( $is_char( $tok[ $k3 ], ')' ) ) { $d3--; if ( 0 === $d3 ) { break; } } $k3++; } // ACG-149-135 (R28-004, his second json_decode shape): a CONSTANT SUBSCRIPT on an array // result. `json_decode('["system"]')[0]` is "system", and the array is already computed - // indexing it here is the same operation $gp_arr_descend performs for a literal array. // ACG-149-R43-002 (self-found while closing R43-001): this descent handled EXACTLY ONE // level, because every builder it was written for returns a flat list. array_chunk does // not — `array_chunk(["system"], 1)` is `[["system"]]` and the name is at `[0][0]`. The // first step produced an ARRAY, the `is_string` test then failed, and the whole call went // undecidable: the row was in the table and the shape still read clean. A depth of one was // never a decision, just the shape of the examples that existed. It is a bounded LOOP now, // so any nesting a bounded builder can produce is reachable, and a chain that ends on // anything but a non-empty string still fails clean. if ( is_array( $gp_bout ) ) { $gp_sdep = 0; while ( is_array( $gp_bout ) && $gp_sdep++ < 4 ) { $gp_sx = $k3 + 1; while ( $gp_sx < $n && is_int( $tok[ $gp_sx ][0] ) && in_array( $tok[ $gp_sx ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_sx++; } if ( ! ( $gp_sx + 2 < $n && $is_char( $tok[ $gp_sx ], '[' ) ) ) { return array( '', '' ); } $gp_si = $gp_pure_arg( $gp_sx + 1, $depth + 1 ); $gp_sc = $gp_sx + 1; while ( $gp_sc < $n && ! $is_char( $tok[ $gp_sc ], ']' ) && $gp_sc < $gp_sx + 40 ) { $gp_sc++; } if ( ! ( $gp_si[0] && ( is_int( $gp_si[1] ) || is_string( $gp_si[1] ) ) && isset( $gp_bout[ $gp_si[1] ] ) && $gp_sc < $n && $is_char( $tok[ $gp_sc ], ']' ) ) ) { return array( '', '' ); } $gp_bout = $gp_bout[ $gp_si[1] ]; $k3 = $gp_sc; } if ( is_array( $gp_bout ) ) { return array( '', '' ); } // still an array after 4 steps } if ( ! is_string( $gp_bout ) || '' === $gp_bout ) { return array( '', '' ); } $val .= $gp_bout; $chan = 'str'; $want = false; $k = $k3; continue; } // (f) ACG-149-092/093/095 (round 5/6/8): `constant()` returns the value of a known user or CLASS // constant. is read BACKSLASH-PRESERVING (`$gp_cls_str` / `$gp_var_cls`, not the stripcslashes // $decode) so `constant("A\C::F")` keeps its namespace separator. A `C::F` / `self::F` / `A\C::F` name // is split; self/static/parent resolve via lexical context, a namespaced name by its short segment; // both a scalar const and an ARRAY const with a trailing subscript (`constant("C::CB")[0]`) resolve. // ACG-149-106 (round 13, R12-002): `\constant(..)` is the SAME global function as `constant(..)`, so the // name is normalised by stripping a leading separator. Matching a bare T_STRING made ONE backslash a // complete bypass of this whole branch - for the SCALAR path as well as the array path he reported. // PERF: a plain ltrim, not $called_fn - this is the hot per-operand path. if ( is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && 'constant' === ltrim( strtolower( (string) $x[1] ), chr( 92 ) ) ) { $gp_cnm = $gp_cls_str( $k + 2 ); if ( '' === $gp_cnm && $k + 2 < $n && is_int( $tok[ $k + 2 ][0] ) && T_VARIABLE === $tok[ $k + 2 ][0] && isset( $gp_var_cls[ $tok[ $k + 2 ][1] ] ) ) { $gp_cnm = (string) $gp_var_cls[ $tok[ $k + 2 ][1] ]; } // ACG-149-100 (round 10, R9-003): `constant(G)` where G is a bareword USER/`define()` constant whose // value is itself a constant NAME - `const G="C::F"; constant(G)` == constant("C::F"). Exactly // `constant( G )` (single bareword arg), G resolved from $gp_uconst; the split logic below handles it. if ( '' === $gp_cnm && $k + 3 < $n && is_int( $tok[ $k + 2 ][0] ) && T_STRING === $tok[ $k + 2 ][0] && $is_char( $tok[ $k + 3 ], ')' ) && isset( $gp_uconst[ (string) $tok[ $k + 2 ][1] ] ) ) { $gp_cnm = (string) $gp_uconst[ (string) $tok[ $k + 2 ][1] ]; } if ( '' === $gp_cnm ) { return array( '', '' ); } $gp_cad = 1; $gp_cak = $k + 2; // skip the constant() argument list to its ')' while ( $gp_cak < $n && $gp_cad > 0 && $steps++ < 500 ) { if ( $is_char( $tok[ $gp_cak ], '(' ) ) { $gp_cad++; } elseif ( $is_char( $tok[ $gp_cak ], ')' ) ) { $gp_cad--; if ( 0 === $gp_cad ) { break; } } $gp_cak++; } $gp_ccp = strpos( $gp_cnm, '::' ); if ( false !== $gp_ccp ) { $gp_lc = strtolower( ltrim( substr( $gp_cnm, 0, $gp_ccp ), chr( 92 ) ) ); if ( 'self' === $gp_lc || 'static' === $gp_lc || 'parent' === $gp_lc ) { $gp_ccls = $gp_class_ref( substr( $gp_cnm, 0, $gp_ccp ), $k ); } else { $gp_pp2 = explode( chr( 92 ), $gp_lc ); $gp_ccls = end( $gp_pp2 ); } if ( '' === $gp_ccls ) { return array( '', '' ); } $gp_ckey = $gp_ccls . '::' . substr( $gp_cnm, $gp_ccp + 2 ); if ( isset( $gp_cconst[ $gp_ckey ] ) ) { $val .= (string) $gp_cconst[ $gp_ckey ]; $chan = 'str'; $want = false; $k = $gp_cak; continue; } if ( isset( $gp_cconst_arr[ $gp_ckey ] ) && $gp_cak + 1 < $n && $is_char( $tok[ $gp_cak + 1 ], '[' ) ) { // constant("C::CB")[0] list( $gp_cd_leaf, $gp_cd_end ) = $gp_arr_descend( $gp_cconst_arr[ $gp_ckey ], $gp_cak + 1 ); if ( null === $gp_cd_leaf ) { return array( '', '' ); } $val = (string) $gp_cd_leaf; $chan = 'str'; $want = false; $k = $gp_cd_end - 1; continue; } return array( '', '' ); } if ( isset( $gp_uconst[ $gp_cnm ] ) ) { $val .= (string) $gp_uconst[ $gp_cnm ]; $chan = 'str'; $want = false; $k = $gp_cak; continue; } // ACG-149-103 (round 12, R11-002): a GLOBAL constant whose value is a literal ARRAY, subscripted - // `define("CB",["system"]); constant("CB")[0](..)` (also `const CB=[..]` and `constant($name)[0]`). // The class-const twin above has had this since round 8; the global branch resolved only a scalar. if ( isset( $gp_const_arr[ $gp_cnm ] ) && $gp_cak + 1 < $n && $is_char( $tok[ $gp_cak + 1 ], '[' ) ) { list( $gp_cd_leaf, $gp_cd_end ) = $gp_arr_descend( $gp_const_arr[ $gp_cnm ], $gp_cak + 1 ); if ( null === $gp_cd_leaf ) { return array( '', '' ); } $val = (string) $gp_cd_leaf; $chan = 'str'; $want = false; $k = $gp_cd_end - 1; continue; } return array( '', '' ); } return array( '', '' ); // not statically decidable } if ( $is_char( $x, '.' ) ) { $want = true; continue; } break; } // ACG-149-132: `'' === $val` means "an empty NAME is not a name", which is right for every existing // caller and WRONG for a builder ARGUMENT, where `""` is a perfectly good value - implode's glue and // str_replace's replacement are usually exactly that. The first cut of the builder arm resolved // `implode("s", [...])` and not `implode("", [...])` for precisely this reason. Opt-in, so no existing // caller changes: $want (nothing consumed at all) still fails unconditionally. if ( $want || ( '' === $val && ! $gp_allow_empty ) ) { return array( '', '' ); } while ( $paren > 0 && $k < $n && $is_char( $tok[ $k ], ')' ) ) { $paren--; $k++; } if ( $paren > 0 ) { return array( '', '' ); } // ACG-143-004 still governs: the run must BE the whole value. `'exec' === $mode ? …` must // not resolve, or a Yoda comparison becomes CRITICAL malware on idiomatic WordPress code. if ( $k >= $n ) { return array( $val, $chan ); } $t = $tok[ $k ]; if ( $is_char( $t, ';' ) || $is_char( $t, ',' ) || $is_char( $t, ')' ) || $is_char( $t, ']' ) || ( is_int( $t[0] ) && T_CLOSE_TAG === $t[0] ) || ( is_int( $t[0] ) && T_DOUBLE_COLON === $t[0] ) // `$c::method(` - operand ends here // ACG-149-133: `=>` ends a value exactly as `,` and `]` do - in `["X" => "t"]` the literal run // "X" IS the whole key. Without it an array KEY never resolved, which is the only reason // strtr("sysXem", ["X" => "t"]) stayed clean while the three-argument spelling worked. || ( is_int( $t[0] ) && defined( 'T_DOUBLE_ARROW' ) && T_DOUBLE_ARROW === $t[0] ) || $is_char( $t, '(' ) ) { // `new $rf(` / `("RF")(` return array( $val, $chan ); } return array( '', '' ); }; /** * ACG-147-003 (Adapter A) - resolve a CLASS OPERAND and decide whether it is PHP's own $want. * * THE #1 LANDMINE OF THIS ROUND. PHP applies two DIFFERENT rules: * - a class name that is a STRING at runtime (`"Closure"`, `$c` holding it, a concat) is * FULLY QUALIFIED. Namespace and `use` imports do NOT apply. `namespace Vend; $c="Closure"; * $c::fromCallable('system')(...)` really does call PHP's \Closure. * - `X::class` and a bare token ARE compile-time, namespace-SENSITIVE. * Routing a resolved string through the namespace resolver re-misses everything; routing * `X::class` through the string rule turns a vendor's own class into CRITICAL malware. Both * directions are pinned by fixtures in the CV and NG groups. */ // ACG-147-003 (Adapter A). Resolve a class OPERAND (not just a token) and apply the CORRECT // globality rule for its channel. See the landmine note at the declaration above. $class_operand_is_global = static function ( $idx, $want ) use ( &$resolve_name, &$class_is_global ) { // true = CLASS position: a following '(' is a constructor's argument list, not a call. $r = $resolve_name( $idx, 0, true ); if ( '' === $r[0] ) { return false; } if ( 'sym' === $r[1] ) { // `X::class` / a bareword: compile-time, so namespace + imports decide. return $class_is_global( $r[0], $want, $idx ); } // A runtime STRING class name is FULLY QUALIFIED - namespace and `use` do not apply. // An interior separator means a different class (`Vendor\Closure`), never PHP's own. $v = strtolower( ltrim( trim( $r[0] ), chr( 92 ) ) ); return ( false === strpos( $v, chr( 92 ) ) ) && $v === strtolower( $want ); }; // ACG-149-088 (external reviewer, pre-1.0.2 BLOCKER): the SAME globality rule as the string // channel of $class_operand_is_global, applied to a class/method PAIR already split out of a // runtime STRING or ARRAY callable. A runtime string class name is FULLY QUALIFIED, so the // class half must lowercase to 'closure' with NO interior separator (an interior '\' means a // vendor's own `Vendor\Closure`, a different class), and the method half to 'fromcallable'. $gp_fc_global_pair = static function ( $cls, $meth ) { $bs = chr( 92 ); $clsL = strtolower( ltrim( trim( (string) $cls ), $bs ) ); $mthL = strtolower( trim( (string) $meth ) ); return ( '' !== $clsL ) && ( false === strpos( $clsL, $bs ) ) && 'closure' === $clsL && 'fromcallable' === $mthL; }; // ACG-149-088: is the ARRAY LITERAL at $start exactly two STRING literals whose values are the // GLOBAL \Closure and fromCallable? Handles both `["Closure","fromCallable"]` and the // `array("Closure","fromCallable")` spelling. Any non-string element, or a count other than 2, // disqualifies it (a `[Closure::class, ...]` or `[$obj,'m']` is not a plain 2-literal callable). // Returns array( bool $is_global, int $close_idx ) so the caller can continue past the literal. $gp_fc_global_arr = static function ( $start ) use ( &$tok, $n, $is_char, &$resolve_name, &$class_operand_is_global ) { if ( $start < 0 || $start >= $n ) { return array( false, $start ); } $open = $start; if ( is_int( $tok[ $start ][0] ) && T_ARRAY === $tok[ $start ][0] ) { if ( $start + 1 >= $n || ! $is_char( $tok[ $start + 1 ], '(' ) ) { return array( false, $start ); } $open = $start + 1; } elseif ( ! $is_char( $tok[ $start ], '[' ) ) { return array( false, $start ); } // ACG-149-088 (siege on my own 1.0.2 diff) + ACG-149-089 (reviewer round 3, MS-002): find the TWO top-level // elements (a single depth-1 comma) and the closing bracket. The CLASS half goes through the SAME globality // helper the ::-token arm uses ($class_operand_is_global) so a runtime STRING "Closure" / a var / a concat // AND a namespace-checked bareword `Closure::class` all resolve to the global \Closure, while "Vendor\Closure" // (string) and a namespaced `Closure::class` (a different class) correctly stay clean. The METHOD half is // resolved as a string operand (literal / concat / const-var) and must be "fromcallable". A non-resolvable // element (`[$obj,'m']`) disqualifies (FG guard). Closes `[$c,"fromCallable"]`, `[Closure::class,"fromCallable"]`, // `["Clo"."sure","fromCallable"]`. $k = $open + 1; $d = 1; $comma = -1; $ncommas = 0; $steps = 0; while ( $k < $n && $d > 0 && $steps++ < 500 && self::scan_budget_ok() ) { $x = $tok[ $k ]; if ( $is_char( $x, '[' ) || $is_char( $x, '(' ) ) { $d++; } elseif ( $is_char( $x, ']' ) || $is_char( $x, ')' ) ) { $d--; if ( 0 === $d ) { break; } } elseif ( 1 === $d && $is_char( $x, ',' ) ) { $ncommas++; if ( $comma < 0 ) { $comma = $k; } } $k++; } if ( 1 !== $ncommas || $comma <= $open + 1 || $comma + 1 >= $k ) { return array( false, $k ); } // CLASS half: the shared globality rule (handles "Closure" string / var / concat AND Closure::class bareword // with the namespace check; rejects Vendor\Closure and a namespaced Closure::class). $cls_global = $class_operand_is_global( $open + 1, 'closure' ); // METHOD half: a resolved string operand equal to 'fromcallable'. $r2 = $resolve_name( $comma + 1 ); $meth_ok = ( '' !== $r2[0] && 'fromcallable' === strtolower( trim( (string) $r2[0] ) ) ); return array( ( $cls_global && $meth_ok ), $k ); }; // ACG-149-090 (reviewer round 3, MS-004): scan an ARRAY LITERAL at $start ([...] or array(...)) and return // the set of CONSTANT integer indices whose element resolves to a DANGEROUS GLOBAL FUNCTION name - // `["system"]` => {0}, `[1 => "exec"]` => {1}. ONLY a 'str'-channel value $danger_name accepts is recorded, so // a vendor class name, a namespaced symbol, an object callable or an unresolvable element is NEVER flagged. // This is the POSITIVE proof that `$cb[]($_POST[..])` / `call_user_func($cb[], $_POST[..])` is a // hidden dangerous callable (a webshell), while an array of SAFE callables stays a benign dispatch table. // ACG-149-091 (reviewer round 4, MS-001): PHP array-key normalisation - a canonical decimal-integer STRING // key ("0","42","-5") becomes an INT key, everything else stays a string. So `$cb["0"]` and `$cb[0]` are the // same slot, exactly as PHP treats them; a leading-zero / non-numeric string ("x","08") stays a string key. // ACG-149-092 (round 5): scan a literal array at $start into a NESTED value map - a dangerous string element // becomes its NAME at the leaf, a nested array element recurses (bounded depth). Only dangerous paths kept, so // `["a"=>["b"=>"system"]]` => {a:{b:"system"}} and a fully-safe array => {}. $gp_scan_arr_danger = null; $gp_scan_arr_danger = static function ( $start, $depth = 0 ) use ( &$tok, $n, $is_char, $decode, &$resolve_name, &$danger_name, &$gp_arrkey_norm, &$gp_scan_arr_danger ) { $out = array(); if ( $depth > 6 || $start < 0 || $start >= $n ) { return $out; } $open = $start; if ( is_int( $tok[ $start ][0] ) && T_ARRAY === $tok[ $start ][0] ) { if ( $start + 1 >= $n || ! $is_char( $tok[ $start + 1 ], '(' ) ) { return $out; } $open = $start + 1; } elseif ( ! $is_char( $tok[ $start ], '[' ) ) { return $out; } $k = $open + 1; $d = 1; $auto = 0; $el_start = $open + 1; $arrow = -1; $steps = 0; $blind = false; while ( $k < $n && $d > 0 && $steps++ < 5000 && self::scan_budget_ok() ) { $x = $tok[ $k ]; if ( $is_char( $x, '[' ) || $is_char( $x, '(' ) ) { $d++; $k++; continue; } if ( $is_char( $x, ']' ) || $is_char( $x, ')' ) ) { $d--; } if ( 1 === $d && is_int( $x[0] ) && T_DOUBLE_ARROW === $x[0] ) { $arrow = $k; $k++; continue; } if ( ( 1 === $d && $is_char( $x, ',' ) ) || 0 === $d ) { // element boundary: depth-1 comma OR the array's own close $idx = null; $val_start = $el_start; if ( $arrow >= 0 ) { // keyed element: a small integer literal, a STRING key, or a numeric-string key if ( $arrow === $el_start + 1 && is_int( $tok[ $el_start ][0] ) && T_LNUMBER === $tok[ $el_start ][0] && ctype_digit( (string) $tok[ $el_start ][1] ) ) { $idx = (int) $tok[ $el_start ][1]; if ( $idx >= $auto ) { $auto = $idx + 1; } } elseif ( $arrow === $el_start + 1 && is_int( $tok[ $el_start ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $el_start ][0] ) { $idx = $gp_arrkey_norm( trim( $decode( $tok[ $el_start ][1] ) ) ); // ACG-149-091 (MS-001): a string key ("x") / numeric-string ("0"->0) if ( is_int( $idx ) && $idx >= $auto ) { $auto = $idx + 1; } } // ACG-149-120 (round 20, self-found FP): a key we cannot read makes every LATER index unknown. if ( null === $idx ) { $blind = true; } $val_start = $arrow + 1; } elseif ( $el_start < $k ) { // positional element (skip a trailing comma before `]`) $idx = $auto; $auto++; } if ( ! empty( $blind ) ) { $idx = null; } // …so record nothing from that point on if ( null !== $idx && $val_start < $k ) { if ( $is_char( $tok[ $val_start ], '[' ) || ( is_int( $tok[ $val_start ][0] ) && T_ARRAY === $tok[ $val_start ][0] ) ) { $sub = $gp_scan_arr_danger( $val_start, $depth + 1 ); // ACG-149-092 (MS-002): a NESTED array value if ( ! empty( $sub ) ) { $out[ $idx ] = $sub; } } else { $r = $resolve_name( $val_start ); if ( '' !== $r[0] && 'str' === $r[1] && $danger_name( ltrim( strtolower( trim( (string) $r[0] ) ), '\\' ) ) ) { $out[ $idx ] = ltrim( strtolower( trim( (string) $r[0] ) ), '\\' ); } } } $el_start = $k + 1; $arrow = -1; if ( 0 === $d ) { break; } } $k++; } return $out; }; // ACG-149-104 (round 12, R11-001): the NEXT auto index of an array LITERAL at $start - what PHP would assign to // the first `$var[] = …` append. Positional elements consume an auto index; an INTEGER (or numeric-string) key // raises the counter to key+1; a plain string key does not move it (PHP semantics). Anything not statically // classifiable (a variable/const/expression key, a `...` spread) returns null so the caller fails toward CLEAN. // Pure and bounded; called only at an append-assignment site, never per operand. $gp_arr_auto_next = static function ( $start ) use ( &$tok, $n, $is_char, $decode ) { if ( $start < 0 || $start >= $n ) { return null; } $open = $start; if ( is_int( $tok[ $start ][0] ) && T_ARRAY === $tok[ $start ][0] ) { if ( $start + 1 >= $n || ! $is_char( $tok[ $start + 1 ], '(' ) ) { return null; } $open = $start + 1; } elseif ( ! $is_char( $tok[ $start ], '[' ) ) { return null; } $k = $open + 1; $d = 1; $auto = 0; $el_start = $open + 1; $arrow = -1; $steps = 0; while ( $k < $n && $d > 0 && $steps++ < 2000 ) { $x = $tok[ $k ]; if ( $is_char( $x, '[' ) || $is_char( $x, '(' ) ) { $d++; $k++; continue; } if ( $is_char( $x, ']' ) || $is_char( $x, ')' ) ) { $d--; } if ( 1 === $d && is_int( $x[0] ) && T_DOUBLE_ARROW === $x[0] ) { $arrow = $k; $k++; continue; } if ( 1 === $d && is_int( $x[0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $x[0] ) { return null; } // a spread makes the length unknowable if ( ( 1 === $d && $is_char( $x, ',' ) ) || 0 === $d ) { if ( $arrow >= 0 ) { $gp_ky = null; if ( $arrow === $el_start + 1 && is_int( $tok[ $el_start ][0] ) && T_LNUMBER === $tok[ $el_start ][0] && ctype_digit( (string) $tok[ $el_start ][1] ) ) { $gp_ky = (string) $tok[ $el_start ][1]; } elseif ( $arrow === $el_start + 1 && is_int( $tok[ $el_start ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $el_start ][0] ) { $gp_ky = trim( $decode( $tok[ $el_start ][1] ) ); // a numeric-string key IS an int key in PHP; a plain string key does not move $auto } else { return null; // an unclassifiable key - the next index is unknown } if ( '' !== (string) $gp_ky && preg_match( '/^(?:0|[1-9][0-9]*)$/', (string) $gp_ky ) && (int) $gp_ky >= $auto ) { $auto = (int) $gp_ky + 1; } } elseif ( $el_start < $k ) { $auto++; // a positional element consumes the auto index } $el_start = $k + 1; $arrow = -1; if ( 0 === $d ) { break; } } $k++; } return ( 0 === $d ) ? $auto : null; }; // ACG-149-104 (round 12, R11-001): resolve a `$var[key]…` operand against the CURRENT scope's proven-dangerous // slot map to its leaf NAME, or ''. $resolve_name cannot do this - $gp_arr_danger is per-scope main-loop state, // not a lexical fact - so the callback-API arm has always descended it inline. This is the SAME descent, shared // with the Closure::fromCallable / ReflectionFunction sink sites, where a `$cb[0]` argument resolved to nothing // (a pre-existing gap for the literal, keyed AND appended forms; the reviewer asked for all four sinks). // Per-sink-occurrence only, never per operand. $gp_var_arr_leaf = static function ( $start ) use ( &$tok, $n, $is_char, &$gp_arr_danger, &$gp_arr_descend ) { if ( $start < 0 || $start + 1 >= $n || ! ( is_int( $tok[ $start ][0] ) && T_VARIABLE === $tok[ $start ][0] ) ) { return ''; } if ( ! $is_char( $tok[ $start + 1 ], '[' ) || ! isset( $gp_arr_danger[ $tok[ $start ][1] ] ) ) { return ''; } list( $leaf, ) = $gp_arr_descend( $gp_arr_danger[ $tok[ $start ][1] ], $start + 1 ); return ( null === $leaf ) ? '' : (string) $leaf; }; // ACG-149-108/109 (round 13/14, R12-004 + R13-001): array mutators that act on a tracked array, by KIND. // Round 13 modelled push/unshift exactly and RETIRED the whole snapshot for everything else - which removed four // real false positives but, as the reviewer then showed, left a short FALSE NEGATIVE: after // `$cb=["strlen","system"]; array_shift($cb);` the dangerous value is provably at index 0. So the removing // mutators now get their EXACT key transform instead of the blunt retire; only genuinely order-destroying ones // (the sort family, array_reverse, shuffle) still retire, because their result depends on the VALUES. // 1 = append at the end (index model identical to `$var[] = …`) // 2 = insert at the front, renumber int keys UP // 3 = array_shift: drop key 0, renumber int keys DOWN by 1 // 4 = array_pop: drop the HIGHEST int key (needs the length -> retires when the layout is not provable) // 5 = array_splice($cb, off, len): drop keys [off, off+len), renumber the rest DOWN by len (literal off/len only) // 9 = order depends on the data -> retire the per-slot snapshot (fail toward clean) $gp_mutators = array( 'array_push' => 1, 'array_unshift' => 2, 'array_shift' => 3, 'array_pop' => 4, 'array_splice' => 5, // ACG-149-121 (round 21, self-found EVASION): array_reverse is NOT here. It does not touch its argument - // it RETURNS a reversed copy (verified against the interpreter) - so treating it as a mutator retired every // fact on sight and `array_reverse($cb);` alone silenced the model. Every remaining entry is by-reference. 'sort' => 9, 'rsort' => 9, 'usort' => 9, 'uasort' => 9, 'uksort' => 9, 'asort' => 9, 'arsort' => 9, 'ksort' => 9, 'krsort' => 9, 'natsort' => 9, 'natcasesort' => 9, 'shuffle' => 9, ); // ACG-149-108 (round 13, R12-004): how many values were APPENDED to $vname between $from and $to. Counts BOTH // spellings of the same operation - `$var[] = …` and `array_push($var, a, b)` (which appends one value per // depth-1 comma) - because they share one index space: `$cb[]="a"; array_push($cb,"system");` puts "system" at 1. // ONE shared primitive so the two arms can never disagree about the next index. Stateless by design (a stored // counter that desynced from the scope-restored state could point at the WRONG slot and cause an FP). $gp_append_count = static function ( $vname, $from, $to ) use ( &$tok, $n, $is_char ) { $cnt = 0; $steps = 0; for ( $q = ( $from > 0 ? $from : 0 ); $q < $to && $q < $n && $steps++ < 20000; $q++ ) { if ( ! ( is_int( $tok[ $q ][0] ) ) ) { continue; } if ( T_VARIABLE === $tok[ $q ][0] && (string) $tok[ $q ][1] === (string) $vname && $q + 3 < $n && $is_char( $tok[ $q + 1 ], '[' ) && $is_char( $tok[ $q + 2 ], ']' ) && $is_char( $tok[ $q + 3 ], '=' ) && ! ( $q + 4 < $n && $is_char( $tok[ $q + 4 ], '=' ) ) ) { $cnt++; continue; } // ACG-149-121 (round 21, FP): the variable is passed to a DYNAMIC callee (`$f($cb, …)`) or through // call_user_func_array. That call may well be a push, and this counter cannot know, so the auto index is // not derivable in this window - report it unknowable rather than count as if nothing happened. // EXCEPT when the callee is provably a CLOSURE that takes nothing by reference: PHP cannot mutate the // caller's array through a by-value parameter, so such a call changes no index. Without this the very // ordinary `$log = function (array $steps) {…}; $log($items);` before a push destroyed the detection. if ( T_VARIABLE === $tok[ $q ][0] && $q + 2 < $n && $is_char( $tok[ $q + 1 ], '(' ) && is_int( $tok[ $q + 2 ][0] ) && T_VARIABLE === $tok[ $q + 2 ][0] && (string) $tok[ $q + 2 ][1] === (string) $vname ) { $byval = false; $cn = (string) $tok[ $q ][1]; for ( $z = ( $from > 0 ? $from : 0 ); $z < $q && $z < $n; $z++ ) { if ( ! is_int( $tok[ $z ][0] ) || T_VARIABLE !== $tok[ $z ][0] || (string) $tok[ $z ][1] !== $cn ) { continue; } $z2 = $z + 1; while ( $z2 < $q && is_int( $tok[ $z2 ][0] ) && in_array( $tok[ $z2 ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $z2++; } if ( $z2 >= $q || ! $is_char( $tok[ $z2 ], '=' ) ) { continue; } $z3 = $z2 + 1; while ( $z3 < $q && is_int( $tok[ $z3 ][0] ) && in_array( $tok[ $z3 ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_STATIC ), true ) ) { $z3++; } $isfn = ( $z3 < $q && is_int( $tok[ $z3 ][0] ) && ( T_FUNCTION === $tok[ $z3 ][0] || ( defined( 'T_FN' ) && T_FN === $tok[ $z3 ][0] ) ) ); if ( ! $isfn ) { $byval = false; continue; } // assigned something else -> unknown // scan just the PARAMETER LIST for any by-reference marker $byval = true; for ( $z4 = $z3, $z4d = 0; $z4 < $q && $z4 < $z3 + 200; $z4++ ) { if ( $is_char( $tok[ $z4 ], '(' ) ) { $z4d++; continue; } if ( $is_char( $tok[ $z4 ], ')' ) ) { $z4d--; if ( 0 === $z4d ) { break; } continue; } if ( $z4d < 1 ) { continue; } if ( $is_char( $tok[ $z4 ], '&' ) ) { $byval = false; break; } if ( is_int( $tok[ $z4 ][0] ) && in_array( token_name( $tok[ $z4 ][0] ), array( 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG' ), true ) ) { $byval = false; break; } } } if ( ! $byval ) { return -1; } continue; } if ( T_STRING === $tok[ $q ][0] && 'call_user_func_array' === ltrim( strtolower( (string) $tok[ $q ][1] ), chr( 92 ) ) && $q + 1 < $n && $is_char( $tok[ $q + 1 ], '(' ) ) { for ( $z = $q + 2, $zd = 1; $z < $n && $z < $q + 400; $z++ ) { if ( $is_char( $tok[ $z ], '(' ) || $is_char( $tok[ $z ], '[' ) ) { $zd++; continue; } if ( $is_char( $tok[ $z ], ')' ) || $is_char( $tok[ $z ], ']' ) ) { $zd--; if ( 0 === $zd ) { break; } continue; } if ( is_int( $tok[ $z ][0] ) && T_VARIABLE === $tok[ $z ][0] && (string) $tok[ $z ][1] === (string) $vname ) { return -1; } } } if ( $q + 3 < $n && $is_char( $tok[ $q + 1 ], '(' ) && is_int( $tok[ $q + 2 ][0] ) && T_VARIABLE === $tok[ $q + 2 ][0] && (string) $tok[ $q + 2 ][1] === (string) $vname && 'array_push' === ltrim( strtolower( (string) $tok[ $q ][1] ), chr( 92 ) ) ) { // PERF: plain ltrim, not $called_fn $d = 1; $args = 0; $spread = 0; for ( $r = $q + 3; $r < $n && $r < $q + 400; $r++ ) { // ACG-149-121 (round 21): a PHP 8 attribute `#[` is ONE token (T_ATTRIBUTE) whose `]` still // closes, so it must count as an opener or the depth underflows and the index model shifts. if ( is_int( $tok[ $r ][0] ) && defined( 'T_ATTRIBUTE' ) && T_ATTRIBUTE === $tok[ $r ][0] ) { $d++; continue; } if ( $is_char( $tok[ $r ], '(' ) || $is_char( $tok[ $r ], '[' ) ) { $d++; continue; } if ( $is_char( $tok[ $r ], ')' ) || $is_char( $tok[ $r ], ']' ) ) { $d--; if ( 0 === $d ) { break; } continue; } if ( 1 === $d && $is_char( $tok[ $r ], ',' ) ) { $args++; } if ( 1 === $d && is_int( $tok[ $r ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $r ][0] ) { $spread++; } } // ACG-149-118 (R17-004): a spread argument contributes an unknown-here number of values; the index // space can no longer be counted by commas, so report the count as unknowable (-1) and let the caller // fail toward clean rather than place a fact on the wrong slot. if ( $spread > 0 ) { return -1; } $cnt += $args; // one appended value per depth-1 comma } } return $cnt; }; // ACG-149-113 (round 15, R14-001..004): THE ORDERED LAYOUT of an array literal - the ordered list of ALL its keys // plus the next auto index. A PHP array is an ORDERED map, and `array_pop`/`array_shift`/`array_unshift`/ // `array_splice` all work on POSITION, not on key value: pop removes the LAST element in order (not the highest // integer key), shift removes the FIRST (not key 0) and then renumbers the integer keys sequentially. Round 14 // transformed keys directly and was therefore wrong in both directions - it produced false negatives // (`[2=>"system",0=>"strlen"]` + pop really keeps key 2) AND critical false positives (`["x"=>"system",0=>…]` + // shift really removes "x"). Modelling those needs EVERY slot, not just the dangerous ones, which is what this // returns. Any element whose key is not statically decidable (a variable key, a spread) makes the whole layout // unknown -> null -> the caller retires the snapshot rather than guess. $gp_arr_layout = static function ( $start ) use ( &$tok, $n, $is_char, $decode ) { if ( $start < 0 || $start >= $n ) { return null; } $open = $start; if ( is_int( $tok[ $start ][0] ) && T_ARRAY === $tok[ $start ][0] ) { if ( $start + 1 >= $n || ! $is_char( $tok[ $start + 1 ], '(' ) ) { return null; } $open = $start + 1; } elseif ( ! $is_char( $tok[ $start ], '[' ) ) { return null; } $k = $open + 1; $d = 1; $auto = 0; $el_start = $open + 1; $arrow = -1; $steps = 0; $keys = array(); while ( $k < $n && $d > 0 && $steps++ < 4000 ) { $x = $tok[ $k ]; if ( $is_char( $x, '[' ) || $is_char( $x, '(' ) ) { $d++; $k++; continue; } if ( $is_char( $x, ']' ) || $is_char( $x, ')' ) ) { $d--; } if ( 1 === $d && is_int( $x[0] ) && T_DOUBLE_ARROW === $x[0] ) { $arrow = $k; $k++; continue; } if ( 1 === $d && is_int( $x[0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $x[0] ) { return null; } if ( ( 1 === $d && $is_char( $x, ',' ) ) || 0 === $d ) { if ( $arrow >= 0 ) { $ky = null; if ( $arrow === $el_start + 1 && is_int( $tok[ $el_start ][0] ) && T_LNUMBER === $tok[ $el_start ][0] && ctype_digit( (string) $tok[ $el_start ][1] ) ) { $ky = (int) $tok[ $el_start ][1]; } elseif ( $arrow === $el_start + 1 && is_int( $tok[ $el_start ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $el_start ][0] ) { $sv = trim( $decode( $tok[ $el_start ][1] ) ); $ky = ( '' !== $sv && preg_match( '/^(?:0|[1-9][0-9]*)$/', $sv ) ) ? (int) $sv : $sv; // a numeric string IS an int key } else { return null; // an undecidable key -> the whole layout is unknown } $keys[] = $ky; if ( is_int( $ky ) && $ky >= $auto ) { $auto = $ky + 1; } } elseif ( $el_start < $k ) { $keys[] = $auto; $auto++; // positional element } $el_start = $k + 1; $arrow = -1; if ( 0 === $d ) { break; } } $k++; } return ( 0 === $d ) ? array( $keys, $auto ) : null; }; // ACG-149-113 (round 15): PHP's renumbering after a positional insert/remove - integer keys are renumbered // sequentially from 0 IN ORDER, string keys keep their key. Returns array( new_ordered_keys, old=>new map, next ). $gp_arr_reindex = static function ( $keys ) { $out = array(); $map = array(); $ni = 0; foreach ( $keys as $k ) { if ( is_int( $k ) ) { $out[] = $ni; $map[ 'i' . $k ] = $ni; $ni++; } else { $out[] = $k; $map[ 's' . $k ] = $k; } } return array( $out, $map, $ni ); }; // ACG-149-114 (round 16, R15-001): apply a FULL `array_splice($var, off, len [, replacement])` to an ordered key // layout. Round 15 modelled only the deletion path: a 4th argument made the mutator arm retire (so // `array_splice($cb,0,1,[])` - semantically a plain delete - went clean) while the layout replay ignored it // entirely, so the two disagreed. ONE helper now serves both, which is what keeps them consistent. // PHP semantics, each verified against the interpreter before this was written: // * elements are removed by OFFSET in order, and the replacement's values are inserted in their place; // * a SURVIVING string key keeps its key, but every integer key is renumbered sequentially from 0 in order; // * the replacement's OWN keys are discarded - `["k"=>"system"]` inserts the VALUE at the next position; // * a non-array replacement is a single element. // Returns array( new_keys, old=>new remap, list of new keys for the inserted slots, next_index ) or null when // anything is not statically decidable (the caller then retires the snapshot - a miss, never a false positive). // ACG-149-115 (round 17, R16-002): resolve an INTEGER operand - a literal, a NEGATIVE literal, a bareword // constant, a class constant, or a variable holding an int - or null. array_splice's bounds went through their own // `T_LNUMBER`-only parser, so `-1`, `OFF`, `K::OFF` and `$off` all silently retired the snapshot even though the // engine had resolvers for every one of them. This is that shared resolver. // ACG-149-120 (round 20, R19-002/003): PHP coerces a numeric STRING and a BOOLEAN in the int parameter of an // internal function - `array_splice($cb, "0", "1")` and `array_splice($cb, false, 1)` are the same calls as the // ones written with 0 and 1. Every arm of the bounds resolver carried its OWN plain-integer regex, so a pair of // quotes or the word `false` was simply "unresolvable" - which RETIRES THE SNAPSHOT and silenced the sink. // This is the ONE place that answers "what int does PHP see here", and every arm below calls it - a value the // engine already resolved (variable / constant / class constant) and a literal token both land here. // Returns an int, the 'NULL' sentinel (= "to the end" for a length), or null when not statically decidable. $gp_num_coerce = static function ( $sv ) { $t = trim( (string) $sv ); $lc = strtolower( $t ); if ( 'null' === $lc ) { return 'NULL'; } if ( 'true' === $lc ) { return 1; } if ( 'false' === $lc ) { return 0; } if ( '' === $t ) { return null; } // A plain integer string, leading zeros and surrounding space included ("01" is 1 as a STRING - note this is // NOT the same as the source literal 01, which is octal; that is handled at the token, below). if ( preg_match( '/^[+-]?[0-9]+$/', $t ) ) { if ( strlen( ltrim( $t, '+-0' ) ) > 18 ) { return null; } // out of int range -> PHP fatals; do not guess return (int) $t; } // ACG-149-121 (round 21, R20-001): any other NUMERIC string is still an int to PHP, truncated toward zero - // "0e0", "1e2", "1.0", "1.9", "-1.9". Verified against the interpreter, not assumed. if ( is_numeric( $t ) ) { $f = (float) $t; if ( $f > 4096 || $f < -4096 ) { return null; } // outside the bounds we model anyway return (int) $f; // (int) of a float truncates toward zero } return null; }; // ACG-149-121 (round 21, R20-001): the value of a NUMERIC LITERAL TOKEN as PHP's own parser reads it. This is a // different question from $gp_num_coerce (which is about a string VALUE), and conflating them is what made // `0x1` and `0b1` unresolvable while `01` worked. Returns int, or null when not a numeric literal. $gp_lit_int = static function ( $tk ) { if ( ! is_int( $tk[0] ) ) { return null; } $raw = str_replace( '_', '', (string) $tk[1] ); // numeric literal separators if ( T_LNUMBER === $tk[0] ) { // PHP 8.1 EXPLICIT octal: intval(..., 0) answers 0 for "0o17" while PHP means 15. if ( preg_match( '/^0[oO]([0-7]+)$/', $raw, $m ) ) { return intval( $m[1], 8 ); } if ( ! preg_match( '/^0[xXbB]?[0-9a-fA-F]*$|^[0-9]+$/', $raw ) ) { return null; } return intval( $raw, 0 ); // 0x/0b/leading-0 octal/decimal } if ( defined( 'T_DNUMBER' ) && T_DNUMBER === $tk[0] ) { if ( ! is_numeric( $raw ) ) { return null; } $f = (float) $raw; if ( $f > 4096 || $f < -4096 ) { return null; } return (int) $f; // truncates toward zero, like PHP } return null; }; $gp_int_operand = static function ( $p ) use ( &$tok, $n, $is_char, &$gp_uconst_int, &$gp_uconst, &$gp_cconst_int, &$gp_cconst, &$gp_class_of, &$const_str, &$gp_isnull, &$gp_cls_str, &$gp_class_ref, &$gp_num_coerce, &$resolve_name, &$gp_lit_int ) { if ( $p < 0 || $p >= $n ) { return null; } $neg = 0; if ( $is_char( $tok[ $p ], '-' ) ) { $neg = 1; $p++; if ( $p >= $n ) { return null; } } // ACG-149-121 (round 21, self-found): a leading `+` is legal PHP and $gp_operand_exact already accepts it, // so the two helpers disagreed and `array_splice($cb, +1, 1)` resolved to nothing. elseif ( $is_char( $tok[ $p ], '+' ) ) { $p++; if ( $p >= $n ) { return null; } } $num = null; // ACG-149-117 (round 18, R17-003): NULL in any of its spellings means "to the end" for a length. Returned as // the sentinel string 'NULL' so the caller can tell it apart from "unresolvable" (which is a real null). if ( is_int( $tok[ $p ][0] ) && T_STRING === $tok[ $p ][0] && 'null' === strtolower( (string) $tok[ $p ][1] ) && ! ( $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) ) { return 'NULL'; } // ACG-149-120 (R19-003): `false` / `true` as a bound. Guarded against a CALL or a class-constant access of // the same name, exactly as the `null` test above is. if ( is_int( $tok[ $p ][0] ) && T_STRING === $tok[ $p ][0] && in_array( strtolower( (string) $tok[ $p ][1] ), array( 'true', 'false' ), true ) && ! ( $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) && ! ( $p + 1 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] ) ) { $bv = ( 'true' === strtolower( (string) $tok[ $p ][1] ) ) ? 1 : 0; return $neg ? -$bv : $bv; } // ACG-149-120 (R19-002): a quoted numeric literal - `array_splice($cb, "0", "1")`. The engine already // resolved this value through a VARIABLE holding "0", which made the literal form an inconsistency, and the // reviewer found it as exactly that. if ( is_int( $tok[ $p ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $p ][0] ) { $sr = $resolve_name( $p ); if ( '' !== $sr[0] && 'str' === $sr[1] ) { $cv = $gp_num_coerce( $sr[0] ); if ( 'NULL' === $cv ) { return 'NULL'; } if ( is_int( $cv ) ) { return $neg ? -$cv : $cv; } } return null; } // `$len = null;` — note the value may be recorded as the literal word 'null' (the name resolver treats a bare // `null` as a symbol and stores it before the numeric capture ever runs), so accept BOTH spellings here rather // than trying to intercept the assignment. Found by the operand matrix: 145 classes, this one cause. if ( is_int( $tok[ $p ][0] ) && T_VARIABLE === $tok[ $p ][0] && isset( $const_str[ $tok[ $p ][1] ] ) && in_array( strtoupper( (string) $const_str[ $tok[ $p ][1] ][0] ), array( 'NULL' ), true ) ) { return 'NULL'; } if ( is_int( $tok[ $p ][0] ) && T_STRING === $tok[ $p ][0] && isset( $gp_isnull[ 'c:' . (string) $tok[ $p ][1] ] ) ) { return 'NULL'; } // ACG-149-117 (round 18, R17-001/002 sibling): `constant("LEN")` - the same value one indirection away. The // engine resolves constant() at several other sites; the bounds parser did not reach any of them. if ( is_int( $tok[ $p ][0] ) && ( T_STRING === $tok[ $p ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $p ][0] ) ) && 'constant' === ltrim( strtolower( (string) $tok[ $p ][1] ), chr( 92 ) ) && $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) { $cnm = $gp_cls_str( $p + 2 ); if ( '' === $cnm && $p + 3 < $n && is_int( $tok[ $p + 2 ][0] ) && T_STRING === $tok[ $p + 2 ][0] && $is_char( $tok[ $p + 3 ], ')' ) && isset( $gp_uconst[ (string) $tok[ $p + 2 ][1] ] ) ) { $cnm = (string) $gp_uconst[ (string) $tok[ $p + 2 ][1] ]; // constant(RN) where RN is a known constant } if ( '' === $cnm ) { return null; } $cpos = strpos( $cnm, '::' ); if ( false !== $cpos ) { $clhs = strtolower( ltrim( substr( $cnm, 0, $cpos ), chr( 92 ) ) ); if ( 'self' === $clhs || 'static' === $clhs || 'parent' === $clhs ) { $cown = $gp_class_ref( substr( $cnm, 0, $cpos ), $p ); // ACG-149-119: LEXICAL, not the literal word if ( '' === $cown ) { return null; } $ckey = $cown . '::' . substr( $cnm, $cpos + 2 ); } else { $cparts = explode( chr( 92 ), $clhs ); $ckey = end( $cparts ) . '::' . substr( $cnm, $cpos + 2 ); } if ( isset( $gp_isnull[ 'k:' . $ckey ] ) ) { return 'NULL'; } if ( isset( $gp_cconst_int[ $ckey ] ) ) { return $neg ? -(int) $gp_cconst_int[ $ckey ] : (int) $gp_cconst_int[ $ckey ]; } if ( isset( $gp_cconst[ $ckey ] ) && preg_match( '/^-?(?:0|[1-9][0-9]*)$/', (string) $gp_cconst[ $ckey ] ) ) { $v = (int) $gp_cconst[ $ckey ]; return $neg ? -$v : $v; } return null; } if ( isset( $gp_isnull[ 'c:' . $cnm ] ) ) { return 'NULL'; } if ( isset( $gp_uconst_int[ $cnm ] ) ) { return $neg ? -(int) $gp_uconst_int[ $cnm ] : (int) $gp_uconst_int[ $cnm ]; } if ( isset( $gp_uconst[ $cnm ] ) && preg_match( '/^-?(?:0|[1-9][0-9]*)$/', (string) $gp_uconst[ $cnm ] ) ) { $v = (int) $gp_uconst[ $cnm ]; return $neg ? -$v : $v; } return null; } // ACG-149-120: each of these arms used to carry its OWN integer regex, so a numeric string or a boolean // arriving through a variable or a constant behaved differently from the literal spelling. They all ask // $gp_num_coerce now - one rule, every spelling. // ACG-149-121 (round 21, R20-001): every numeric LITERAL FORM PHP has - decimal, octal (leading zero and // explicit 0o), hex, binary, with numeric separators, and float literals - goes through one reader. // (Round 20 used ctype_digit here, which is true for "010" and false for "0x1": it answers "are these // digits", never "what does PHP's parser make of this". Third time that primitive has bitten.) if ( is_int( $tok[ $p ][0] ) && ( T_LNUMBER === $tok[ $p ][0] || ( defined( 'T_DNUMBER' ) && T_DNUMBER === $tok[ $p ][0] ) ) && null !== $gp_lit_int( $tok[ $p ] ) ) { $num = (int) $gp_lit_int( $tok[ $p ] ); } elseif ( is_int( $tok[ $p ][0] ) && T_VARIABLE === $tok[ $p ][0] && isset( $const_str[ $tok[ $p ][1] ] ) && ! ( $p + 1 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] ) ) { $cv = $gp_num_coerce( $const_str[ $tok[ $p ][1] ][0] ); if ( 'NULL' === $cv ) { return 'NULL'; } if ( ! is_int( $cv ) ) { return null; } $num = $cv; } elseif ( $p + 1 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] ) { list( $cl, $cp ) = $gp_class_of( $p ); // K::OFF / self::OFF / static::OFF if ( '' === $cl || $cp + 1 >= $n || ! is_int( $tok[ $cp + 1 ][0] ) || T_STRING !== $tok[ $cp + 1 ][0] ) { return null; } $ck = $cl . '::' . (string) $tok[ $cp + 1 ][1]; if ( isset( $gp_isnull[ 'k:' . $ck ] ) ) { return 'NULL'; } if ( isset( $gp_cconst_int[ $ck ] ) ) { $num = (int) $gp_cconst_int[ $ck ]; } elseif ( isset( $gp_cconst[ $ck ] ) ) { $cv = $gp_num_coerce( $gp_cconst[ $ck ] ); if ( 'NULL' === $cv ) { return 'NULL'; } if ( ! is_int( $cv ) ) { return null; } $num = $cv; } } elseif ( is_int( $tok[ $p ][0] ) && T_STRING === $tok[ $p ][0] ) { $cn = (string) $tok[ $p ][1]; if ( isset( $gp_uconst_int[ $cn ] ) ) { $num = (int) $gp_uconst_int[ $cn ]; } elseif ( isset( $gp_uconst[ $cn ] ) ) { $cv = $gp_num_coerce( $gp_uconst[ $cn ] ); if ( 'NULL' === $cv ) { return 'NULL'; } if ( ! is_int( $cv ) ) { return null; } $num = $cv; } } if ( null === $num ) { return null; } return $neg ? -$num : $num; }; // ACG-149-115 (round 17, R16-003/004): resolve an array_splice REPLACEMENT operand to array( element_count, // position => dangerous value ) or null. Accepts an inline literal, a bareword/class ARRAY CONSTANT, a variable // holding a known literal array, or a scalar (one element). A dangerous value may itself be a NESTED map, which is // what makes `array_splice($cb,0,1,[["system"]]); $cb[0][0](…)` resolve (R16-004). $gp_repl_spec = null; $gp_rs_depth = 0; // ACG-149-119: $gp_arr_replay can re-enter $gp_repl_spec through a splat; bound the cycle $gp_repl_spec = static function ( $p ) use ( &$tok, $n, $is_char, &$gp_arr_layout, &$gp_scan_arr_danger, &$gp_const_arr, &$gp_const_lay, &$gp_cconst_arr, &$gp_cconst_lay, &$gp_class_of, &$gp_arr_whole, &$gp_arr_danger, &$resolve_name, &$danger_name, &$gp_cls_str, &$gp_uconst, &$gp_class_ref, &$gp_arr_replay, &$gp_rs_depth ) { if ( $p < 0 || $p >= $n ) { return null; } if ( $is_char( $tok[ $p ], '[' ) || ( is_int( $tok[ $p ][0] ) && T_ARRAY === $tok[ $p ][0] ) ) { $lay = $gp_arr_layout( $p ); if ( null === $lay ) { return null; } $dg = $gp_scan_arr_danger( $p ); $out = array(); foreach ( $lay[0] as $pos => $ky ) { if ( isset( $dg[ $ky ] ) ) { $out[ $pos ] = $dg[ $ky ]; } } return array( count( $lay[0] ), $out ); } // ACG-149-117 (round 18, R17-001): `constant("R")` / `constant("C::A")` returning an ARRAY. The engine resolves // constant() at several other sites, but this slot never asked it. Must come BEFORE the bareword branch, whose // `(`-exclusion would otherwise skip it silently. if ( is_int( $tok[ $p ][0] ) && ( T_STRING === $tok[ $p ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $p ][0] ) ) && 'constant' === ltrim( strtolower( (string) $tok[ $p ][1] ), chr( 92 ) ) && $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) { $cnm = $gp_cls_str( $p + 2 ); if ( '' === $cnm && $p + 3 < $n && is_int( $tok[ $p + 2 ][0] ) && T_STRING === $tok[ $p + 2 ][0] && $is_char( $tok[ $p + 3 ], ')' ) && isset( $gp_uconst[ (string) $tok[ $p + 2 ][1] ] ) ) { $cnm = (string) $gp_uconst[ (string) $tok[ $p + 2 ][1] ]; // constant(RN) where RN is a known constant } if ( '' !== $cnm ) { $cpos = strpos( $cnm, '::' ); if ( false !== $cpos ) { $clhs2 = strtolower( ltrim( substr( $cnm, 0, $cpos ), chr( 92 ) ) ); if ( 'self' === $clhs2 || 'static' === $clhs2 || 'parent' === $clhs2 ) { $cown2 = $gp_class_ref( substr( $cnm, 0, $cpos ), $p ); // ACG-149-119 (R18-003) $ck2 = ( '' === $cown2 ) ? '' : $cown2 . '::' . substr( $cnm, $cpos + 2 ); } else { $cparts = explode( chr( 92 ), $clhs2 ); $ck2 = end( $cparts ) . '::' . substr( $cnm, $cpos + 2 ); } if ( isset( $gp_cconst_lay[ $ck2 ] ) ) { $out = array(); $dg = isset( $gp_cconst_arr[ $ck2 ] ) ? $gp_cconst_arr[ $ck2 ] : array(); foreach ( $gp_cconst_lay[ $ck2 ] as $pos => $ky ) { if ( isset( $dg[ $ky ] ) ) { $out[ $pos ] = $dg[ $ky ]; } } return array( count( $gp_cconst_lay[ $ck2 ] ), $out ); } } elseif ( isset( $gp_const_lay[ $cnm ] ) ) { $out = array(); $dg = isset( $gp_const_arr[ $cnm ] ) ? $gp_const_arr[ $cnm ] : array(); foreach ( $gp_const_lay[ $cnm ] as $pos => $ky ) { if ( isset( $dg[ $ky ] ) ) { $out[ $pos ] = $dg[ $ky ]; } } return array( count( $gp_const_lay[ $cnm ] ), $out ); } } // not a known ARRAY constant -> fall through; the scalar resolver below handles constant() of a string } if ( is_int( $tok[ $p ][0] ) && T_STRING === $tok[ $p ][0] && ! ( $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) && ! ( $p + 1 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] ) ) { $cn = (string) $tok[ $p ][1]; // a bareword ARRAY constant // ACG-149-117 (round 18, R17-002): when it is NOT a known array constant, FALL THROUGH to the scalar // resolver instead of returning null. Returning null retired the entire snapshot, so `const R = "system";` // as a replacement was invisible AND every surviving dangerous slot was discarded with it. if ( isset( $gp_const_lay[ $cn ] ) ) { $out = array(); $dg = isset( $gp_const_arr[ $cn ] ) ? $gp_const_arr[ $cn ] : array(); foreach ( $gp_const_lay[ $cn ] as $pos => $ky ) { if ( isset( $dg[ $ky ] ) ) { $out[ $pos ] = $dg[ $ky ]; } } return array( count( $gp_const_lay[ $cn ] ), $out ); } } if ( $p + 2 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] ) { list( $cl, $cp ) = $gp_class_of( $p ); // a CLASS array constant if ( '' !== $cl && $cp + 1 < $n && is_int( $tok[ $cp + 1 ][0] ) && T_STRING === $tok[ $cp + 1 ][0] ) { $ck = $cl . '::' . (string) $tok[ $cp + 1 ][1]; if ( isset( $gp_cconst_lay[ $ck ] ) ) { // else fall through to the scalar resolver $out = array(); $dg = isset( $gp_cconst_arr[ $ck ] ) ? $gp_cconst_arr[ $ck ] : array(); foreach ( $gp_cconst_lay[ $ck ] as $pos => $ky ) { if ( isset( $dg[ $ky ] ) ) { $out[ $pos ] = $dg[ $ky ]; } } return array( count( $gp_cconst_lay[ $ck ] ), $out ); } } } if ( is_int( $tok[ $p ][0] ) && T_VARIABLE === $tok[ $p ][0] && isset( $gp_arr_whole[ $tok[ $p ][1] ] ) ) { // ACG-149-119 (round 19, self-found FP): a SUBSCRIPT makes this a DIFFERENT array. `...$a["k"]` was // answered with the layout of `$a`, so the element count came from the wrong array and the surviving // keys were renumbered onto the wrong slots - a false positive on innocent code. Unresolvable here // (fails toward clean) until the subscript chain is modelled. if ( $p + 1 < $n && $is_char( $tok[ $p + 1 ], '[' ) ) { return null; } // ACG-149-119 (round 19, self-found FP): answer about the array AS IT IS HERE, not as it was declared. // This used the DECLARATION literal's layout, so `$r = ["a","b"]; array_pop($r); …(...$r)` still counted // two elements and shifted every surviving key one slot too far - branding a slot PHP does not even // have. $gp_arr_replay is the engine's own stateless replay of the mutations; use it and fall back to // the literal only when the replay cannot decide. $vn = $tok[ $p ][1]; $lit = (int) $gp_arr_whole[ $vn ] + 2; $lay = null; if ( $gp_rs_depth < 3 && $p - $lit < 4000 ) { $gp_rs_depth++; // the replay may re-enter here through a splat $rp = $gp_arr_replay( $vn, $lit, $p ); $gp_rs_depth--; if ( null !== $rp ) { $lay = array( $rp[0] ); } } if ( null === $lay ) { $lay = $gp_arr_layout( $lit ); } if ( null === $lay ) { return null; } $out = array(); $dg = isset( $gp_arr_danger[ $vn ] ) ? $gp_arr_danger[ $vn ] : array(); foreach ( $lay[0] as $pos => $ky ) { if ( isset( $dg[ $ky ] ) ) { $out[ $pos ] = $dg[ $ky ]; } } return array( count( $lay[0] ), $out ); } $r = $resolve_name( $p ); // a SCALAR replacement = one element if ( '' !== $r[0] && 'str' === $r[1] ) { $nm = ltrim( strtolower( trim( (string) $r[0] ) ), chr( 92 ) ); return array( 1, $danger_name( $nm ) ? array( 0 => $nm ) : array() ); } return null; }; // ACG-149-120 (round 20): does the operand starting at $start end exactly at $limit (exclusive)? False when the // argument is an EXPRESSION the resolver cannot fold, so the caller treats it as unresolvable instead of // silently answering with the first term. Shapes accepted: an optional sign, then a single token, or // `Class::CONST`, or a `constant(...)` call. $gp_operand_exact = static function ( $start, $limit ) use ( &$tok, $n, $is_char ) { $sig = array(); for ( $q = $start; $q < $limit && $q < $n; $q++ ) { if ( is_int( $tok[ $q ][0] ) && in_array( $tok[ $q ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { continue; } $sig[] = $q; if ( count( $sig ) > 8 ) { return false; } } if ( empty( $sig ) ) { return false; } $k = ( $is_char( $tok[ $sig[0] ], '-' ) || $is_char( $tok[ $sig[0] ], '+' ) ) ? 1 : 0; $rest = count( $sig ) - $k; if ( $rest < 1 ) { return false; } $first = $tok[ $sig[ $k ] ]; // `constant( ... )` - accept the whole call, whatever is inside it if ( is_int( $first[0] ) && ( T_STRING === $first[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $first[0] ) ) && 'constant' === ltrim( strtolower( (string) $first[1] ), chr( 92 ) ) && $rest >= 3 && $is_char( $tok[ $sig[ $k + 1 ] ], '(' ) && $is_char( $tok[ $sig[ count( $sig ) - 1 ] ], ')' ) ) { return true; } if ( 1 === $rest ) { return true; } // a single literal / variable / bareword // `-0.0` / `+1.9`: a sign plus a float literal is still ONE operand (already covered by $k above). if ( 3 === $rest && is_int( $tok[ $sig[ $k + 1 ] ][0] ) && T_DOUBLE_COLON === $tok[ $sig[ $k + 1 ] ][0] ) { return true; } // A chain of STRING LITERALS joined by `.` is not really an expression to us: $resolve_name fuses exactly // that shape (it is what makes `"sy" . "stem"` a detected callable name), so the resolver does consume all // of it. Anything else with more than one term - `LAST - 1`, `1+1`, `count($x)` - stays unresolvable. $only_concat = true; for ( $z = $k; $z < count( $sig ); $z++ ) { $want_str = ( 0 === ( $z - $k ) % 2 ); $tk = $tok[ $sig[ $z ] ]; if ( $want_str ) { if ( ! is_int( $tk[0] ) || T_CONSTANT_ENCAPSED_STRING !== $tk[0] ) { $only_concat = false; break; } } elseif ( ! $is_char( $tk, '.' ) ) { $only_concat = false; break; } } if ( $only_concat && 1 === ( $rest % 2 ) ) { return true; } return false; // anything longer is an expression }; // ACG-149-121 (round 21, R20-002): the parameter names PHP gives the mutators we model. A variadic parameter // cannot be named in PHP, so `values` never appears here - which is why push/unshift need only the target. // ACG-149-121 (round 21, self-found FP): every distinct string literal ever assigned to $vname before $upto. // Returns the single agreed name, or '' when there is none or more than one - in which case the callee is not // knowable here and the caller must fail toward clean instead of picking one. $gp_var_names = static function ( $vname, $upto ) use ( &$tok, $n, $is_char, $decode, &$resolve_name ) { $seen = array(); $from = $upto - 6000; if ( $from < 0 ) { $from = 0; } for ( $q = $from; $q < $upto && $q < $n; $q++ ) { if ( ! is_int( $tok[ $q ][0] ) || T_VARIABLE !== $tok[ $q ][0] || (string) $tok[ $q ][1] !== (string) $vname ) { continue; } $r = $q + 1; while ( $r < $upto && is_int( $tok[ $r ][0] ) && in_array( $tok[ $r ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $r++; } if ( $r >= $upto || ! $is_char( $tok[ $r ], '=' ) ) { continue; } $v = $r + 1; while ( $v < $upto && is_int( $tok[ $v ][0] ) && in_array( $tok[ $v ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $v++; } // ACG-149-122 (round 22, R21-002): ask the SHARED resolver, which folds `"array_" . "splice"` and every // other literal-concatenation spelling. Reading the raw token here made this the one callee position in // the engine that did not benefit from it. $rv = $resolve_name( $v ); if ( '' !== $rv[0] && 'str' === $rv[1] ) { $seen[ ltrim( strtolower( trim( (string) $rv[0] ) ), chr( 92 ) ) ] = true; } elseif ( $v < $upto && is_int( $tok[ $v ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $v ][0] ) { $seen[ ltrim( strtolower( trim( (string) $decode( $tok[ $v ][1] ) ) ), chr( 92 ) ) ] = true; } else { $seen['?'] = true; // assigned something we cannot read } if ( count( $seen ) > 1 ) { return ''; } } if ( 1 !== count( $seen ) ) { return ''; } $only = array_keys( $seen ); return ( '?' === $only[0] ) ? '' : $only[0]; }; $gp_mut_pnames = array( 'array_splice' => array( 'array', 'offset', 'length', 'replacement' ), 'array_shift' => array( 'array' ), 'array_pop' => array( 'array' ), 'array_push' => array( 'array' ), 'array_unshift' => array( 'array' ), // ACG-149-122 (round 22): the REORDERING family takes the array first too. Without an entry here the target // detection could not identify their argument 0, so every one of them fell into the "unreadable" arm and was // retired by name - which meant the kind-9 no-op reasoning below was never even reached. 'sort' => array( 'array', 'flags' ), 'rsort' => array( 'array', 'flags' ), 'asort' => array( 'array', 'flags' ), 'arsort' => array( 'array', 'flags' ), 'ksort' => array( 'array', 'flags' ), 'krsort' => array( 'array', 'flags' ), 'natsort' => array( 'array' ), 'natcasesort' => array( 'array' ), 'shuffle' => array( 'array' ), 'usort' => array( 'array', 'callback' ), 'uasort' => array( 'array', 'callback' ), 'uksort' => array( 'array', 'callback' ), ); // Returns array( starts, ends, saw_named ) with the arguments in POSITIONAL order, or null when the call cannot // be read (an unknown parameter name, a duplicate, or a walk that never reached the closing paren). $gp_mut_args = static function ( $callpos, $names ) use ( &$tok, $n, $is_char, $decode ) { // The opener is `(` for a real call and `[` for the ARRAY LITERAL that carries call_user_func_array's // arguments - the element list inside it is the argument list, so one walker reads both. if ( $callpos + 1 >= $n || ! ( $is_char( $tok[ $callpos + 1 ], '(' ) || $is_char( $tok[ $callpos + 1 ], '[' ) ) ) { return null; } // ACG-149-122 (round 22, R21-001): inside an ARRAY literal a named argument is written `"offset" => 0`, not // `offset: 0` - call_user_func_array turns an ASSOCIATIVE args array into a named-argument call. Same // mapping, different syntax, so it is recognised here rather than in a second parser. // ACG-149-133: $names === false means RAW ELEMENT MODE - a plain array literal whose `"k" => "v"` // pairs are elements, not named arguments. Opt-in, so every existing caller behaves exactly as before. $gp_raw = ( false === $names ); if ( $gp_raw ) { $names = array(); } $inarr = ! $gp_raw && $is_char( $tok[ $callpos + 1 ], '[' ); $starts = array(); $ends = array(); $named = false; $nextpos = 0; $d = 1; $vs = $callpos + 2; $closed = false; for ( $r = $callpos + 2; $r < $n && $r < $callpos + 400; $r++ ) { // ACG-149-121 (round 21): a PHP 8 attribute `#[` is ONE token (T_ATTRIBUTE) whose `]` still closes, so // it must count as an opener or every depth counter underflows and the index model shifts. if ( is_int( $tok[ $r ][0] ) && defined( 'T_ATTRIBUTE' ) && T_ATTRIBUTE === $tok[ $r ][0] ) { $d++; continue; } if ( $is_char( $tok[ $r ], '(' ) || $is_char( $tok[ $r ], '[' ) ) { $d++; continue; } if ( $is_char( $tok[ $r ], ')' ) || $is_char( $tok[ $r ], ']' ) ) { $d--; if ( 0 !== $d ) { continue; } $closed = true; } if ( $closed || ( 1 === $d && $is_char( $tok[ $r ], ',' ) ) ) { if ( $vs < $r ) { // first significant token of this argument $f = $vs; while ( $f < $r && is_int( $tok[ $f ][0] ) && in_array( $tok[ $f ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $f++; } $g = $f + 1; while ( $g < $r && is_int( $tok[ $g ][0] ) && in_array( $tok[ $g ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $g++; } // A parameter LABEL may be a reserved keyword: PHP tokenizes `array:` as T_ARRAY, not T_STRING, // which is exactly why the first cut of this walker matched `offset:` and missed `array:`. // Accept any single word token here and let the name lookup below decide. $isnamed = ( ! $gp_raw ) && ( $f < $r && is_int( $tok[ $f ][0] ) && in_array( $tok[ $f ][0], array( T_STRING, T_ARRAY ), true ) && $g < $r && $is_char( $tok[ $g ], ':' ) && ! ( $g + 1 < $n && $is_char( $tok[ $g + 1 ], ':' ) ) ); $label = $isnamed ? strtolower( (string) $tok[ $f ][1] ) : ''; $vstart = $isnamed ? ( $g + 1 ) : $vs; // …and the array-literal spelling of the same thing: `"offset" => 0` if ( ! $isnamed && $inarr && $f < $r && is_int( $tok[ $f ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $f ][0] && $g < $r && is_int( $tok[ $g ][0] ) && T_DOUBLE_ARROW === $tok[ $g ][0] ) { $isnamed = true; $label = strtolower( trim( (string) $decode( $tok[ $f ][1] ) ) ); $vstart = $g + 1; } if ( $isnamed ) { $named = true; $ix = array_search( $label, $names, true ); if ( false === $ix || isset( $starts[ $ix ] ) ) { return null; } // unknown or duplicate $starts[ $ix ] = $vstart; $ends[ $ix ] = $r; } else { if ( $named ) { return null; } // positional after named is not PHP while ( isset( $starts[ $nextpos ] ) ) { $nextpos++; } $starts[ $nextpos ] = $vs; $ends[ $nextpos ] = $r; $nextpos++; } } $vs = $r + 1; if ( $closed ) { break; } } } ksort( $starts ); ksort( $ends ); return array( $starts, $ends, $named, $closed ); }; // ACG-149-125 (round 24b, R24-001): $aoff shifts every argument index. `call_user_func("array_splice", $cb, 0, 1)` // puts the mutator's own arguments at positions 1..n of the SAME list, so the caller passes $aoff = 1 and the // shared walker still does the reading - no second parser. $gp_splice_apply = static function ( $keys, $callpos, $aoff = 0 ) use ( &$tok, $n, $is_char, &$gp_int_operand, &$gp_repl_spec, &$gp_operand_exact, &$gp_mut_args, &$gp_mut_pnames ) { // The opener is `(` for a direct call and `[` for the array literal carrying call_user_func_array's arguments. if ( $callpos + 3 >= $n || ! ( $is_char( $tok[ $callpos + 1 ], '(' ) || $is_char( $tok[ $callpos + 1 ], '[' ) ) ) { return null; } // ACG-149-121 (round 21, R20-002): arguments come from the SHARED walker, so a named-argument call // (`array_splice(array: $cb, offset: 0, length: 1)`) is read exactly like the positional one. The walker also // refuses a call whose closing paren it never reached - a bound that runs out is not an answer (round 19). $gp_spn = $gp_mut_pnames['array_splice']; if ( $aoff > 0 ) { // a shifted list: the leading slots belong to the WRAPPER (call_user_func's callback), not to the // mutator, so give them names the mutator can never be called with. $gp_pre = array(); for ( $gp_pi = 0; $gp_pi < $aoff; $gp_pi++ ) { $gp_pre[] = "\0wrap" . $gp_pi; } $gp_spn = array_merge( $gp_pre, $gp_spn ); } $gp_sa = $gp_mut_args( $callpos, $gp_spn ); if ( null === $gp_sa || ! $gp_sa[3] ) { return null; } // the bounds need the COMPLETE list $args = array(); $aend = array(); foreach ( $gp_sa[0] as $gp_ak => $gp_av ) { if ( $gp_ak >= $aoff ) { $args[ $gp_ak - $aoff ] = $gp_av; } } foreach ( $gp_sa[1] as $gp_ak => $gp_av ) { if ( $gp_ak >= $aoff ) { $aend[ $gp_ak - $aoff ] = $gp_av; } } // ACG-149-120 (round 20, R19-001): the LENGTH argument is OPTIONAL. PHP's default is "remove from the offset // to the END of the array" - exactly the meaning the round-18 'NULL' sentinel already carries - so an omitted // length is a COMPUTABLE case, not an unresolvable one. Demanding three arguments here retired the whole // snapshot, so `$cb = ["system"]; array_splice($cb, 1);`, which removes NOTHING, went clean. // ACG-149-121 (round 21, self-found): count POSITIONS, not keys. `array_splice(array: $cb, length: 1)` fills // slots {0,2}, so count() said 2 while $args[1] did not exist - two PHP warnings per scan, which land in the // output on a host with display_errors on. Require the slots we are about to read. if ( ! isset( $args[0] ) || ! isset( $args[1] ) ) { return null; } // need at least $var and the offset // ACG-149-115 (round 17, R16-001/002): both bounds go through the SHARED int resolver, so a NEGATIVE literal, // a constant, a class constant or a known variable all work - not just a positive T_LNUMBER. // each bound must be an operand the resolver can consume ENTIRELY - not the first term of an expression if ( ! $gp_operand_exact( $args[1], $aend[1] ) ) { return null; } if ( isset( $args[2] ) && ! $gp_operand_exact( $args[2], $aend[2] ) ) { return null; } $off = $gp_int_operand( $args[1] ); $len = isset( $args[2] ) ? $gp_int_operand( $args[2] ) : 'NULL'; // omitted length => to the end // ACG-149-121 (round 21, R20-001): `array_splice($cb, null, 1)` is offset 0 - PHP coerces null to 0 in an int // parameter. The LENGTH slot keeps its own meaning ('NULL' = to the end), so the two slots are ASYMMETRIC and // the sentinel must be read per slot. Round 20 rejected a null offset outright, which retired the snapshot. if ( 'NULL' === $off ) { $off = 0; } if ( null === $off || null === $len ) { return null; } $cnt0 = count( $keys ); $len_to_end = ( 'NULL' === $len ); // ACG-149-117 (R17-003): remove to the END if ( $len_to_end ) { $len = 0; } // PHP's own arithmetic: a negative offset counts back from the end; a negative length stops that many from the // end; both are then clamped into range. Verified against the interpreter. if ( $off < 0 ) { $off = $cnt0 + $off; if ( $off < 0 ) { $off = 0; } } if ( $off > $cnt0 ) { $off = $cnt0; } if ( $len_to_end ) { $len = $cnt0 - $off; } elseif ( $len < 0 ) { $len = $cnt0 + $len - $off; if ( $len < 0 ) { $len = 0; } } if ( $off + $len > $cnt0 ) { $len = $cnt0 - $off; } $rcnt = 0; $rmap = array(); if ( isset( $args[3] ) ) { $rs = $gp_repl_spec( $args[3] ); // ACG-149-115 (R16-003/004): the SHARED array resolver if ( null === $rs ) { return null; } $rcnt = (int) $rs[0]; $rmap = $rs[1]; } if ( $rcnt > 64 || $off > 4096 || $len > 4096 ) { return null; } $slots = array(); foreach ( $keys as $pos => $kv ) { if ( $pos < $off ) { $slots[] = $kv; } } for ( $z = 0; $z < $rcnt; $z++ ) { $slots[] = array( 'R', $z ); } foreach ( $keys as $pos => $kv ) { if ( $pos >= $off + $len ) { $slots[] = $kv; } } $new = array(); $remap = array(); $rkeys = array(); $ni = 0; foreach ( $slots as $s ) { if ( is_array( $s ) ) { $new[] = $ni; $rkeys[ $s[1] ] = $ni; $ni++; } elseif ( is_int( $s ) ) { $new[] = $ni; $remap[ 'i' . $s ] = $ni; $ni++; } else { $new[] = $s; $remap[ 's' . $s ] = $s; } // a surviving STRING key keeps its key } return array( $new, $remap, $rkeys, $ni, $rmap ); // [4] = the replacement's dangerous values BY POSITION }; // ACG-149-113 (round 15): REPLAY every layout-changing event on $vname from its literal up to $to, and return the // ordered key layout at that point - array( keys, next_auto_index ) - or null when anything is not statically // decidable. STATELESS on purpose: deriving the layout by re-reading the tokens cannot desync from the scope // stack the way a stored copy could, and a desynced layout would move a fact onto the wrong slot (a false // positive). Consistent with the append arm by construction: both start from the same literal and apply the // same auto-index rule, so `layout.next` equals `auto_next + append_count` -- but ONLY while nothing has been // REMOVED in between. ACG-149-120 (round 20): a pop/shift/splice invalidates the literal's index space // entirely, which is why both append sites now ask $gp_arr_removed first and place no fact when it says yes. // (The original wording here said "always", which was a coverage claim no test could falsify - exactly what // round 19 said never to write. It was false the moment a removal intervened.) $gp_arr_replay = null; // NOTE the &$gp_splice_apply capture: without it this closure threw "Value of type null is not callable" - an // UNCAUGHT FATAL - on any file where a splice-with-replacement was followed by another mutator on the same array. // The 807-test harness stayed green because no fixture had that COMPOSITION; only an adversarial composition // probe surfaced it. (Same lesson as "a corpus cannot gate a shape it does not contain".) $gp_arr_replay = static function ( $vname, $lit, $to ) use ( &$tok, $n, $is_char, &$gp_arr_layout, &$gp_arr_reindex, &$gp_key_at, &$gp_splice_apply, &$gp_repl_spec ) { $lay = $gp_arr_layout( $lit ); if ( null === $lay ) { return null; } list( $keys, $next ) = $lay; // ACG-149-123 (round 23): the INTERNAL POINTER, as the KEY it currently sits on. false = ran off an end // (current() returns false, so not a callable); null = unknowable, so the caller must fail clean. $ptr = empty( $keys ) ? false : $keys[0]; $steps = 0; for ( $q = $lit; $q < $to && $q < $n && $steps++ < 20000; $q++ ) { if ( ! is_int( $tok[ $q ][0] ) ) { continue; } // ACG-149-124 (round 24, self-found FP, 114 cases): SKIP a nested function / closure / arrow-fn body. // Inside one, a same-named variable is a different binding - a by-value parameter, or a fresh local - // and applying its mutations to the OUTER layout reported innocent code as critical malware. if ( T_FUNCTION === $tok[ $q ][0] || ( defined( 'T_FN' ) && T_FN === $tok[ $q ][0] ) ) { $skip = -1; if ( T_FUNCTION === $tok[ $q ][0] ) { // scan the signature to its body brace; an abstract/interface declaration ends at ';' instead. for ( $z = $q + 1; $z < $n && $z < $q + 600; $z++ ) { if ( $is_char( $tok[ $z ], ';' ) ) { $skip = $z; break; } if ( $is_char( $tok[ $z ], '{' ) ) { $bd2 = 0; for ( $y = $z; $y < $n && $y < $z + 20000; $y++ ) { if ( $is_char( $tok[ $y ], '{' ) || ( is_int( $tok[ $y ][0] ) && ( T_CURLY_OPEN === $tok[ $y ][0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $tok[ $y ][0] ) ) ) ) { $bd2++; continue; } if ( $is_char( $tok[ $y ], '}' ) ) { $bd2--; if ( 0 === $bd2 ) { $skip = $y; break; } } } break; } } } else { // an arrow function's body is ONE expression: it ends at a ',' or ';' at its own depth, or at // the bracket that closes the construct containing it. $d3 = 0; for ( $z = $q + 1; $z < $n && $z < $q + 2000; $z++ ) { if ( $is_char( $tok[ $z ], '(' ) || $is_char( $tok[ $z ], '[' ) || $is_char( $tok[ $z ], '{' ) ) { $d3++; continue; } if ( $is_char( $tok[ $z ], ')' ) || $is_char( $tok[ $z ], ']' ) || $is_char( $tok[ $z ], '}' ) ) { $d3--; if ( $d3 < 0 ) { $skip = $z - 1; break; } continue; } if ( 0 === $d3 && ( $is_char( $tok[ $z ], ',' ) || $is_char( $tok[ $z ], ';' ) ) ) { $skip = $z - 1; break; } } } if ( $skip < 0 ) { return null; } // could not bound it -> fail clean // The READ sits INSIDE that nested body while the literal is outside it: a different binding. if ( $skip >= $to ) { return null; } $q = $skip; continue; } // --- unset($var[]) : remove that key, NO renumbering --- if ( defined( 'T_UNSET' ) && T_UNSET === $tok[ $q ][0] && $q + 2 < $n && is_int( $tok[ $q + 2 ][0] ) && T_VARIABLE === $tok[ $q + 2 ][0] && (string) $tok[ $q + 2 ][1] === (string) $vname ) { if ( ! ( $q + 3 < $n && $is_char( $tok[ $q + 3 ], '[' ) ) ) { return null; } list( $uk, $ukp ) = $gp_key_at( $q + 4 ); if ( null === $uk || $ukp >= $n || ! $is_char( $tok[ $ukp ], ']' ) ) { return null; } $upos = array_search( $uk, $keys, true ); foreach ( $keys as $ki => $kv ) { if ( $kv === $uk ) { unset( $keys[ $ki ] ); break; } } $keys = array_values( $keys ); // ACG-149-123 (round 23): unsetting the element the pointer sits on ADVANCES it to the next key in // order, and past the end when it was the last one (ground-truthed - PHP does not reset it). if ( $uk === $ptr ) { $ptr = ( false !== $upos && isset( $keys[ $upos ] ) ) ? $keys[ $upos ] : false; } continue; } if ( T_VARIABLE !== $tok[ $q ][0] || (string) $tok[ $q ][1] !== (string) $vname ) { // --- ( $var , … ) --- if ( $q + 3 < $n && $is_char( $tok[ $q + 1 ], '(' ) && is_int( $tok[ $q + 2 ][0] ) && T_VARIABLE === $tok[ $q + 2 ][0] && (string) $tok[ $q + 2 ][1] === (string) $vname ) { $fn = ltrim( strtolower( (string) $tok[ $q ][1] ), chr( 92 ) ); if ( 'array_push' === $fn || 'array_unshift' === $fn || 'array_splice' === $fn ) { $d = 1; $cnt = 0; $vs = $q + 3; $off = null; $ln = null; $args = array(); for ( $r = $q + 3; $r < $n && $r < $q + 400; $r++ ) { // ACG-149-121 (round 21): a PHP 8 attribute `#[` is ONE token (T_ATTRIBUTE) whose `]` still closes, so // it must count as an opener or every depth counter underflows and the index model shifts. if ( is_int( $tok[ $r ][0] ) && defined( 'T_ATTRIBUTE' ) && T_ATTRIBUTE === $tok[ $r ][0] ) { $d++; continue; } if ( $is_char( $tok[ $r ], '(' ) || $is_char( $tok[ $r ], '[' ) ) { $d++; continue; } if ( $is_char( $tok[ $r ], ')' ) || $is_char( $tok[ $r ], ']' ) ) { $d--; if ( 0 === $d ) { if ( $vs < $r ) { $args[] = $vs; } break; } continue; } if ( 1 === $d && $is_char( $tok[ $r ], ',' ) ) { if ( $vs < $r && $vs > $q + 2 ) { $args[] = $vs; } $vs = $r + 1; } } $cnt = count( $args ); // ACG-149-118 (R17-004): expand `...$spread` to the number of elements it really contributes. $cnt = 0; foreach ( $args as $ap ) { if ( is_int( $tok[ $ap ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $ap ][0] ) { $sp2 = $gp_repl_spec( $ap + 1 ); if ( null === $sp2 ) { return null; } $cnt += (int) $sp2[0]; } else { $cnt++; } } if ( 'array_push' === $fn ) { for ( $z = 0; $z < $cnt; $z++ ) { $keys[] = $next; $next++; } // appending does NOT move the pointer (ground-truthed) } elseif ( 'array_unshift' === $fn ) { if ( $cnt < 1 || $cnt > 64 ) { return null; } $pre = array(); for ( $z = 0; $z < $cnt; $z++ ) { $pre[] = 0; } // placeholders; the reindex assigns 0..n-1 $keys = array_merge( $pre, $keys ); list( $keys, , $next ) = $gp_arr_reindex( $keys ); $ptr = empty( $keys ) ? false : $keys[0]; // unshift REINDEXES -> pointer to the start } else { // array_splice($var, off, len [, replacement]) // ACG-149-114 (round 16, R15-001): the SAME helper the mutator arm uses, so the replay and // the transform can never disagree about the replacement argument. $sp = $gp_splice_apply( $keys, $q ); if ( null === $sp ) { return null; } $keys = $sp[0]; $next = $sp[3]; $ptr = empty( $keys ) ? false : $keys[0]; // splice REINDEXES -> pointer to the start } continue; } if ( 'array_pop' === $fn ) { array_pop( $keys ); $mx = -1; foreach ( $keys as $kv ) { if ( is_int( $kv ) && $kv > $mx ) { $mx = $kv; } } $next = $mx + 1; // PHP recomputes the next index after a pop $ptr = empty( $keys ) ? false : $keys[0]; // pop RESETS the pointer (ground-truthed) continue; } if ( 'array_shift' === $fn ) { array_shift( $keys ); list( $keys, , $next ) = $gp_arr_reindex( $keys ); $ptr = empty( $keys ) ? false : $keys[0]; continue; } // the POINTER functions: contents and order untouched, only the cursor moves. if ( in_array( $fn, array( 'next', 'prev', 'reset', 'end', 'key', 'current', 'pos', 'each' ), true ) ) { if ( 'reset' === $fn ) { $ptr = empty( $keys ) ? false : $keys[0]; } elseif ( 'end' === $fn ) { $ptr = empty( $keys ) ? false : $keys[ count( $keys ) - 1 ]; } elseif ( 'each' === $fn ) { $ptr = null; } // removed in PHP 8; not worth modelling elseif ( 'next' === $fn || 'prev' === $fn ) { if ( false === $ptr ) { $ptr = false; } // already off an end: stays off elseif ( null === $ptr ) { $ptr = null; } else { $at = array_search( $ptr, $keys, true ); if ( false === $at ) { $ptr = null; } else { $at = ( 'next' === $fn ) ? $at + 1 : $at - 1; $ptr = ( $at < 0 || $at >= count( $keys ) ) ? false : $keys[ $at ]; } } } continue; } // A REORDERING of a ONE-element array cannot move anything. Two families, ground-truthed: // * KEY-PRESERVING (asort/arsort/ksort/krsort/natsort/natcasesort/uasort/uksort) - the single // key survives whatever it is, so this is a no-op for any key shape; // * REINDEXING (sort/rsort/usort/shuffle) - a single element ends up at key 0, so it is a // no-op only when the key is ALREADY int 0. `[5 => "x"]` and `["k" => "x"]` really do change // key, and remapping the danger map for that is not worth the machinery: it fails clean. // Anything longer needs PHP's real ordering semantics and stays the documented RES2201 residual. if ( 1 === count( $keys ) && ( in_array( $fn, array( 'asort', 'arsort', 'ksort', 'krsort', 'natsort', 'natcasesort', 'uasort', 'uksort' ), true ) || ( in_array( $fn, array( 'sort', 'rsort', 'usort', 'shuffle' ), true ) && isset( $keys[0] ) && 0 === $keys[0] ) ) ) { continue; } return null; // any other function taking it by reference } continue; } // --- $var[…] = … / $var[] = … --- if ( $q + 1 < $n && $is_char( $tok[ $q + 1 ], '[' ) ) { if ( $is_char( $tok[ $q + 2 ], ']' ) ) { // append if ( ! ( $q + 3 < $n && $is_char( $tok[ $q + 3 ], '=' ) ) ) { return null; } $keys[] = $next; $next++; continue; } list( $wk, $wkp ) = $gp_key_at( $q + 2 ); if ( null === $wk || $wkp >= $n || ! $is_char( $tok[ $wkp ], ']' ) ) { return null; } if ( ! ( $wkp + 1 < $n && $is_char( $tok[ $wkp + 1 ], '=' ) ) ) { continue; } // a READ, not a write if ( ! in_array( $wk, $keys, true ) ) { $keys[] = $wk; } if ( is_int( $wk ) && $wk >= $next ) { $next = $wk + 1; } continue; } if ( $q + 1 < $n && $is_char( $tok[ $q + 1 ], '=' ) && $q > $lit ) { return null; } // whole-array reassignment } return array( $keys, $next, $ptr ); }; // ACG-149-109 (round 14, R13-001): has $vname already had an element REMOVED (or been reordered) in this range? // `array_pop` is the one transform that needs the array's LENGTH (it drops the highest int key), and the length is // only derivable as "literal + appends" while nothing has been removed. If anything has, the caller retires the // snapshot instead of guessing - guessing a length would move a fact onto a slot that holds something else, i.e. // a false positive. $gp_arr_removed = static function ( $vname, $from, $to ) use ( &$tok, $n, $is_char ) { $steps = 0; for ( $q = ( $from > 0 ? $from : 0 ); $q < $to && $q < $n && $steps++ < 20000; $q++ ) { if ( ! is_int( $tok[ $q ][0] ) ) { continue; } // unset($var[...]) if ( defined( 'T_UNSET' ) && T_UNSET === $tok[ $q ][0] && $q + 2 < $n && is_int( $tok[ $q + 2 ][0] ) && T_VARIABLE === $tok[ $q + 2 ][0] && (string) $tok[ $q + 2 ][1] === (string) $vname ) { return true; } // ( $var , … ) if ( $q + 2 < $n && $is_char( $tok[ $q + 1 ], '(' ) && is_int( $tok[ $q + 2 ][0] ) && T_VARIABLE === $tok[ $q + 2 ][0] && (string) $tok[ $q + 2 ][1] === (string) $vname && in_array( ltrim( strtolower( (string) $tok[ $q ][1] ), chr( 92 ) ), array( 'array_pop', 'array_shift', 'array_splice' ), true ) ) { return true; } } return false; }; // ACG-149-091/092: resolve a SINGLE subscript key to its normalised value (int/string/const/class-const). $gp_subscript_key = static function ( $p ) use ( &$gp_key_at ) { list( $key, ) = $gp_key_at( $p ); return $key; }; // ACG-149-102 (round 11, R10-003): resolve an INLINE literal-array callable `(["system"])[0]` / // `(["x"=>"system"])["x"]` at $start (the `(`) to its dangerous leaf NAME, or '' . Called ONLY at the // callback-API / factory / Reflection argument sites (each a per-sink occurrence) - deliberately NOT in the hot // $resolve_name, where the per-operand cost timed the 6.6k-file corpus out. The `( ) [` shape is // confirmed within a bounded window before the array is scanned. A safe array scans to an empty map -> ''. $gp_inline_arr_leaf = static function ( $start ) use ( &$tok, $n, $is_char, &$gp_scan_arr_danger, &$gp_arr_descend ) { if ( $start < 0 || $start >= $n || ! $is_char( $tok[ $start ], '(' ) ) { return ''; } // skip NESTED grouping parens `((["system"]))[0]` to the array literal (one extra paren must not evade it). $as = $start; while ( $as + 1 < $n && $as < $start + 8 && $is_char( $tok[ $as ], '(' ) && $is_char( $tok[ $as + 1 ], '(' ) ) { $as++; } $arr = $as + 1; if ( $arr >= $n || ! ( $is_char( $tok[ $arr ], '[' ) || ( is_int( $tok[ $arr ][0] ) && T_ARRAY === $tok[ $arr ][0] ) ) ) { return ''; } $d = 0; $pc = -1; // matching ')' of the OUTERMOST '(' at $start for ( $ii = $start; $ii < $n && $ii < $start + 400; $ii++ ) { if ( $is_char( $tok[ $ii ], '(' ) ) { $d++; } elseif ( $is_char( $tok[ $ii ], ')' ) ) { $d--; if ( 0 === $d ) { $pc = $ii; break; } } } if ( $pc < 0 || $pc + 1 >= $n || ! $is_char( $tok[ $pc + 1 ], '[' ) ) { return ''; } $map = $gp_scan_arr_danger( $arr ); if ( empty( $map ) ) { return ''; } list( $leaf, ) = $gp_arr_descend( $map, $pc + 1 ); return ( null === $leaf ) ? '' : (string) $leaf; }; // ACG-149-123 (round 23, R22-001/R22-002): the VALUE a value-returning array function yields. // Returns array( , , ). // array_pop / end -> the LAST element in ORDER (not the highest key - a PHP array is an ordered map) // array_shift/reset -> the FIRST element in order // current -> the first element, but ONLY while the internal pointer is provably untouched // array_splice -> the REMOVED elements, as a fresh list reindexed from 0 (a trailing subscript is // descended here, so `array_splice($cb,0,1)[0]` arrives at callers as a plain name) // FP-SAFETY: the answer comes from $gp_arr_danger, which holds ONLY proven-dangerous slots. A safe element is // simply absent, so `["strlen"]` stays clean - and so does array_pop(["system","strlen"]), which really returns // "strlen" (ground-truthed against the interpreter, and it is the reviewer's own guard case). // $gp_valret_pre is why the DIRECT-invoke spelling works: the mutator arm reaches `array_pop($cb)` earlier in // the same token loop than the `(` that invokes its result, so by then the popped slot is already gone from the // live map. The arm snapshots the map as it was BEFORE its own transform, keyed by the callee token. $gp_valret_pre = array(); // ACG-149-125 (round 24b, R24-001): `$f = array_pop(...);` - PHP's first-class callable syntax. The Closure it // makes keeps the by-reference signature, so `$f($cb)` really pops $cb (interpreter-verified). Recorded as // varname => the global function it wraps. $gp_fcc_fn = array(); // ACG-149-126 (round 24c, R24B-001): the function name a CALLABLE-VALUED expression denotes. This is the // question the value-return model should have been asking all along; asking "is this token `array_pop`?" // instead is what made every round find one more spelling. // "array_pop" / "\array_pop" / "cur"."rent" -> the shared string resolver folds all of these // array_pop(...) -> PHP's first-class callable syntax // Closure::fromCallable() -> recurses, so any spelling may sit inside // new ReflectionFunction() -> ditto // $var -> a name in a variable, or a first-class callable in one // Returns a lowercased global function name, or ''. $gp_callable_name = null; $gp_callable_name = static function ( $q, $depth = 0 ) use ( &$tok, $n, $is_char, &$called_fn, &$resolve_name, &$gp_fcc_fn, &$const_str, &$gp_var_names, &$gp_cls_str, &$gp_callable_name ) { if ( $q < 0 || $q >= $n || $depth > 3 ) { return ''; } $sk = array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ); while ( $q < $n && ( $is_char( $tok[ $q ], '@' ) || ( is_int( $tok[ $q ][0] ) && in_array( $tok[ $q ][0], $sk, true ) ) ) ) { $q++; } if ( $q >= $n ) { return ''; } // a parenthesised group - unwrap one level if ( $is_char( $tok[ $q ], '(' ) ) { return $gp_callable_name( $q + 1, $depth + 1 ); } // `new ReflectionFunction(...)` - step over the keyword so the class name below is the one examined if ( is_int( $tok[ $q ][0] ) && T_NEW === $tok[ $q ][0] ) { return $gp_callable_name( $q + 1, $depth + 1 ); } // `::fromCallable(...)` handed in at the CLASS token (which is how it arrives in a // call_user_func callback slot) - step onto the method name so the check below applies. if ( is_int( $tok[ $q ][0] ) && $q + 2 < $n && is_int( $tok[ $q + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $q + 1 ][0] && is_int( $tok[ $q + 2 ][0] ) && T_STRING === $tok[ $q + 2 ][0] && 'fromcallable' === strtolower( (string) $tok[ $q + 2 ][1] ) ) { return $gp_callable_name( $q + 2, $depth + 1 ); } if ( is_int( $tok[ $q ][0] ) && T_VARIABLE === $tok[ $q ][0] ) { if ( isset( $gp_fcc_fn[ (string) $tok[ $q ][1] ] ) ) { return (string) $gp_fcc_fn[ (string) $tok[ $q ][1] ]; } if ( isset( $const_str[ (string) $tok[ $q ][1] ] ) ) { return ltrim( strtolower( (string) $gp_var_names( (string) $tok[ $q ][1], $q ) ), chr( 92 ) ); } return ''; } if ( ! is_int( $tok[ $q ][0] ) ) { return ''; } // `(...)` - a first-class callable. The `(...)` must be the WHOLE argument list. $nx = $q + 1; while ( $nx < $n && is_int( $tok[ $nx ][0] ) && in_array( $tok[ $nx ][0], $sk, true ) ) { $nx++; } if ( $nx < $n && $is_char( $tok[ $nx ], '(' ) ) { $el = $nx + 1; while ( $el < $n && is_int( $tok[ $el ][0] ) && in_array( $tok[ $el ][0], $sk, true ) ) { $el++; } if ( $el + 1 < $n && is_int( $tok[ $el ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $el ][0] && $is_char( $tok[ $el + 1 ], ')' ) ) { return ltrim( strtolower( (string) $called_fn( $q ) ), chr( 92 ) ); } // `Closure::fromCallable( )` / `new ReflectionFunction( )` - recurse on the argument // ltrim the leading `\` : `\ReflectionFunction` and `\Closure` are T_NAME_FULLY_QUALIFIED, so an // un-normalised comparison silently failed on the fully qualified spelling (331 cross-product misses). $fcn = ltrim( strtolower( (string) $tok[ $q ][1] ), chr( 92 ) ); // The class part must be PHP's OWN \Closure. Read the token directly rather than through a class // resolver: a vendor's `Vendor\Closure` is T_NAME_QUALIFIED and must NOT match, and depending on a // helper here is what made the assigned-factory spelling fail silently. $isf = ( 'fromcallable' === $fcn && $q >= 2 && is_int( $tok[ $q - 1 ][0] ) && T_DOUBLE_COLON === $tok[ $q - 1 ][0] && is_int( $tok[ $q - 2 ][0] ) && ( T_STRING === $tok[ $q - 2 ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $q - 2 ][0] ) ) && 'closure' === ltrim( strtolower( (string) $tok[ $q - 2 ][1] ), chr( 92 ) ) ); $isr = ( in_array( $fcn, array( 'reflectionfunction' ), true ) && $q >= 1 && is_int( $tok[ $q - 1 ][0] ) && T_NEW === $tok[ $q - 1 ][0] ); if ( $isf || $isr ) { return $gp_callable_name( $nx + 1, $depth + 1 ); } // ACG-149-128 (round 24e, R24D-001): ANY OTHER call may still be a literal TRANSFORM that produces the // name - strrev / base64_decode / str_rot13 / hex2bin. The shared resolver already folds those for the // dangerous-name path; returning '' here is the reason it never reached the value-return model. Same // recurring defect as always: two resolvers for one question. $tv = $resolve_name( $q ); if ( '' !== $tv[0] && 'str' === $tv[1] ) { return ltrim( strtolower( trim( (string) $tv[0] ) ), chr( 92 ) ); } return ''; } // `->getClosure()` - the Closure a Reflection factory hands back denotes the same function. // Detected by looking FORWARD from the expression start to a `-> getClosure (` at depth 0. if ( $is_char( $tok[ $q ], '(' ) ) { return $gp_callable_name( $q + 1, $depth + 1 ); } // a plain string operand - the shared resolver folds concatenation, escapes and constants $rv = $resolve_name( $q ); if ( '' !== $rv[0] && 'str' === $rv[1] ) { return ltrim( strtolower( trim( (string) $rv[0] ) ), chr( 92 ) ); } return ''; }; $gp_arr_valret = static function ( $p ) use ( &$tok, $n, $is_char, &$called_fn, &$gp_arr_danger, &$gp_arr_whole, &$gp_arr_replay, &$gp_splice_apply, &$gp_arr_descend, &$gp_valret_pre, &$gp_mut_args, &$gp_mut_pnames, &$resolve_name, &$gp_fcc_fn, &$const_str, &$gp_var_names, &$gp_callable_name, &$gp_cls_str, &$danger_name ) { $none = array( '', array(), -1 ); if ( $p < 0 ) { return $none; } // ACG-149-125 (round 24b, R24-001): step over a leading `@`. Several of these calls emit a by-reference // notice, so the attacker writes `@call_user_func("array_pop", $cb)` - and that ONE CHARACTER put the callee // where no consumer was looking, taking the whole family clean. Whitespace and comments likewise. while ( $p < $n && ( $is_char( $tok[ $p ], '@' ) || ( is_int( $tok[ $p ][0] ) && in_array( $tok[ $p ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) ) ) { $p++; } // ACG-149-126 (round 24c): consumers hand us the START of the callee expression, which for a FACTORY form is // the class token or the `(new …)` group - not the method name the factory logic below keys on. Normalise // both here, once, instead of teaching every consumer the shape. Without this the factory spellings worked // in the direct-invoke position and silently failed as a sink ARGUMENT (3,209 matrix misses, one cause). // BOUNDS FIRST: the `@`/whitespace skip above can leave $p at $n on a truncated file, and reading $tok[$p] // then emits a warning. The truncation fuzzers caught this in this very block. if ( $p + 3 >= $n ) { return $none; } if ( is_int( $tok[ $p ][0] ) && $p + 2 < $n && is_int( $tok[ $p + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p + 1 ][0] && is_int( $tok[ $p + 2 ][0] ) && T_STRING === $tok[ $p + 2 ][0] && 'fromcallable' === strtolower( (string) $tok[ $p + 2 ][1] ) ) { $p = $p + 2; } if ( $is_char( $tok[ $p ], '(' ) ) { // `(new ReflectionFunction())->invoke(` - step onto the method name. $nd0 = 0; $nc0 = -1; for ( $z = $p; $z < $n && $z < $p + 200; $z++ ) { if ( $is_char( $tok[ $z ], '(' ) ) { $nd0++; continue; } if ( $is_char( $tok[ $z ], ')' ) ) { $nd0--; if ( 0 === $nd0 ) { $nc0 = $z; break; } } } if ( $nc0 > 0 && $nc0 + 2 < $n && is_int( $tok[ $nc0 + 1 ][0] ) && T_OBJECT_OPERATOR === $tok[ $nc0 + 1 ][0] && is_int( $tok[ $nc0 + 2 ][0] ) && T_STRING === $tok[ $nc0 + 2 ][0] && in_array( strtolower( (string) $tok[ $nc0 + 2 ][1] ), array( 'invoke', 'invokeargs' ), true ) ) { $p = $nc0 + 2; $clfrom = $p; } } // NOTE the order: the `is_int` test comes AFTER the group form below, because a `(` is a CHARACTER token and // `is_int( $tok[$p][0] )` is false for it - putting the test first silently rejected every inline // first-class callable before it was ever examined. if ( $p + 3 >= $n ) { return $none; } // ACG-149-126 (round 24c): a consumer may hand us the `)` that CLOSES the callee group (the subscript arm // does, for `(array_splice(...))($cb,0,1)[0]`). Normalise it to the matching `(` so the group handler below // is reached; nothing else in the file wants a `)` here, and an unrecognised group still returns none. if ( $is_char( $tok[ $p ], ')' ) ) { $bd0 = 0; $op0 = -1; for ( $z = $p; $z >= 0 && $z > $p - 200; $z-- ) { if ( $is_char( $tok[ $z ], ')' ) ) { $bd0++; continue; } if ( $is_char( $tok[ $z ], '(' ) ) { $bd0--; if ( 0 === $bd0 ) { $op0 = $z; break; } } } if ( $op0 < 0 ) { return $none; } $p = $op0; } // `pos` is PHP's alias of current(); next/prev RETURN the element they move TO. // ACG-149-R42-001 (external review): `key` is the ONE member of this set that returns the KEY rather // than the value at the pointer. It therefore cannot share the danger-VALUE map the other nine use — // see the dedicated branch further down, and the gate it has to skip. // ACG-149-R42-002: array_key_first/array_key_last/array_keys answer the SAME question from the SAME // layout — "which key sits at this position" — and were unreachable for the same reason. $VR = array( 'array_pop', 'array_shift', 'array_splice', 'current', 'pos', 'reset', 'end', 'next', 'prev', 'key', 'array_key_first', 'array_key_last', 'array_keys' ); // ACG-149-125 (round 24b): the INLINE first-class callable, `(array_pop(...))($cb)`. Same helper, no // intermediate variable - so the group `(` is where the caller points us. Recognised here rather than in a // fourth consumer branch: $clfrom then marks where the WHOLE expression's closing paren is found. $clfrom = $p; if ( $is_char( $tok[ $p ], '(' ) ) { // ACG-149-133 (round 27, found by the matrix the reviewer asked for): this window was 40 tokens // while its two siblings a few lines above use 200 - and 40 is not enough to span a name spelled // one chr() per character. `Closure::fromCallable(chr(101).chr(110).chr(100))` (3 calls) resolved // and `...(chr(114).chr(101).chr(115).chr(101).chr(116))` (5 calls, "reset") did not, which is a // detection boundary decided by nothing but a number. 200 is chosen so it spans the LONGEST name // in either set - call_user_func_array, 20 characters, about 140 tokens as a chr() chain - and it // matches the sibling scans. The scan only runs when the callee expression is a GROUP, so the cost // is nil; it was 5 real misses in the 63,504-case matrix. $gd = 0; $gc = -1; for ( $z = $p; $z < $n && $z < $p + 200; $z++ ) { if ( $is_char( $tok[ $z ], '(' ) ) { $gd++; continue; } if ( $is_char( $tok[ $z ], ')' ) ) { $gd--; if ( 0 === $gd ) { $gc = $z; break; } } } if ( $gc < 0 || $gc + 1 >= $n || ! $is_char( $tok[ $gc + 1 ], '(' ) ) { return $none; } // ACG-149-126 (round 24c, R24B-001): whatever the group holds, ask the ONE callable-name resolver - // `(array_pop(...))`, `("array_pop")`, `("cur"."rent")`, `(Closure::fromCallable("current"))`, and any // nesting of those. Round 24b hard-coded the first-class-callable shape here and missed the rest. $inl = (string) $gp_callable_name( $p + 1 ); if ( '' === $inl || ! in_array( $inl, $VR, true ) ) { return $none; } $inlfn = $inl; $p = $gc; $clfrom = $gc; // the argument list opens right after the group } $inlfn = isset( $inlfn ) ? $inlfn : ''; $aoffx = 0; $acpx = -1; // Only for the ordinary forms: when the inline group matched, $p is now that group's `)` - a CHARACTER // token - and the name has already been resolved from inside it. if ( '' === $inlfn && ! is_int( $tok[ $p ][0] ) ) { return $none; } $skip = array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ); // ACG-149-124 (round 24, R23-002): the EFFECTIVE callee name and the position whose next token opens the // argument list - for a direct call they are just the resolved builtin and $p. Then argument 0 comes from // the SHARED walker $gp_mut_args, which has understood named arguments and call_user_func_array's array // literal since round 21. Round 23's own textual walk here understood neither. // ACG-149-126 (round 24c, R24B-001): the callee may be a FACTORY whose result is invoked directly - // `Closure::fromCallable("array_pop")($cb)` - or a Reflection invoke - `(new ReflectionFunction("current")) // ->invoke($cb)`. In both, the token at $p already sits right before the argument list, so only the NAME // has to be read differently. if ( '' === $inlfn && is_int( $tok[ $p ][0] ) ) { $lc = strtolower( (string) $tok[ $p ][1] ); if ( 'fromcallable' === $lc && $p >= 2 && is_int( $tok[ $p - 1 ][0] ) && T_DOUBLE_COLON === $tok[ $p - 1 ][0] ) { // `Closure::fromCallable()` - the group after it is fromCallable's OWN argument list, so // the helper's arguments start after that list closes. // Read the class token DIRECTLY, exactly as $gp_callable_name does. Going through a class resolver // here is why the callback-slot spelling failed while the direct-invoke one worked - two checks for // one question, and only one of them answered it. A vendor's Vendor\Closure is T_NAME_QUALIFIED // and correctly does not match. $gp_fcok = ( $p >= 2 && is_int( $tok[ $p - 2 ][0] ) && ( T_STRING === $tok[ $p - 2 ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $p - 2 ][0] ) ) && 'closure' === ltrim( strtolower( (string) $tok[ $p - 2 ][1] ), chr( 92 ) ) ); if ( $gp_fcok && $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) { $fd = 0; $fc = -1; for ( $z = $p + 1; $z < $n && $z < $p + 200; $z++ ) { if ( $is_char( $tok[ $z ], '(' ) ) { $fd++; continue; } if ( $is_char( $tok[ $z ], ')' ) ) { $fd--; if ( 0 === $fd ) { $fc = $z; break; } } } $cand2 = ( $fc > 0 ) ? (string) $gp_callable_name( $p + 2 ) : ''; if ( '' !== $cand2 && in_array( $cand2, $VR, true ) && $fc + 1 < $n && $is_char( $tok[ $fc + 1 ], '(' ) ) { $inlfn = $cand2; $p = $fc; $clfrom = $fc; } } } elseif ( in_array( $lc, array( 'invoke', 'invokeargs' ), true ) && $p >= 1 && is_int( $tok[ $p - 1 ][0] ) && T_OBJECT_OPERATOR === $tok[ $p - 1 ][0] ) { // `(new ReflectionFunction())->invoke()` - ReflectionFunction::invoke passes BY // VALUE, which is why the pointer rules for a by-value wrapper apply (see next/prev below). $rb = $p - 2; while ( $rb > 0 && is_int( $tok[ $rb ][0] ) && in_array( $tok[ $rb ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $rb--; } if ( $rb > 0 && $is_char( $tok[ $rb ], ')' ) ) { $rd = 0; $ro = -1; for ( $z = $rb; $z >= 0 && $z > $rb - 200; $z-- ) { if ( $is_char( $tok[ $z ], ')' ) ) { $rd++; continue; } if ( $is_char( $tok[ $z ], '(' ) ) { $rd--; if ( 0 === $rd ) { $ro = $z; break; } } } $cand3 = ( $ro >= 0 ) ? (string) $gp_callable_name( $ro + 1 ) : ''; if ( '' !== $cand3 && in_array( $cand3, $VR, true ) ) { $inlfn = $cand3; $aoffx = 1; // ACG-149-127 (round 24d, R24C-003): invokeArgs takes its arguments inside an ARRAY LITERAL, // exactly like call_user_func_array - so point the shared walker at the token before its `[`. if ( 'invokeargs' === $lc && $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) { $ia = $p + 2; while ( $ia < $n && is_int( $tok[ $ia ][0] ) && in_array( $tok[ $ia ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $ia++; } if ( $ia < $n && $is_char( $tok[ $ia ], '[' ) ) { $acpx = $ia - 1; } } } } } } $fn = ( '' !== $inlfn ) ? $inlfn : (string) $called_fn( $p ); // normalised: rejects ->method, ::method, a local shadow, an import $acp = $p; $aoff = 0; // ACG-149-125 (round 24b, R24-001): an INDIRECT name - `$f = "array_pop"; $f($cb)` - and a FIRST-CLASS // CALLABLE - `$f = array_pop(...); $f($cb)`. The mutator arm has resolved the first since round 21 through // $gp_var_names; the value-return model simply was not asking. Both land here as a plain `$f(` call. if ( '' === $fn && is_int( $tok[ $p ][0] ) && T_VARIABLE === $tok[ $p ][0] && $p + 1 < $n && $is_char( $tok[ $p + 1 ], '(' ) ) { $vf = (string) $tok[ $p ][1]; $cand = isset( $gp_fcc_fn[ $vf ] ) ? $gp_fcc_fn[ $vf ] : ''; if ( '' === $cand && isset( $const_str[ $vf ] ) ) { // $gp_var_names returns the ONE name every literal assignment agrees on, as a STRING - or '' when // they disagree or one of them is unreadable. (It is not a map; reading it as one is why the // `$f = "array_pop"` spelling stayed clean on the first cut of this fix.) $cand = (string) $gp_var_names( $vf, $p ); } if ( '' !== $cand ) { $fn = ltrim( strtolower( $cand ), chr( 92 ) ); } } // …and `call_user_func("array_pop", $cb, …)`, whose arguments are this call's arguments 1..n. if ( 'call_user_func' === $fn ) { $cuf = $gp_mut_args( $p, array( 'callback' ) ); if ( null === $cuf || ! isset( $cuf[0][0] ) ) { return $none; } $cn = (string) $gp_callable_name( (int) $cuf[0][0] ); if ( ! in_array( $cn, $VR, true ) ) { return $none; } $fn = $cn; $acp = $p; $aoff = 1; } if ( 'call_user_func_array' === $fn ) { $cua = $gp_mut_args( $p, array( 'callback', 'args' ) ); if ( null === $cua || ! isset( $cua[0][0] ) || ! isset( $cua[0][1] ) ) { return $none; } $cn = (string) $gp_callable_name( (int) $cua[0][0] ); $ab = (int) $cua[0][1]; while ( $ab < $n && is_int( $tok[ $ab ][0] ) && in_array( $tok[ $ab ][0], $skip, true ) ) { $ab++; } // the real arguments live in the ARRAY LITERAL: point the walker at the token before its `[`. if ( ! in_array( $cn, $VR, true ) || $ab >= $n || ! $is_char( $tok[ $ab ], '[' ) ) { return $none; } $fn = $cn; $acp = $ab - 1; } if ( ! in_array( $fn, $VR, true ) ) { return $none; } if ( $acpx >= 0 ) { $acp = $acpx; } // invokeArgs: the walker reads the ARRAY literal, not the call $pn = isset( $gp_mut_pnames[ $fn ] ) ? $gp_mut_pnames[ $fn ] : array( 'array' ); if ( $aoff > 0 ) { $pre = array(); for ( $pi = 0; $pi < $aoff; $pi++ ) { $pre[] = "\0wrap" . $pi; } $pn = array_merge( $pre, $pn ); } $ma = $gp_mut_args( $acp, $pn ); if ( null === $ma || ! isset( $ma[0][ $aoff ] ) || ! isset( $ma[1][ $aoff ] ) ) { return $none; } $a = (int) $ma[0][ $aoff ]; // skip whitespace and a leading `&` - call_user_func_array passes the array BY REFERENCE, and in PHP 8 that // `&` is T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, not the character '&' (the round-21 trap). $amp = $skip; foreach ( array( 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG' ) as $an ) { if ( defined( $an ) ) { $amp[] = constant( $an ); } } while ( $a < $n && ( $is_char( $tok[ $a ], '&' ) || ( is_int( $tok[ $a ][0] ) && in_array( $tok[ $a ][0], $amp, true ) ) ) ) { $a++; } if ( $a >= $n || ! is_int( $tok[ $a ][0] ) || T_VARIABLE !== $tok[ $a ][0] ) { return $none; } $vn = (string) $tok[ $a ][1]; // The argument must be NOTHING BUT that variable. A subscripted or property target ($cfg[0], $o->l) is a // DIFFERENT array, and modelling it as the base is exactly the false positive round 20 shipped. $ma[1][0] // is the token that CLOSED argument 0, so "the next token IS the closer" is the whole test. $b = $a + 1; while ( $b < $n && is_int( $tok[ $b ][0] ) && in_array( $tok[ $b ][0], $skip, true ) ) { $b++; } if ( $b !== (int) $ma[1][ $aoff ] ) { return $none; } $dmap = isset( $gp_valret_pre[ $p ] ) ? $gp_valret_pre[ $p ] : ( isset( $gp_arr_danger[ $vn ] ) ? $gp_arr_danger[ $vn ] : null ); // ACG-149-R42-001/002: this line is exactly where the KEY-returning family used to die. $dmap holds the // array's dangerous VALUES, and for `["system" => 1]` it is EMPTY — the only string in that array is the // KEY. The value-reading members of $VR genuinely need a non-empty value map; these four need the key // LAYOUT instead, and the replay below produces that whether or not any value is dangerous. // (Written first as `'key' !== $fn`, which left the three siblings failing at this very line while their // own branches sat unreachable below — the fix has to name the whole family, not the one case tested.) $gp_keyfn = array( 'key', 'array_key_first', 'array_key_last', 'array_keys' ); if ( ! in_array( $fn, $gp_keyfn, true ) && ( ! is_array( $dmap ) || empty( $dmap ) ) ) { return $none; } if ( ! isset( $gp_arr_whole[ $vn ] ) || $p - (int) $gp_arr_whole[ $vn ] >= 2000 ) { return $none; } $lit = (int) $gp_arr_whole[ $vn ] + 2; $lay = $gp_arr_replay( $vn, $lit, $p ); if ( null === $lay || empty( $lay[0] ) ) { return $none; } $keys = $lay[0]; $cd = 0; $cl = -1; // the ')' that closes THIS call for ( $z = $clfrom + 1; $z < $n && $z < $clfrom + 400; $z++ ) { if ( $is_char( $tok[ $z ], '(' ) || $is_char( $tok[ $z ], '[' ) ) { $cd++; continue; } if ( $is_char( $tok[ $z ], ')' ) || $is_char( $tok[ $z ], ']' ) ) { $cd--; if ( 0 === $cd ) { $cl = $z; break; } } } if ( $cl < 0 ) { return $none; } // ───────────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R42-001 (external review, HIGH) — key() RETURNS THE KEY, AND THE KEY CAN BE THE NAME. // // $cb = ["system" => 1]; reset($cb); call_user_func(key($cb), $_POST["cmd"]); // // really runs system($_POST["cmd"]), and this engine reported nothing. The cause was not the // pointer model — that has tracked the ordered KEY list and the internal cursor since round 23 — // it was that nothing ever asked it the KEY question. Every other member of $VR reads a VALUE, so // the whole arm was gated on the dangerous-VALUE map, and in this shape the dangerous string is // the key while the value is the integer 1. Six spellings were affected: reset/end/next combined // with key(), bare and through call_user_func, plus the no-pointer-call form (a fresh array's // cursor is already on the first element) and `$x = key($cb); $x(...)`. // // GROUND-TRUTHED against the real interpreter before a line of this was written, because three of // the rules are not guessable and one of them is a trap: // · a FRESH array's pointer sits on the first element, so key() answers with no reset() at all; // · off either end key() is NULL — and, unlike next()/prev(), a BY-VALUE copy does NOT rescue // it. Measured: after the cursor runs off, call_user_func('next', $a) returns the SECOND // element while call_user_func('key', $a) returns NULL. The $byval reset a few lines below is // therefore deliberately NOT reused here; copying that rule across would have invented a // finding out of an expression that evaluates to null. // · a numeric-string key IS an int key ("7" => x makes key() return int 7 — $gp_arr_layout // already models exactly this), and an int is not callable at all ("Value of type int is not // callable"), so only a non-empty STRING key can ever name a function. // // Returning a key that is NOT dangerous is safe by construction: all seven consumers of this // helper pass the result through $danger_name() before it can become a finding, so a config array // like ["home_url" => 1] resolves and is then discarded exactly like any other harmless name. if ( 'key' === $fn ) { if ( ! isset( $lay[2] ) || null === $lay[2] || false === $lay[2] ) { return $none; } if ( ! is_string( $lay[2] ) || '' === $lay[2] ) { return $none; } return array( (string) $lay[2], array(), $cl + 1 ); } // ACG-149-R42-002 (SELF-FOUND, by probing key()'s siblings the moment R42-001 was closed): three more // helpers ask the same question of the same layout — "which KEY is at this position" — and all three // were unreachable for the same reason. array_key_first/array_key_last were admitted to the pure-literal // builder table back in round 38, so `array_key_first(["system" => 1])` with a LITERAL argument already // resolved and looked covered; the VARIABLE form did not, and a variable is what real code writes. That // is the same trap as R42-001 in a different costume: a fixture proving the easy spelling works, while // the spelling an attacker would actually use went to a code path nobody had wired up. // Unlike key() these three ignore the internal pointer entirely, so they need nothing the replay has // not already computed. Their DELIBERATE limits, so the next reviewer gets an answer instead of a round: // · an INT key is not callable, so only a non-empty string key is returned (same rule as key()); // · array_keys($a, $filter) returns only the keys whose VALUE matches — a different function — so // only the single-argument form is accepted, tested on the token that closed argument 0; // · the returned map is filtered to DANGEROUS keys only, which keeps $gp_arr_danger's invariant // ("this map holds dangerous names") intact when a consumer stores it against a variable. // STILL OUT, and these are decisions rather than gaps: `foreach ($cb as $k => $v) { $k(...); }` needs // per-iteration bindings and the replay is straight-line by construction (RES2306); array_flip needs a // value→key inversion model; and an array reaching the read through a CONSTANT is the $gp_const_arr // axis, not this one. Each would be new machinery, which rule 4 of the boundary test excludes. if ( 'array_key_first' === $fn || 'array_key_last' === $fn ) { $kk = ( 'array_key_last' === $fn ) ? $keys[ count( $keys ) - 1 ] : $keys[0]; if ( ! is_string( $kk ) || '' === $kk ) { return $none; } return array( $kk, array(), $cl + 1 ); } if ( 'array_keys' === $fn ) { if ( (int) $ma[1][ $aoff ] !== $cl ) { return $none; } // a 2nd/3rd argument means a FILTERED subset $map = array(); foreach ( $keys as $pos => $kv ) { if ( is_string( $kv ) && '' !== $kv && $danger_name( ltrim( strtolower( trim( $kv ) ), chr( 92 ) ) ) ) { $map[ $pos ] = $kv; } } if ( empty( $map ) ) { return $none; } if ( $cl + 1 < $n && $is_char( $tok[ $cl + 1 ], '[' ) ) { list( $lf, $de ) = $gp_arr_descend( $map, $cl + 1 ); return ( null !== $lf && is_string( $lf ) ) ? array( (string) $lf, array(), $de ) : $none; } return array( '', $map, $cl + 1 ); } if ( 'array_splice' === $fn ) { $sp = $gp_splice_apply( $keys, $acp, $aoff ); // the SAME helper the mutator arm uses if ( null === $sp ) { return $none; } $map = array(); $ix = 0; foreach ( $keys as $kv ) { $id = ( is_int( $kv ) ? 'i' : 's' ) . $kv; if ( isset( $sp[1][ $id ] ) ) { continue; } // it survived: no remap entry means REMOVED // ACG-149-123 (round 23, FOUND BY THIS ROUND'S OWN MATRIX - 18 false positives): the array // array_splice RETURNS is not a plain list. It PRESERVES STRING KEYS and renumbers only the // INTEGER ones, from 0, in order of appearance (ground-truthed: removing 'b'=>x then 0=>y yields // ['b'=>x, 0=>y], so [0] is the SECOND element, not the first). Reindexing everything moved the // fact onto the wrong slot and branded an innocent esc_html call critical - the round-15 lesson, // "a PHP array is an ORDERED MAP", recurring on the RETURN value this time. $nk = is_int( $kv ) ? $ix++ : $kv; if ( isset( $dmap[ $kv ] ) && is_string( $dmap[ $kv ] ) ) { $map[ $nk ] = $dmap[ $kv ]; } } if ( empty( $map ) ) { return $none; } if ( $cl + 1 < $n && $is_char( $tok[ $cl + 1 ], '[' ) ) { list( $lf, $de ) = $gp_arr_descend( $map, $cl + 1 ); return ( null !== $lf && is_string( $lf ) ) ? array( (string) $lf, array(), $de ) : $none; } return array( '', $map, $cl + 1 ); } if ( 'current' === $fn || 'pos' === $fn ) { // current() (and its alias pos()) reads the INTERNAL POINTER: `next($cb); current($cb)` really returns // the SECOND element. The replay tracks the pointer as a KEY - false means it ran off an end (current() // is then false, not a callable) and null means unknowable; both fail toward clean. if ( ! isset( $lay[2] ) || null === $lay[2] || false === $lay[2] || ! isset( $dmap[ $lay[2] ] ) ) { return $none; } return is_string( $dmap[ $lay[2] ] ) ? array( (string) $dmap[ $lay[2] ], array(), $cl + 1 ) : $none; } if ( 'next' === $fn || 'prev' === $fn ) { // ACG-149-125 (round 24b, found by the widened matrix): call_user_func passes the array BY VALUE, and // COPYING an array whose internal pointer has run off an end RESETS the copy's pointer to the first // element. So `next($cb); next($cb); @call_user_func("next", $cb)` really returns the SECOND element, // not false (ground-truthed). Only the by-value wrapper behaves this way - call_user_func_array and the // first-class callable both pass by reference and keep the caller's pointer. $byval = ( $aoff > 0 ) || ! empty( $aoffx ); if ( $byval && isset( $lay[2] ) && false === $lay[2] && ! empty( $keys ) ) { $lay[2] = $keys[0]; } // ACG-149-124 (round 24, R23-001): next()/prev() MOVE the pointer and return the element they land on - // so `$cb = ["strlen","system"]; next($cb)(…)` really invokes "system" (interpreter-verified). Running // off either end returns false, which is not a callable, so that fails clean. if ( ! isset( $lay[2] ) || null === $lay[2] || false === $lay[2] ) { return $none; } $at = array_search( $lay[2], $keys, true ); if ( false === $at ) { return $none; } $at = ( 'next' === $fn ) ? $at + 1 : $at - 1; if ( $at < 0 || $at >= count( $keys ) ) { return $none; } $nk = $keys[ $at ]; if ( ! isset( $dmap[ $nk ] ) || ! is_string( $dmap[ $nk ] ) ) { return $none; } return array( (string) $dmap[ $nk ], array(), $cl + 1 ); } $key = in_array( $fn, array( 'array_pop', 'end' ), true ) ? $keys[ count( $keys ) - 1 ] : $keys[0]; if ( ! isset( $dmap[ $key ] ) || ! is_string( $dmap[ $key ] ) ) { return $none; } return array( (string) $dmap[ $key ], array(), $cl + 1 ); }; $tainted = array(); // current scope's tainted var-name set $gp_taint_pos = array(); // ACG-149-081 (siege 14 #2): token index of each var's most-recent DIRECT taint, for arr-lit-vs-taint recency $gp_arr_whole = array(); // ACG-149-081 (siege 14 #2): token index of each var's most-recent WHOLE `= array()` assignment (REPLACES value; element writes excluded) $gp_classes = array(); // ACG-149-082 (siege 15): [start_brace_idx, end_brace_idx] per class/trait/interface body - for CLASS-SCOPED property taint (a same-named field in an unrelated class must not poison it) $gp_req_props = array(); // ACG-149-081 (siege 14 #1): property/static FIELD names ever assigned request data ANYWHERE in the file - class-scoped taint that crosses methods (a ctor writes $this->h=$_REQUEST, another method dispatches it) $gp_str_prefix = array(); // ACG-149-081 (siege 14 #3): leading LITERAL of an interpolated string assignment ($addr="tcp://$ip:$port"), for the fopen-socket resolver // ACG-139-001 (reviewer 2, 2026-07-17): var-names holding a DANGEROUS CALLABLE produced by a // callable factory — `$f = Closure::fromCallable('system')`. Separate from $tainted: the value is // not request-derived, it IS a command-execution function. See the fromCallable arm below. $danger_cb = array(); $gp_sock_var = array(); $gp_sock_data = array(); // ACG-148-005: reverse-shell links (socket handle / socket-read data) // ACG-149-130 (FP round, self-found): var-names whose value provably CANNOT be a dangerous global // function name, because it was assembled with a literal part no dangerous name contains. A // DEMOTION fact, in the same family as $gp_arr_lit - see the walker and the emit gate below. $gp_bound_nm = array(); $bnm_scopes = array(); /** * ACG-149-130c: is $v's name bound RIGHT NOW? The map stores the TOKEN INDEX of the assignment that * proved the bound, and every write this engine models stamps $gp_taint_pos. So a bound that predates * the variable's most recent taint is a fact about a value that no longer exists, and must not demote: * $fn = "su_ajax_" . $_POST['x']; list( $fn ) = array( $_POST['f'] ); $fn( $_POST['a'] ); * The list()/foreach-as/by-ref-out-param arms never touch $gp_bound_nm, and they do not have to - one * comparison at the consumer covers all of them, and any future taint site for free. */ $gp_name_bound = static function ( $v ) use ( &$gp_bound_nm, &$gp_taint_pos ) { if ( ! isset( $gp_bound_nm[ $v ] ) ) { return false; } if ( isset( $gp_taint_pos[ $v ] ) && (int) $gp_taint_pos[ $v ] > (int) $gp_bound_nm[ $v ] ) { return false; } return true; }; /** * Does the assignment RHS starting at token $p provably bound the resulting NAME? * * True only when the RHS is a pure CONCATENATION / INTERPOLATION - which is the one expression * shape where every literal part is guaranteed to survive into the result as a substring - AND at * least one of those literal parts is a string no dangerous name contains ($gp_lit_bounds). * * Everything else returns false, and the list of "everything else" is the load-bearing part: * - a ternary / ?: / ?? does NOT preserve its parts (`$fn = $x ? "su_" : $_POST['f']`) * - a nested CALL's literals are its arguments, not the result (`substr("XXXsystem",3)`) * - a literal carrying a BACKSLASH is not its own runtime value (`"\x73\x79\x73tem"` is "system") * so each of those keeps the callee unbounded and the finding stays malware. Bailing out is always * the reporting direction, which is why an unrecognised operator bails rather than continues. */ // token types that may appear at depth 0 of a pure concatenation / interpolation without changing the // guarantee that every literal part survives into the result. Anything NOT here bails the walker. $gp_conc_tok = array( T_VARIABLE, T_STRING, T_NS_SEPARATOR, T_WHITESPACE, T_COMMENT, T_DOC_COMMENT, T_OBJECT_OPERATOR, T_DOUBLE_COLON, T_LNUMBER, T_DNUMBER, T_ARRAY, T_START_HEREDOC, T_END_HEREDOC ); foreach ( array( 'T_NAME_QUALIFIED', 'T_NAME_FULLY_QUALIFIED', 'T_NAME_RELATIVE', 'T_NULLSAFE_OBJECT_OPERATOR', 'T_NUM_STRING', 'T_STRING_VARNAME' ) as $gp_ctn ) { if ( defined( $gp_ctn ) ) { $gp_conc_tok[] = constant( $gp_ctn ); } } // PERF (ACG-149-130e): keyed, not scanned. This walker runs on EVERY `$v = …` assignment, so a // 19-element in_array() per token was measurable (+7.3% on a file that is nothing but dispatchers); // an isset() on a flipped map is O(1) and gives it back. My own standing rule is that resolvers // belong at SINK sites, not on a per-assignment path - this is the next best thing, because the // `.=` accumulation and the transitive-variable bound both need the fact built as we go. $gp_conc_tok = array_flip( $gp_conc_tok ); // these OPEN a group inside a double-quoted string; their '}' must find a matching increment $gp_conc_open = array(); foreach ( array( 'T_CURLY_OPEN', 'T_DOLLAR_OPEN_CURLY_BRACES' ) as $gp_ctn ) { if ( defined( $gp_ctn ) ) { $gp_conc_open[ constant( $gp_ctn ) ] = 1; } } $gp_bound_rhs = static function ( $p ) use ( &$tok, $n, $is_char, $gp_lit_bounds, $gp_conc_tok, $gp_conc_open, &$gp_bound_nm, $gp_name_bound ) { $gp_ok = false; $gp_end = false; for ( $gp_q = $p, $gp_qd = 0, $gp_qs = 0; $gp_q < $n && $gp_qs < 400; $gp_q++, $gp_qs++ ) { $gp_qx = $tok[ $gp_q ]; // ACG-149-130c (adversarial pass on my own fix, and it is the sharpest finding of the round): // A SUBSCRIPT ON A STRING LITERAL IS NOT CONCATENATION. `"su_ajax_"[0]` is the single character // "s" - and "s" IS contained in "system", so the bound is not merely weaker, it is WRONG: // $fn = "su_ajax_"[0] . $_POST['f']; $fn( $_POST['a'] ); // runtime: "s" . "ystem" // is a one-line webshell that this walker read as bounded by "su_ajax_". An out-of-range index is // worse - `"su_ajax_"[99]` is "" (a warning, not a fatal), so the callee is ENTIRELY the request. // The whole proof rests on "every literal part survives into the result"; a subscript is exactly // the operator that breaks it, so a `[` (or the deprecated `{`) directly after ANY string literal // bails the walk. A subscript on a VARIABLE (`"su_" . $_POST['act']`) is untouched - that is the // shape the fix exists for. Decided by looking BACK at the previous significant token, so there is // no flag to keep in sync across the walker's many `continue` paths. if ( $is_char( $gp_qx, '[' ) || $is_char( $gp_qx, '{' ) ) { for ( $gp_pv = $gp_q - 1; $gp_pv >= $p; $gp_pv-- ) { $gp_pt = $tok[ $gp_pv ]; if ( is_int( $gp_pt[0] ) && ( T_WHITESPACE === $gp_pt[0] || T_COMMENT === $gp_pt[0] || T_DOC_COMMENT === $gp_pt[0] ) ) { continue; } if ( $is_char( $gp_pt, '"' ) ) { return false; } // closes an interpolated string if ( is_int( $gp_pt[0] ) && ( T_CONSTANT_ENCAPSED_STRING === $gp_pt[0] || ( defined( 'T_END_HEREDOC' ) && T_END_HEREDOC === $gp_pt[0] ) ) ) { return false; } break; } } if ( $is_char( $gp_qx, '(' ) || $is_char( $gp_qx, '[' ) || $is_char( $gp_qx, '{' ) || ( is_int( $gp_qx[0] ) && isset( $gp_conc_open[ $gp_qx[0] ] ) ) ) { $gp_qd++; continue; } if ( $is_char( $gp_qx, ')' ) || $is_char( $gp_qx, ']' ) || $is_char( $gp_qx, '}' ) ) { $gp_qd--; if ( $gp_qd < 0 ) { $gp_end = true; break; } continue; } if ( $gp_qd > 0 ) { continue; } // inside a nested group: not part of this concatenation if ( $is_char( $gp_qx, ';' ) ) { $gp_end = true; break; } if ( $is_char( $gp_qx, '.' ) || $is_char( $gp_qx, '"' ) || $is_char( $gp_qx, '$' ) ) { continue; } if ( ! is_int( $gp_qx[0] ) ) { return false; } // any other single character (?, :, +, ,) - bail if ( T_CONSTANT_ENCAPSED_STRING === $gp_qx[0] || ( defined( 'T_ENCAPSED_AND_WHITESPACE' ) && T_ENCAPSED_AND_WHITESPACE === $gp_qx[0] ) ) { $gp_ql = (string) $gp_qx[1]; if ( T_CONSTANT_ENCAPSED_STRING === $gp_qx[0] ) { $gp_ql = substr( $gp_ql, 1, -1 ); } // an escape sequence means the token text is NOT the value - "\x73ystem" IS "system" if ( false !== strpos( $gp_ql, '\\' ) ) { continue; } // ACG-149-131b (adversarial pass, CRITICAL - I had made detection WORSE): a heredoc/nowdoc // body token ALWAYS ends in a NEWLINE, so the untrimmed literal is "system" plus that newline, // which is contained in no dangerous name - and this walker therefore declared // $c = << 1, 'is_array' => 1, 'is_numeric' => 1, 'is_int' => 1, 'is_integer' => 1, 'is_bool' => 1, 'is_null' => 1, 'is_object' => 1, 'is_callable' => 1, 'is_float' => 1, 'is_double' => 1, 'is_scalar' => 1, 'is_iterable' => 1, 'ctype_digit' => 1, 'ctype_alpha' => 1, 'ctype_alnum' => 1, 'intval' => 1, 'floatval' => 1, 'doubleval' => 1, 'boolval' => 1, 'count' => 1, 'sizeof' => 1, 'strlen' => 1, 'mb_strlen' => 1, 'empty' => 1, 'isset' => 1, 'gettype' => 1 ); $gp_sock_reads = array( 'fgets' => 1, 'fgetss' => 1, 'fread' => 1, 'stream_get_contents' => 1, 'socket_read' => 1, 'fgetc' => 1, 'stream_get_line' => 1, 'socket_recv' => 1, 'stream_socket_recvfrom' => 1, 'fscanf' => 1, 'socket_recvfrom' => 1, 'fgetcsv' => 1 ); // ACG-149-039 // ACG-149-010: $_SERVER / $_ENV carry BOTH server-set filesystem roots and client-controlled // values. $is_super() cannot tell them apart, so `system("ls " . $_SERVER['DOCUMENT_ROOT'])` // was CRITICAL malware. Exempt ONLY a LITERAL server-set filesystem key - the same narrow rule // the upload arm already uses (ACG-148-004). HTTP_*/QUERY_STRING/REQUEST_URI/PATH_INFO and any // non-literal key still fire, because the exemption needs a constant string to read. $gp_srv_keys = array( 'document_root' => 1, 'context_document_root' => 1, 'script_filename' => 1, 'server_root' => 1 ); $gp_srv_path = static function ( $idx ) use ( &$tok, $n, $is_char, $gp_srv_keys ) { if ( $idx < 0 || $idx >= $n ) { return false; } $x = $tok[ $idx ]; if ( ! is_int( $x[0] ) || T_VARIABLE !== $x[0] ) { return false; } if ( '$_SERVER' !== $x[1] && '$_ENV' !== $x[1] ) { return false; } if ( $idx + 2 >= $n || ! $is_char( $tok[ $idx + 1 ], '[' ) ) { return false; } if ( ! is_int( $tok[ $idx + 2 ][0] ) || T_CONSTANT_ENCAPSED_STRING !== $tok[ $idx + 2 ][0] ) { return false; } return isset( $gp_srv_keys[ strtolower( trim( $tok[ $idx + 2 ][1], "\"'" ) ) ] ); }; $gp_remote_in = static function ( $idx ) use ( &$tok, $n, $is_char, $called_fn, $gp_sock_reads, &$gp_sock_var, &$gp_sock_data ) { if ( empty( $gp_sock_var ) && empty( $gp_sock_data ) ) { return false; } if ( $idx < 0 || $idx >= $n ) { return false; } $x = $tok[ $idx ]; // ACG-149-023: socket-derived bytes are remote input, period. escapeshellarg prevents // INJECTION but not `bash -c`/awk/pipe execution, and deciding when it is safe cannot be // completed (siege 2 found six bypasses), so a socket value reaching a sink always reports. if ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $gp_sock_data[ $x[1] ] ) ) { return true; } if ( empty( $gp_sock_var ) ) { return false; } $fnm = $called_fn( $idx ); if ( '' === $fnm || ! isset( $gp_sock_reads[ $fnm ] ) ) { return false; } $k = $idx + 2; $d = 1; $s = 0; while ( $k < $n && $d > 0 && $s++ < 200 ) { if ( $is_char( $tok[ $k ], '(' ) ) { $d++; } elseif ( $is_char( $tok[ $k ], ')' ) ) { $d--; if ( 0 === $d ) { break; } } elseif ( is_int( $tok[ $k ][0] ) && T_VARIABLE === $tok[ $k ][0] && isset( $gp_sock_var[ $tok[ $k ][1] ] ) ) { return true; } $k++; } return false; }; $scopes = array(); // stack of saved parent taint sets $cb_scopes = array(); // ACG-140-001: same, for $danger_cb $cs_scopes = array(); // ACG-147-002: same, for $const_str $als_scopes = array(); // ACG-149-124 (round 24, self-found FP): $gp_arr_whole must be scope-stacked like its sibling $gp_arr_lit - // they are written on the SAME line, but only $gp_arr_lit was saved/restored, so a same-named local array in // any nested scope re-pointed the OUTER variable's literal and the layout was read from the wrong array. $awh_scopes = array(); // ACG-149-048: same, for $gp_arr_lit $fca_scopes = array(); // ACG-149-088: same, for $gp_fc_arr $adg_scopes = array(); // ACG-149-090 (MS-004): same, for $gp_arr_danger $sk_scopes = array(); $sd_scopes = array(); // ACG-148-005 (self-review): same, for $gp_sock_var / $gp_sock_data $bd = 0; // brace depth $base = array( 0 ); // base brace depth per active scope (stack) $pending_fn = false; $pending_params = array(); // a `function(...)` whose body `{` is awaited $pending_use = array(); // ACG-149-008: its `use (...)` capture list // ACG-149-123 (round 23, self-found FP, pre-existing): which of those were captured BY REFERENCE, and the // per-scope stack of that list. A `use (&$v)` capture is the same binding, so the closure body's changes must // travel back OUT - see the write-through at the scope pop. $pending_use_ref = array(); $uref_scopes = array(); $gp_cur_uref = array(); $found = array(); $is_tainted = static function ( $e ) use ( &$tainted ) { return is_int( $e[0] ) && T_VARIABLE === $e[0] && isset( $tainted[ $e[1] ] ); }; $is_req = static function ( $x ) use ( $is_super, $is_fn, $req_read, &$tainted ) { return $is_super( $x ) || $is_fn( $x, $req_read ) || ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $tainted[ $x[1] ] ) ); }; // ACG-138-R2-02b: the former boolean $is_src was superseded by $src_level (which returns a // provenance LEVEL, not just true/false) and had no callers left, so it was removed. // ACG-138-R2-02b (reviewer 2, 2026-07-17): THE TAINT IS IN THE KEY, NOT IN THE VALUE. // // Given a '[' at $k that opens a SUBSCRIPT, return the primary VARIABLE token the subscript // reads out of, or null when that base cannot be identified. // // The distinction this exists to draw: // $control = $wp_registered_widget_controls[ $widget_id ]; // $widget_id = $_POST['widget-id'] // A request-controlled SUBSCRIPT chooses WHICH element is read. It does not choose the // element's CONTENT: the value is one of the entries the DEVELOPER registered in that array, // so it is bounded by that set — exactly the bounded-table reasoning the callee walk already // applies to `$this->handlers[$_GET['a']]()` (traversing '[' = a registered table = demote). // The read path never learned it, so one hop into a plain variable re-tainted the value and // stock WordPress core (widgets-form.php, ajax-actions.php) was reported as CRITICAL MALWARE. // // Deliberately conservative — every "I cannot tell" answer returns null, which keeps today's // taint (a false positive is what we are fixing; a false negative is not an acceptable trade): // • base is a superglobal or an already-tainted variable → NOT bounded ($data = $_POST; // $x = $data['cmd'] must stay tainted), so the caller keeps the taint. // • an ARRAY LITERAL ( $x = [ $_POST['a'] ] ) is not a subscript at all → null → taints. // • a base reached through a CALL ( foo()[$k], $this->get()[$k] ) is a return value of // unknown provenance → null → taints. $subscript_base = static function ( $k ) use ( &$tok, $is_char ) { $j = $k - 1; $guard = 0; while ( $j >= 0 && $guard++ < 200 ) { $x = $tok[ $j ]; if ( is_int( $x[0] ) && T_VARIABLE === $x[0] ) { return $x; } // $registry[ … ] / $this->p[ … ] if ( is_int( $x[0] ) && ( T_OBJECT_OPERATOR === $x[0] || T_DOUBLE_COLON === $x[0] || T_NS_SEPARATOR === $x[0] ) ) { $j--; continue; } // step over a member/static/namespace operator toward the root if ( is_int( $x[0] ) && T_STRING === $x[0] ) { // ACG-149-086 (siege-22 final review #2): a T_STRING base. If it CONTINUES a chain (preceded by // -> :: \) it is a mid-chain member name - keep walking to the root variable. Otherwise it IS the // root: a class name (Cls::SANITIZERS[$_POST['t']]) or a bare constant (MY_MAP[$_POST['t']]) - an // IMMUTABLE fixed table, so return it as a non-request base. Without this, a class-constant / define() // sanitizer or handler map keyed by a request value was returning null here, so $rhs_src tainted the // resolved callable and `$cb = self::SANITIZERS[$_POST['t']]; $cb($_POST['v'])` fired CRITICAL malware. if ( $j - 1 >= 0 && is_int( $tok[ $j - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $j - 1 ][0] || T_DOUBLE_COLON === $tok[ $j - 1 ][0] || T_NS_SEPARATOR === $tok[ $j - 1 ][0] ) ) { $j--; continue; } return $x; } if ( $is_char( $x, ']' ) ) { // $a['b'][ … ] — step over the inner group $d = 1; $j--; while ( $j >= 0 && $d > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $j ], ']' ) ) { $d++; } elseif ( $is_char( $tok[ $j ], '[' ) ) { $d--; } $j--; } continue; } return null; // '(' , '=' , ',' , anything else → unknown } return null; }; // ACG-138-R2-02b: NUMERIC/BOOLEAN CASTS DESTROY THE TAINT. // // `(int) $_GET['num']` is an integer. An integer cannot name a function, cannot carry a // quote, and cannot carry a shell metacharacter — it is WordPress's own canonical sanitiser // and every taint analyser treats it as one. Tracking it as "request data" is not caution, // it is a false positive with a chain reaction, and stock WordPress core is where it landed: // $multi_number = (int) $_GET['num']; // ← not dangerous // $control['id'] = $control['id_base'] . '-' . $multi_number; // taints ALL of $control // $control_callback = $control['callback']; // ...so the CALLBACK is "tainted" // call_user_func_array( $control_callback, $control['params'] ); // → CRITICAL MALWARE // (wp-admin/widgets-form.php:238-291. Proven by bisection to be THE load-bearing link: drop // that one line and the finding disappears.) // // Scope is deliberately tight — this governs only whether a VARIABLE becomes tainted by an // assignment. It does not touch the direct-superglobal-in-a-sink rules, which scan tokens // themselves: system( (int) $_POST['x'] ) still reports exactly as it did. $num_cast_fns = array( 'intval' => 1, 'absint' => 1, 'floatval' => 1, 'doubleval' => 1, 'boolval' => 1 ); $gp_filter_fns = array( 'apply_filters' => 1 ); $gp_compound_eq = array( T_CONCAT_EQUAL, T_PLUS_EQUAL, T_MINUS_EQUAL, T_MUL_EQUAL, T_DIV_EQUAL, T_MOD_EQUAL, T_AND_EQUAL, T_OR_EQUAL, T_XOR_EQUAL, T_SL_EQUAL, T_SR_EQUAL, T_POW_EQUAL ); // ACG-149-085 (siege 18 #11): .= += etc. if ( defined( 'T_COALESCE_EQUAL' ) ) { $gp_compound_eq[] = T_COALESCE_EQUAL; } // ACG-149-084 (siege 17 #3): result = filtered 2nd arg; 1st is the hook name, 3rd+ are context (apply_filters_ref_array packs args differently - left to the normal scan) // Given the index of a cast token (or of a numeric-cast function name), return the index of // the last token of the value it neutralises, so the caller can skip it. $skip_numeric = static function ( $k ) use ( &$tok, $n, $is_char ) { $x = $tok[ $k ]; $is_cast = is_int( $x[0] ) && in_array( $x[0], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ); $k++; if ( $k >= $n ) { return $k; } // A grouped operand — (int) ( $_GET['a'] + 1 ) — or a call's argument list: skip it whole. if ( $is_char( $tok[ $k ], '(' ) ) { $d = 1; $k++; while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $k ], '(' ) ) { $d++; } elseif ( $is_char( $tok[ $k ], ')' ) ) { $d--; } $k++; } return $k - 1; } if ( ! $is_cast ) { return $k - 1; } // intval without '(' — not a call; neutralise nothing // A cast binds tighter than any binary operator, so it neutralises exactly ONE primary: // the variable/literal plus the member/index chain hanging off it. Anything beyond that // ( (int)$_GET['a'] . $_POST['b'] ) is NOT covered and still taints — which is correct. if ( is_int( $tok[ $k ][0] ) && ( T_VARIABLE === $tok[ $k ][0] || T_STRING === $tok[ $k ][0] || T_LNUMBER === $tok[ $k ][0] || T_DNUMBER === $tok[ $k ][0] || T_CONSTANT_ENCAPSED_STRING === $tok[ $k ][0] ) ) { $k++; while ( $k < $n ) { if ( $is_char( $tok[ $k ], '[' ) || $is_char( $tok[ $k ], '(' ) ) { $open = $is_char( $tok[ $k ], '[' ) ? '[' : '('; $close = '[' === $open ? ']' : ')'; $d = 1; $k++; while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $k ], $open ) ) { $d++; } elseif ( $is_char( $tok[ $k ], $close ) ) { $d--; } $k++; } continue; } if ( is_int( $tok[ $k ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $k ][0] || T_DOUBLE_COLON === $tok[ $k ][0] ) ) { $k += 2; continue; } break; } return $k - 1; } return $k - 1; }; // ACG-138-R2-02b (reviewer 2 + adversarial review, 2026-07-17): TAINT DIRECTNESS (provenance level). // // A tainted value is DIRECT (level 1) when it flows from a superglobal / request reader through // whole-variable assignments and subscript READS of a request base. It is INDIRECT (level 2) // when its taint was deposited into a CONTAINER by an ELEMENT/PROPERTY WRITE and later read back // out. That distinction is what separates a webshell from stock WordPress core: // $f = $_POST['f']; $f($_POST['a']); // DIRECT -> malware (ACG-122) // $control['id'] = ...req...; $cb = $control['callback']; $cb(); // INDIRECT -> review item // In the second shape (wp-admin/widgets-form.php: $widget_id=$_POST[..] → explode → array_pop → // $control['id']=…$multi_number → $cb=$control['callback']) the request taint was written into one // field ('id') and a DIFFERENT field ('callback') is read back as the callee. Field-INsensitivity // conflated the two, so a CLEAN core file was reported CRITICAL MALWARE. Marking the read-back as // INDIRECT lets the callee sinks DEMOTE it to the existing review item (tk_dyn_superglobal_call) // instead of confirmed malware. // // This is a PURE DEMOTION: nothing that was clean becomes malware, so NO new false positive is // possible by construction (verified: corpus one line changed, malware→review; 0 additions). // // ACCEPTED FALSE-NEGATIVE CLASS (documented and gated; still surfaced at HIGH as a review item, // NEVER silent). An adversarial FN-hunt confirmed no DIRECT webshell demotes and no corpus malware // is lost, but corrected my first description as too narrow. The accepted class is: ANY request // value deposited into a CONTAINER FIELD by an element/property write and read back as the callee — // which covers more than the single example, all within this same mechanism: // $a['x']=$_POST['f']; $f=$a['x']; $f($_POST['y']); // intermediate variable // $h['x']=$_POST['f']; $h['x']($_POST['y']); // direct subscript-dispatch, no temp var // $o->cmd=$_POST['c']; $f=$o->cmd; $f(...); // property launder // array_map($c['cb'], $_POST['items']); // where $c['cb'] was element-written from request // Each demotes malware→review. The direct/one-hop forms ($_POST['f'](…); $f=$_POST['f']; $f(…); // multi-hop var-to-var; the directly-tainted container $data=$_POST) all STAY CRITICAL malware. // Recovering the class needs constant-key field-sensitivity (write 'id' ≠ read 'callback'), a global // taint-semantics change deferred to a corpus-first round: a pure demotion is the safest property to // ship now, and this codebase's history is of large detection changes shipping surprise FPs. $src_level = static function ( $x ) use ( $is_super, $is_fn, $req_read, $decode, &$tainted ) { if ( $is_super( $x ) || $is_fn( $x, $req_read ) ) { return 1; } if ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $tainted[ $x[1] ] ) ) { return (int) $tainted[ $x[1] ]; } if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] && false !== strpos( strtolower( $decode( $x[1] ) ), 'php://input' ) ) { return 1; } return 0; }; // scan the RHS of an assignment from $start to ';' (depth 0) — return the STRONGEST request-taint // level found (1 direct, 2 indirect, 0 none). Direct short-circuits; an indirect source is // remembered but the scan continues in case a direct source appears further along the RHS. // ACG-149-002: the RHS scan is bounded by TOTAL work per file, not per call. A per-call // cap was defeatable by padding one assignment (~150 `"".` pads hid the request source and // a `system($c)` webshell scanned clean - a regression vs v1.0.147). The DoS this defends // is O(n^2) from re-scanning the same tail once per target in a chained assignment, which // is a total-work problem; bounding the total caps the hang while letting any realistic // single RHS be scanned to its end. $gp_rhs_total = 0; // ACG-149-003: the same per-file bound for the immediately-invoked-closure arm (7b). Its // step counter is reset on every firing, so a file of nested `(function(){` - whose braces // never balance - burned the full body-scan cap once PER FIRING: O(n x 5000), measured at // 26 s for 520 KB, with no deadline check inside this function to interrupt it. $gp_cf_total = 0; // ACG-149-078 (siege 13 #3/#4/#9): a superglobal used ONLY as the immediate subscript KEY of a FIXED // developer table contributes no bytes of its own - the request merely picks WHICH developer entry runs / // is used. Bounded when the base right before the '[' is a plain variable holding an array LITERAL // ($gp_arr_lit, positive evidence), or a property / static access ($this->handlers[..], self::$h[..]) - the // same bounded-table reasoning the direct-call arm applies. A request/tainted base is NOT bounded. $gp_super_is_fixedkey = static function ( $pos ) use ( &$tok, $is_char, $is_super, &$tainted, &$gp_arr_lit, &$gp_taint_pos, &$gp_arr_whole, &$gp_req_props, &$gp_classes, $danger_name, $req_read ) { // Walk back from the super to the enclosing subscript '[', TRANSPARENTLY skipping any sanitiser/plain-fn // call wrappers around the key (ACG-149-081 siege 14 #4/#5: the WP idiom sanitize_key(wp_unslash($_POST)) // nests two calls). Then the base right before that '[' decides: a plain var holding an array LITERAL // ($gp_arr_lit, positive evidence, untainted), or a property/static table whose OBJECT/CLASS var is not // tainted (ACG-149-081 siege 14 #1: `$this->h=$_REQUEST` taints $this, so that table is NOT bounded). $gp_j = $pos - 1; $gp_d = 0; $gp_s = 0; while ( $gp_j >= 0 && $gp_s++ < 300 ) { $gp_c = $tok[ $gp_j ]; if ( $is_char( $gp_c, ')' ) || $is_char( $gp_c, ']' ) ) { $gp_d++; } elseif ( $is_char( $gp_c, '(' ) ) { if ( 0 === $gp_d ) { // ACG-149-082 (siege 15 #8): the sanitiser wrapper may be a NAMESPACED / leading-backslash global // (`\sanitize_key(..)`, `WP\clean(..)`), which PHP 8 tokenises as T_NAME_FULLY_QUALIFIED / T_NAME_QUALIFIED, // not T_STRING. Accept those too so a fully-qualified key sanitiser is skipped like the bare form. if ( $gp_j - 1 >= 0 && is_int( $tok[ $gp_j - 1 ][0] ) && ( T_STRING === $tok[ $gp_j - 1 ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $gp_j - 1 ][0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $gp_j - 1 ][0] ) ) ) { // ACG-149-083 (siege 16 ROOT C): but a super fed to a SINK wrapper (system/exec/eval/assert/ // call_user_func...) is EXECUTED by that sink, not merely sanitised into a bounded key - // `$h[\system($_POST['x'])]` runs the command. Do NOT see through a danger wrapper; report. // ACG-149-084 (siege 17 #5/#6): only a GLOBAL danger call is a sink here; a METHOD/static whose // name merely collides ($this->system(..), $db->exec(..), Foo::exec(..)) is a benign key wrapper. if ( $danger_name( $tok[ $gp_j - 1 ][1] ) && ! ( $gp_j - 2 >= 0 && is_int( $tok[ $gp_j - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_j - 2 ][0] || T_DOUBLE_COLON === $tok[ $gp_j - 2 ][0] ) ) ) { return false; } $gp_j -= 2; continue; } return false; } $gp_d--; } elseif ( $is_char( $gp_c, '[' ) ) { if ( 0 === $gp_d ) { break; } $gp_d--; } elseif ( 0 === $gp_d && ( $is_char( $gp_c, ';' ) || $is_char( $gp_c, ',' ) || $is_char( $gp_c, '{' ) || $is_char( $gp_c, '}' ) ) ) { return false; } $gp_j--; } if ( $gp_j < 1 || ! $is_char( $tok[ $gp_j ], '[' ) ) { return false; } $bp = $gp_j - 1; $gp_bt = $tok[ $bp ]; // ACG-149-085 (siege 18 #7): a NESTED-subscript base `$cfg['handlers'][$super]` - the token before the enclosing // '[' is a ']'. Walk back over the whole leading subscript chain to the ROOT variable/property, then judge THAT // (a bounded read out of `$cfg['handlers']` is exactly as bounded as out of `$cfg`). $gp_rbs = 0; while ( $bp >= 1 && $is_char( $tok[ $bp ], ']' ) && $gp_rbs++ < 100 ) { $gp_rbd = 0; while ( $bp >= 0 ) { if ( $is_char( $tok[ $bp ], ']' ) ) { $gp_rbd++; } elseif ( $is_char( $tok[ $bp ], '[' ) ) { $gp_rbd--; if ( 0 === $gp_rbd ) { $bp--; break; } } $bp--; } } // ACG-149-086 (siege 19 #8): an INLINE function/method-result base `get_option('h')[$super]` / `$o->map()[$super]` // - the token before the '[' is a ')'. The call result is NOT request-derived unless the callee is a global // request READER (filter_input/getallheaders/...), so it is a bounded table exactly like the assigned form // `$h=get_option('h'); $h[$super]` (ACG-149-084). A request-reader result stays request -> not bounded. if ( $bp >= 1 && $is_char( $tok[ $bp ], ')' ) ) { $gp_cld = 0; $gp_clj = $bp; $gp_cls2 = 0; while ( $gp_clj >= 0 && $gp_cls2++ < 4000 ) { if ( $is_char( $tok[ $gp_clj ], ')' ) ) { $gp_cld++; } elseif ( $is_char( $tok[ $gp_clj ], '(' ) ) { $gp_cld--; if ( 0 === $gp_cld ) { break; } } $gp_clj--; } if ( $gp_clj - 1 >= 0 && is_int( $tok[ $gp_clj - 1 ][0] ) && isset( $tok[ $gp_clj - 1 ][1] ) && isset( $req_read[ ltrim( strtolower( (string) $tok[ $gp_clj - 1 ][1] ), '\\' ) ] ) && ! ( $gp_clj - 2 >= 0 && is_int( $tok[ $gp_clj - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_clj - 2 ][0] || T_DOUBLE_COLON === $tok[ $gp_clj - 2 ][0] ) ) ) { return false; } // filter_input()[$super] -> request result return true; // get_option()/a method result/... is not request-derived -> bounded } if ( $bp < 0 ) { return false; } $gp_bt = $tok[ $bp ]; if ( is_int( $gp_bt[0] ) && T_VARIABLE === $gp_bt[0] ) { if ( $bp - 1 >= 0 && is_int( $tok[ $bp - 1 ][0] ) && T_DOUBLE_COLON === $tok[ $bp - 1 ][0] ) { $gp_cid = -1; foreach ( $gp_classes as $gp_cl ) { if ( $gp_cl[0] <= $pos && $pos <= $gp_cl[1] && $gp_cl[0] > $gp_cid ) { $gp_cid = $gp_cl[0]; } } // innermost enclosing class of the dispatch return ! ( $gp_cid >= 0 && isset( $gp_req_props[ $gp_cid . ':' . strtolower( (string) $gp_bt[1] ) ] ) ) && ! isset( $tainted[ $gp_bt[1] ] ); // self::$h[..] (ACG-149-082: request-tainted IN THIS CLASS is not a fixed table) } if ( $is_super( $gp_bt ) ) { return false; } // ACG-149-084 (siege 17): for `base[$super]` an UNTAINTED base is positive evidence its VALUES are not // request-derived, and the request provably controls only the KEY - so the selected value is not // attacker-chosen. This holds for the ubiquitous `$h = get_option('handlers'); call_user_func($h[$_POST['op']])` // (also a method result, a constant, a property subscript, a ternary of fixed maps) that v1.0.147 scanned // CLEAN and the aggressive v149 callee arm branded CRITICAL malware - a broad realistic FP, and inconsistent // with the direct-call arm which already treats `$fn=$h[$_POST]; $fn()` as clean. Only a TAINTED base (the // table itself carries request data) stays malware, gated below exactly as before. if ( ! isset( $tainted[ $gp_bt[1] ] ) ) { return true; } // untainted base -> the super only picks a key into a non-request table if ( ! isset( $gp_arr_lit[ $gp_bt[1] ] ) ) { return false; } // tainted, no fixed-table evidence -> not bounded // ACG-149-081 (siege 14 #2): the var is BOTH tainted and holds a fixed table. Bounded only if a WHOLE // `= array(..)` assignment (which REPLACES the value) is more recent than the taint - NOT a mere element // write, which adds one key and leaves `$h=$_POST;$h['z']='x'` fully request data. Both the whole // assignment and the direct taint are stamped with the LHS token index; if the taint came later, or no // whole assignment exists (an element-built table over a tainted base, S13a/S13b), it still fires. return isset( $gp_arr_whole[ $gp_bt[1] ] ) && isset( $gp_taint_pos[ $gp_bt[1] ] ) && $gp_arr_whole[ $gp_bt[1] ] > $gp_taint_pos[ $gp_bt[1] ]; } if ( is_int( $gp_bt[0] ) && T_STRING === $gp_bt[0] && $bp - 1 >= 0 && is_int( $tok[ $bp - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $bp - 1 ][0] || T_DOUBLE_COLON === $tok[ $bp - 1 ][0] ) ) { // property/static table. bounded ONLY if the object/class variable before -> / :: is not tainted. if ( T_OBJECT_OPERATOR === $tok[ $bp - 1 ][0] && $bp - 2 >= 0 && is_int( $tok[ $bp - 2 ][0] ) && T_VARIABLE === $tok[ $bp - 2 ][0] ) { // ACG-149-081/082 (siege 14 #1, siege 15): bounded only if the object var is untainted AND this // property NAME is never assigned request data ELSEWHERE IN THE SAME CLASS ($this->h=$_REQUEST in a // ctor, dispatched here). Class-scoped so a same-named field in an unrelated class does not poison it. $gp_cid = -1; foreach ( $gp_classes as $gp_cl ) { if ( $gp_cl[0] <= $pos && $pos <= $gp_cl[1] && $gp_cl[0] > $gp_cid ) { $gp_cid = $gp_cl[0]; } } return ! ( $gp_cid >= 0 && isset( $gp_req_props[ $gp_cid . ':' . strtolower( (string) $gp_bt[1] ) ] ) ) && ! isset( $tainted[ $tok[ $bp - 2 ][1] ] ) && ! $is_super( $tok[ $bp - 2 ] ); } return true; // Cls::CONST[..] class constant (immutable), or a longer chain - treat as bounded } return false; }; // ACG-149-082 (siege 15 #7): is the FIRST element (object/class) of an array-callable request-derived? // `array($_POST['cls'], $_POST['m'])` is `$_POST['cls']::$_POST['m']()` - an arbitrary static call, NOT a bounded // method on a fixed object. $openIdx is the '(' after `array` or the short-array '['. Scans the first element only. $gp_ac_reqbase = static function ( $openIdx ) use ( &$tok, $n, $is_char, $is_super, &$is_tainted, $is_fn, $req_read ) { // ACG-149-083 (siege 16 #5/#6): the first element is request-CONTROLLED only when a super / tainted var / // request-reader appears at the element's TOP LEVEL (depth 1). A super merely passed as an ARGUMENT to a // method/function call there (`array($this->getService($_GET['id']), 'run')`) does NOT make the resulting // object request-controlled - the class is fixed, only an argument is tainted; that stayed bounded (FP fix). // A request-reader whose RESULT is the element (`array(filter_input(INPUT_POST,'cls'), $m)`) IS request (FN fix). $j = $openIdx + 1; $depth = 1; $steps = 0; while ( $j < $n && $depth > 0 && $steps++ < 200 ) { $x = $tok[ $j ]; if ( $is_char( $x, '(' ) || $is_char( $x, '[' ) ) { $depth++; } elseif ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { $depth--; if ( 0 === $depth ) { break; } } elseif ( 1 === $depth && $is_char( $x, ',' ) ) { break; } // end of the first element elseif ( 1 === $depth && ( $is_super( $x ) || $is_tainted( $x ) // ACG-149-084 (siege 17 #4): a request-reader NAME as a METHOD/property ($this->getallheaders()) is not the // global reader; ACG-149-085 (siege 18 #6): a NAMESPACED reader (\filter_input) is T_NAME_FULLY_QUALIFIED, not T_STRING. || ( ( $is_fn( $x, $req_read ) || ( is_int( $x[0] ) && ( ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $x[0] ) ) && isset( $req_read[ ltrim( strtolower( (string) $x[1] ), '\\' ) ] ) ) ) && ! ( $j - 1 >= 0 && is_int( $tok[ $j - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $j - 1 ][0] || T_DOUBLE_COLON === $tok[ $j - 1 ][0] ) ) ) ) ) { return true; } $j++; } return false; }; $rhs_src = static function ( $start ) use ( &$gp_rhs_total, &$tok, $n, $is_char, $src_level, $is_super, $is_fn, $subscript_base, $skip_numeric, $num_cast_fns, $gp_filter_fns, $req_read, $gp_srv_path, &$tainted, $gp_super_is_cond ) { $k = $start; $d = 0; $best = 0; $gp_rhs_steps = 0; // ACG-149-032 (siege 3 #9/#20): the ACG-149-024 "closure RHS -> return 0" guard that stood // here was REVERTED. It suppressed the theoretical FP `$h = function(){ return $_POST['x']; }; // $h();` (tk_dyn_superglobal_call, a REVIEW-class id not present anywhere in the 6,637-file // corpus) at the cost of a real CRITICAL false NEGATIVE: `$h = function(){ return $_POST['c']; // }; system($h());` scanned clean. Letting rhs_src scan the body taints $h at the INDIRECT // level, so the bare `$h()` stays review-class while `system($h())` correctly fires malware - // the exact split v1.0.147 shipped. Security-first: a review-class over-report beats a missed RCE. // ACG-149-036 (siege 4 #6): a closure LITERAL RHS is fixed code, not a request-chosen callable // name, so its taint is capped at INDIRECT (level 2). `$fmt = function($x) use ($mode) {...}; // $fmt($_POST)` then reviews (tk_dyn_request_callee_var demotes on $gp_callee_indirect) instead // of branding legit WordPress closure code CRITICAL malware, while `system($fmt())` still fires. $gp_rhs_is_closure = ( $start < $n && is_int( $tok[ $start ][0] ) && ( T_FUNCTION === $tok[ $start ][0] || ( defined( 'T_FN' ) && T_FN === $tok[ $start ][0] ) || ( T_STATIC === $tok[ $start ][0] && $start + 1 < $n && is_int( $tok[ $start + 1 ][0] ) && ( T_FUNCTION === $tok[ $start + 1 ][0] || ( defined( 'T_FN' ) && T_FN === $tok[ $start + 1 ][0] ) ) ) ) ); for ( ; $k < $n; $k++ ) { // ACG-148-012 (self-review, siege [07]): BOUND the RHS scan. A CHAINED assignment // `$a = $b = $c = ... = $_POST['x']` calls $rhs_src once per target, and each call scanned // the whole tail to the ';', giving O(n^2): a 54 KB file of such a chain took ~70s — a file // a few hundred KB (still under MAX_FILE_SIZE) would hang the scan. No LEGITIMATE right-hand // side is thousands of tokens long, and a request source within a realistic RHS is found // far inside this bound; only a pathological chain (the DoS itself) reaches it, and there // returning the best level found so far is the safe disposition. This mirrors the step caps // the other arms already use. // Per call: generous, so ordinary and padded right-hand sides are scanned to the end. // Per file: hard total across every call, so the chained-assignment O(n^2) stays bounded. // ACG-149-017: exhausting this budget is NOT proof the RHS carried no request source - // an attacker pads the RHS or the chain to burn it. Flag the file so it fails visible // (a coverage notice), never a silent clean, instead of just bailing. if ( ++$gp_rhs_total > 300000 ) { self::$analysis_truncated = true; break; } // ACG-149-042 (siege 6 #10): only the per-FILE total flags. A legit large array literal is fully scanned; a real padding attack blows the file total or is memory-skipped (both fail-visible) $x = $tok[ $k ]; // ACG-138-R2-02b: an int/float/bool cast (or intval/absint/…) neutralises its operand. if ( is_int( $x[0] ) && in_array( $x[0], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) { $k = $skip_numeric( $k ); continue; } // ACG-138-R2-02b-adv (adversarial review, 2026-07-17): only the GLOBAL cast FUNCTION // sanitises. $is_fn matches a bare T_STRING by name, so `$this->intval($_POST['f'])` / // `Foo::intval(...)` — an attacker passthrough METHOD shadowing a cast name — would launder // the taint and hide a one-hop webshell (proven FN). Reject a method/static/namespaced call, // exactly as the callee sink does one block below: a real global intval( has no ->/::/\ before // it. (A fully-qualified \intval( tokenises as T_NAME_*, not T_STRING, so $is_fn already // misses it and taint survives — same-side safe.) if ( $is_fn( $x, $num_cast_fns ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && ! ( $k - 1 >= 0 && is_int( $tok[ $k - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $k - 1 ][0] || T_DOUBLE_COLON === $tok[ $k - 1 ][0] || T_NS_SEPARATOR === $tok[ $k - 1 ][0] ) ) ) { $k = $skip_numeric( $k ); continue; } // ACG-149-084 (siege 17 #3): apply_filters()/apply_filters_ref_array() RETURN their 2nd argument as // filtered by the developer's hook chain; the 1st arg is the hook NAME and the 3rd+ args are CONTEXT // passed to callbacks - none of them make the result request-derived. So `$h = apply_filters('cbs', // $fixed_map, $_POST)` is NOT request-controlled (the ubiquitous "filterable map + request context" // idiom). Evaluate ONLY the 2nd argument for a request source and skip the rest of the call. A method // /static named apply_filters is excluded (must be the global). If the 2nd arg IS a super the result // still fires. Bounded step budget; degrades to scanning the whole call if the shape is unusual. if ( $is_fn( $x, $gp_filter_fns ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && ! ( $k - 1 >= 0 && is_int( $tok[ $k - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $k - 1 ][0] || T_DOUBLE_COLON === $tok[ $k - 1 ][0] ) ) ) { $gp_fk = $k + 2; $gp_fd = 1; $gp_fc = 0; $gp_fcomma = 0; $gp_a2s = -1; $gp_a2e = -1; while ( $gp_fk < $n && $gp_fd > 0 && $gp_fc++ < 4000 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_fk ], '(' ) || $is_char( $tok[ $gp_fk ], '[' ) ) { $gp_fd++; } elseif ( $is_char( $tok[ $gp_fk ], ')' ) || $is_char( $tok[ $gp_fk ], ']' ) ) { $gp_fd--; if ( 0 === $gp_fd ) { break; } } elseif ( 1 === $gp_fd && $is_char( $tok[ $gp_fk ], ',' ) ) { $gp_fcomma++; if ( 1 === $gp_fcomma ) { $gp_a2s = $gp_fk + 1; } elseif ( 2 === $gp_fcomma ) { $gp_a2e = $gp_fk; } } $gp_fk++; } if ( $gp_a2e < 0 ) { $gp_a2e = $gp_fk; } if ( $gp_a2s >= 0 && $gp_a2s < $gp_a2e ) { for ( $gp_sk = $gp_a2s; $gp_sk < $gp_a2e; $gp_sk++ ) { $gp_st = $tok[ $gp_sk ]; // ACG-149-085 (siege 18 #12): a '[' means reading OUT of a base - the subscript KEY says WHICH // entry, not WHAT is in it - so skip the whole subscript, exactly as the main loop does. Without // this, `apply_filters('h', $a[$_POST['k']])` (a bounded read) was branded request-derived (FP). if ( $is_char( $gp_st, '[' ) ) { $gp_sd = 1; $gp_sk++; while ( $gp_sk < $gp_a2e && $gp_sd > 0 ) { if ( $is_char( $tok[ $gp_sk ], '[' ) ) { $gp_sd++; } elseif ( $is_char( $tok[ $gp_sk ], ']' ) ) { $gp_sd--; } $gp_sk++; } $gp_sk--; continue; } // ACG-149-085 (siege 18 #5): a request READER (filter_input/getallheaders/...) as the 2nd arg IS a // request source (`apply_filters('cmd', filter_input(INPUT_POST,'c'))`), which the super-only scan missed. if ( $is_super( $gp_st ) || ( is_int( $gp_st[0] ) && T_VARIABLE === $gp_st[0] && isset( $tainted[ $gp_st[1] ] ) ) || $is_fn( $gp_st, $req_read ) ) { if ( 1 > $best ) { $best = 1; } break; } } } $k = $gp_fk; // skip the whole apply_filters call continue; } if ( $is_char( $x, '[' ) ) { // ACG-138-R2-02b: reading OUT of a non-request array — the subscript says WHICH // entry, not WHAT is in it. Skip the subscript so a request-controlled key does // not masquerade as a request-controlled value. The base itself was already // tested by $src_level on a previous iteration, so a tainted/superglobal base has // returned true before we get here; re-testing it is what keeps this honest. $b = $subscript_base( $k ); if ( null !== $b && ! $is_super( $b ) && ! isset( $tainted[ $b[1] ] ) ) { $sd = 1; $k++; while ( $k < $n && $sd > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $k ], '[' ) ) { $sd++; } elseif ( $is_char( $tok[ $k ], ']' ) ) { $sd--; } $k++; } $k--; // the for-loop's k++ consumes the closing ']' continue; } $d++; continue; } if ( $is_char( $x, '(' ) ) { $d++; continue; } if ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { if ( 0 === $d ) { break; } $d--; continue; } if ( 0 === $d && $is_char( $x, ';' ) ) { break; } // ACG-149-065 (siege 9 #2): STOP at a depth-0 `as`. rhs_src also tests a foreach SOURCE (ACG-149-061); // without this it walked past `as` into the loop variables, and a loop var a PRIOR statement had // tainted (`$v=$_POST['x']; foreach($rows as $v){...}` - ubiquitous name reuse) made the clean source // read as request-derived. `as` never appears in an assignment RHS, so this bounds only the foreach use. if ( 0 === $d && is_int( $x[0] ) && T_AS === $x[0] ) { break; } // ACG-149-022: a LITERAL server-set filesystem key ($_SERVER['DOCUMENT_ROOT'] ...) is // not attacker-controlled, so a variable assigned from it must not become tainted. Skip // the whole `$_SERVER['KEY']` construct. HTTP_*/QUERY_STRING and any non-literal key // are NOT in $gp_srv_path, so they still return a source level below. if ( $gp_srv_path( $k ) ) { $k += 3; continue; } // past $_SERVER, '[', 'KEY' -> ']' $lv = $src_level( $x ); // ACG-149-074 (siege 12 #3): a request value used ONLY as a boolean CONDITION (isset/empty/comparison/ // bare ternary) selects among fixed literals and contributes NO bytes to the assigned value, so it must // not TAINT the target. The sink arms already suppress this (ACG-149-066); apply the same test in the // taint-assignment path so `$d = isset($_POST['x']) ? '--v' : ''; system('cmd'.$d);` stays clean. if ( $lv > 0 && $gp_super_is_cond( $k, true ) ) { continue; } // ACG-149-086-fix (siege-20): $rhs_src is an ASSIGNMENT-RHS context - word ops or/and/xor bind looser than `=` and capture the raw super, so they are NOT condition-only here (only the command/callable callers get the word-form exemption) if ( 1 === $lv ) { return $gp_rhs_is_closure ? 2 : 1; } // ACG-149-036: a closure caps at indirect if ( 2 === $lv && 0 === $best ) { $best = 2; } } return $best; }; // ACG-149-081/082 (siege 14 #1, siege 15): per-function taint cannot cross methods, so a class that stores // request data in a property in one method ($this->h = $_REQUEST) and dispatches it in another // (call_user_func($this->h[$_GET[..]])) hid the attacker-chosen callee. Pre-scan ONCE, CLASS-SCOPED: build class // body spans, and for each $this->NAME=/self::$NAME= write (WHOLE or ELEMENT $this->NAME[..]=) whose statement // carries request data, record (enclosing-class : field-name). The bounded-table demotion then refuses to treat // that field as a fixed registry ONLY inside the class that taints it - a same-named field in an unrelated class // is untouched (siege 15 fixed a name-only, file-scoped version that branded ubiquitous multi-class plugin files // CRITICAL). Restricted to $this/self/static: a plain $obj->NAME= is same-scope taint the normal tracker handles. $gp_bstack = array(); $gp_cstack = array(); $gp_pending_class = false; $gp_cnstack = array(); $gp_pending_cname = ''; // ACG-149-091 (MS-002): parallel CLASS-NAME stack, for class-constant keys $gp_pnstack = array(); $gp_pending_parent = ''; // ACG-149-093 (round 6, MS-001): parallel PARENT-name stack, for parent::F $gp_class_parents = array(); $gp_ppsstack = array(); $gp_pending_parents = array(); // ACG-149-096 (round 9, R8-001): classlower => [ancestor short names] (extends + implements), for inherited const propagation // ACG-149-107 (round 13, R12-003): a PRE-SCAN-local map of `$var = "literal";` so `define($n, [...])` can resolve // the constant NAME. It cannot use $const_str: that is per-function MAIN-LOOP state and is still empty here (the // pre-scan runs first). Forward-only, so the value seen is the last one assigned before the define - which is // exactly what PHP would pass. Kept local to the pre-scan; never consulted by the taint model. $gp_pre_str = array(); for ( $gp_pp = 0; $gp_pp < $n && self::scan_budget_ok(); $gp_pp++ ) { $gp_pt = $tok[ $gp_pp ]; if ( is_int( $gp_pt[0] ) && T_VARIABLE === $gp_pt[0] && $gp_pp + 3 < $n && $is_char( $tok[ $gp_pp + 1 ], '=' ) && ! $is_char( $tok[ $gp_pp + 2 ], '=' ) && is_int( $tok[ $gp_pp + 2 ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $gp_pp + 2 ][0] && strlen( (string) $tok[ $gp_pp + 2 ][1] ) < 260 && ( $is_char( $tok[ $gp_pp + 3 ], ';' ) || ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_CLOSE_TAG === $tok[ $gp_pp + 3 ][0] ) ) ) { $gp_pre_str[ (string) $gp_pt[1] ] = trim( $decode( (string) $tok[ $gp_pp + 2 ][1] ) ); } if ( is_int( $gp_pt[0] ) && ( T_CLASS === $gp_pt[0] || T_TRAIT === $gp_pt[0] || ( defined( 'T_INTERFACE' ) && T_INTERFACE === $gp_pt[0] ) ) ) { if ( ! ( $gp_pp > 0 && is_int( $tok[ $gp_pp - 1 ][0] ) && T_DOUBLE_COLON === $tok[ $gp_pp - 1 ][0] ) ) { $gp_pending_class = true; $gp_pending_cname = ( $gp_pp + 1 < $n && is_int( $tok[ $gp_pp + 1 ][0] ) && T_STRING === $tok[ $gp_pp + 1 ][0] ) ? (string) $tok[ $gp_pp + 1 ][1] : ''; // ACG-149-091: the class name (empty for anon class) // ACG-149-093/096 (round 6/9): capture the `extends` parent (for parent::F) AND the FULL list of // ancestors (extends + implements, short names) for inherited/interface const propagation. $gp_pending_parent = ''; $gp_pending_parents = array(); $gp_ex_kind = 0; for ( $gp_ex = $gp_pp + 2, $gp_exs = 0; $gp_ex < $n && $gp_exs++ < 60; $gp_ex++ ) { if ( $is_char( $tok[ $gp_ex ], '{' ) || $is_char( $tok[ $gp_ex ], ';' ) ) { break; } if ( ! is_int( $tok[ $gp_ex ][0] ) ) { continue; } if ( defined( 'T_EXTENDS' ) && T_EXTENDS === $tok[ $gp_ex ][0] ) { $gp_ex_kind = 1; continue; } if ( defined( 'T_IMPLEMENTS' ) && T_IMPLEMENTS === $tok[ $gp_ex ][0] ) { $gp_ex_kind = 2; continue; } if ( $gp_ex_kind > 0 && ( T_STRING === $tok[ $gp_ex ][0] || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $gp_ex ][0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $gp_ex ][0] ) ) ) { $gp_pn_parts = explode( chr( 92 ), strtolower( ltrim( (string) $tok[ $gp_ex ][1], chr( 92 ) ) ) ); $gp_pending_parents[] = end( $gp_pn_parts ); if ( 1 === $gp_ex_kind && '' === $gp_pending_parent ) { $gp_pending_parent = (string) $tok[ $gp_ex ][1]; } // the extends parent, for parent:: } } } // not Foo::class continue; } // ACG-149-083 (siege 16): PHP interpolation braces are ASYMMETRIC - `"a{$x}b"` OPENS with T_CURLY_OPEN // (and `"${x}"` with T_DOLLAR_OPEN_CURLY_BRACES) but CLOSES with a plain '}' char. The '}' pop below matches // both, so an interpolated string in ANY method popped a class-body brace with no matching push, truncating // the class span and letting a request-tainted property escape (FN) or leak into the enclosing class (FP). // Count the interpolation OPEN too (as a NON-class brace), mirroring the sibling matchers (ACG-143-006). if ( $is_char( $gp_pt, '{' ) || ( is_int( $gp_pt[0] ) && ( T_CURLY_OPEN === $gp_pt[0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $gp_pt[0] ) ) ) ) { $gp_is_classbrace = ( $is_char( $gp_pt, '{' ) && $gp_pending_class ); // only a REAL code brace can open a class body $gp_bstack[] = array( $gp_pp, $gp_is_classbrace ); if ( $gp_is_classbrace ) { $gp_cstack[] = ( count( $gp_classes ) < 4000 ) ? $gp_pp : -1; $gp_cnstack[] = $gp_pending_cname; $gp_pnstack[] = $gp_pending_parent; $gp_ppsstack[] = $gp_pending_parents; } if ( $is_char( $gp_pt, '{' ) ) { $gp_pending_class = false; } continue; } if ( $is_char( $gp_pt, '}' ) ) { if ( ! empty( $gp_bstack ) ) { $gp_top = array_pop( $gp_bstack ); if ( $gp_top[1] ) { $gp_cx = array_pop( $gp_cstack ); $gp_pcn = array_pop( $gp_cnstack ); $gp_ppn = array_pop( $gp_pnstack ); $gp_pps = array_pop( $gp_ppsstack ); if ( $gp_cx >= 0 ) { $gp_classes[] = array( $gp_cx, $gp_pp ); if ( count( $gp_class_ranges ) < 4000 ) { $gp_class_ranges[] = array( $gp_cx, $gp_pp, strtolower( ltrim( (string) $gp_pcn, chr( 92 ) ) ), strtolower( ltrim( (string) $gp_ppn, chr( 92 ) ) ) ); } if ( '' !== (string) $gp_pcn && ! empty( $gp_pps ) && count( $gp_class_parents ) < 4000 ) { $gp_class_parents[ strtolower( ltrim( (string) $gp_pcn, chr( 92 ) ) ) ] = $gp_pps; } } } } continue; } // ACG-149-091 (reviewer round 4, MS-002): collect user CONSTANTS holding a callable name / a numeric index. // Runs in the pre-scan so it is ORDER-INDEPENDENT - `(C::F)(..)` textually above the class still resolves. if ( is_int( $gp_pt[0] ) && defined( 'T_CONST' ) && T_CONST === $gp_pt[0] && $gp_pp + 3 < $n && is_int( $tok[ $gp_pp + 1 ][0] ) && T_STRING === $tok[ $gp_pp + 1 ][0] && $is_char( $tok[ $gp_pp + 2 ], '=' ) ) { $gp_kname = (string) $tok[ $gp_pp + 1 ][1]; $gp_kvr = $resolve_name( $gp_pp + 3 ); // ACG-149-116 (round 17, found by the OPERAND MATRIX harness): a NEGATIVE constant (`const OFF = -1;`) // tokenises as `-` then T_LNUMBER, so the ctype_digit test alone recorded no int at all - which made every // negative-constant array_splice bound unresolvable (294 cases across 50 classes, all one cause). $gp_kneg = $is_char( $tok[ $gp_pp + 3 ], '-' ) ? 1 : 0; $gp_kint = ( $gp_pp + 3 + $gp_kneg < $n && is_int( $tok[ $gp_pp + 3 + $gp_kneg ][0] ) && T_LNUMBER === $tok[ $gp_pp + 3 + $gp_kneg ][0] && ctype_digit( (string) $tok[ $gp_pp + 3 + $gp_kneg ][1] ) ) ? ( $gp_kneg ? -(int) $tok[ $gp_pp + 3 + $gp_kneg ][1] : (int) $tok[ $gp_pp + 3 + $gp_kneg ][1] ) : null; // ACG-149-092 (round 5, MS-001): a const whose value is a literal ARRAY - scan its dangerous slots. $gp_karr = ( $is_char( $tok[ $gp_pp + 3 ], '[' ) || ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_ARRAY === $tok[ $gp_pp + 3 ][0] ) ) ? $gp_scan_arr_danger( $gp_pp + 3 ) : array(); // ACG-149-115 (round 17, R16-003): also remember the ORDERED LAYOUT of an array constant, so it can serve // as an array_splice replacement (which needs the element COUNT and their order, not just danger). $gp_klay = ( $is_char( $tok[ $gp_pp + 3 ], '[' ) || ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_ARRAY === $tok[ $gp_pp + 3 ][0] ) ) ? $gp_arr_layout( $gp_pp + 3 ) : null; if ( ! empty( $gp_cstack ) && end( $gp_cstack ) >= 0 && '' !== (string) end( $gp_cnstack ) ) { $gp_cckey = strtolower( ltrim( (string) end( $gp_cnstack ), chr( 92 ) ) ) . '::' . $gp_kname; $gp_cconst_defined[ $gp_cckey ] = 1; // ACG-149-098 (R9-001): record the DECLARATION so a child override wins even when its value is safe (stored nowhere else) if ( '' !== $gp_kvr[0] && 'str' === $gp_kvr[1] ) { $gp_cconst[ $gp_cckey ] = $gp_kvr[0]; } if ( null !== $gp_kint ) { $gp_cconst_int[ $gp_cckey ] = $gp_kint; } // ACG-149-115 (R16-002): K::OFF = 0 if ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_STRING === $tok[ $gp_pp + 3 ][0] && 'null' === strtolower( (string) $tok[ $gp_pp + 3 ][1] ) ) { $gp_isnull[ 'k:' . $gp_cckey ] = 1; } // ACG-149-120 (round 20, R19-003): a BOOLEAN class constant. PHP sees false/true as 0/1 wherever an // int is expected, so it belongs in the int map alongside the numeric capture above. // ACG-149-120 (round 20, self-found FP): only when the keyword IS the whole value. if ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_STRING === $tok[ $gp_pp + 3 ][0] && in_array( strtolower( (string) $tok[ $gp_pp + 3 ][1] ), array( 'true', 'false' ), true ) && ! ( $gp_pp + 4 < $n && $is_char( $tok[ $gp_pp + 4 ], '(' ) ) && ( $gp_pp + 4 >= $n || $is_char( $tok[ $gp_pp + 4 ], ';' ) || $is_char( $tok[ $gp_pp + 4 ], ',' ) || ( is_int( $tok[ $gp_pp + 4 ][0] ) && in_array( $tok[ $gp_pp + 4 ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) && $gp_pp + 5 < $n && ( $is_char( $tok[ $gp_pp + 5 ], ';' ) || $is_char( $tok[ $gp_pp + 5 ], ',' ) ) ) ) ) { $gp_cconst_int[ $gp_cckey ] = ( 'true' === strtolower( (string) $tok[ $gp_pp + 3 ][1] ) ) ? 1 : 0; } if ( ! empty( $gp_karr ) ) { $gp_cconst_arr[ $gp_cckey ] = $gp_karr; } if ( null !== $gp_klay ) { $gp_cconst_lay[ $gp_cckey ] = $gp_klay[0]; } } else { if ( null !== $gp_klay ) { $gp_const_lay[ $gp_kname ] = $gp_klay[0]; } if ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_STRING === $tok[ $gp_pp + 3 ][0] && 'null' === strtolower( (string) $tok[ $gp_pp + 3 ][1] ) ) { $gp_isnull[ 'c:' . $gp_kname ] = 1; } if ( '' !== $gp_kvr[0] && 'str' === $gp_kvr[1] ) { $gp_uconst[ $gp_kname ] = $gp_kvr[0]; } if ( null !== $gp_kint ) { $gp_uconst_int[ $gp_kname ] = $gp_kint; } // ACG-149-124 (round 24): the namespace this const was DECLARED in, so a `use const` alias can be // required to match it instead of binding to any same-named constant in the file. $gp_krid = $gp_region_of( $gp_pp ); $gp_uconst_ns[ $gp_kname ] = strtolower( ltrim( ( $gp_krid >= 0 && isset( $gp_regions[ $gp_krid ] ) ) ? (string) $gp_regions[ $gp_krid ]['ns'] : '', chr( 92 ) ) ); // ACG-149-120 (round 20, R19-003): the same for a global `const NAME = false;`. // ACG-149-120 (round 20, self-found FP): only when the keyword IS the whole value. if ( is_int( $tok[ $gp_pp + 3 ][0] ) && T_STRING === $tok[ $gp_pp + 3 ][0] && in_array( strtolower( (string) $tok[ $gp_pp + 3 ][1] ), array( 'true', 'false' ), true ) && ! ( $gp_pp + 4 < $n && $is_char( $tok[ $gp_pp + 4 ], '(' ) ) && ( $gp_pp + 4 >= $n || $is_char( $tok[ $gp_pp + 4 ], ';' ) || $is_char( $tok[ $gp_pp + 4 ], ',' ) || ( is_int( $tok[ $gp_pp + 4 ][0] ) && in_array( $tok[ $gp_pp + 4 ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) && $gp_pp + 5 < $n && ( $is_char( $tok[ $gp_pp + 5 ], ';' ) || $is_char( $tok[ $gp_pp + 5 ], ',' ) ) ) ) ) { $gp_uconst_int[ $gp_kname ] = ( 'true' === strtolower( (string) $tok[ $gp_pp + 3 ][1] ) ) ? 1 : 0; } if ( ! empty( $gp_karr ) ) { $gp_const_arr[ $gp_kname ] = $gp_karr; } } } // define("NAME", ) - a GLOBAL runtime constant, wherever it appears. // ACG-149-106/107 (round 13, R12-002/R12-003): the callee name is normalised through $called_fn (so `\define` // counts, and a method/static `->define(` still does not), and the NAME is an OPERAND, not necessarily a // single string token: a concat (`"C"."B"`), a bareword user constant, or a `$var` holding the name all // resolve. The value argument is found at the DEPTH-1 comma instead of a fixed offset - the old fixed // `$gp_pp + 3` comma test silently rejected every non-single-token name (ACG-149-045 rule: never match at // fixed token offsets). if ( is_int( $gp_pt[0] ) && ( T_STRING === $gp_pt[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $gp_pt[0] ) ) && $gp_pp + 4 < $n && $is_char( $tok[ $gp_pp + 1 ], '(' ) && 'define' === ltrim( strtolower( (string) $gp_pt[1] ), chr( 92 ) ) && ! ( $gp_pp > 0 && is_int( $tok[ $gp_pp - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_pp - 1 ][0] || T_DOUBLE_COLON === $tok[ $gp_pp - 1 ][0] || T_FUNCTION === $tok[ $gp_pp - 1 ][0] ) ) ) { $gp_dcm = -1; $gp_dd = 1; for ( $gp_dq = $gp_pp + 2; $gp_dq < $n && $gp_dq < $gp_pp + 200; $gp_dq++ ) { if ( $is_char( $tok[ $gp_dq ], '(' ) || $is_char( $tok[ $gp_dq ], '[' ) ) { $gp_dd++; continue; } if ( $is_char( $tok[ $gp_dq ], ')' ) || $is_char( $tok[ $gp_dq ], ']' ) ) { $gp_dd--; if ( 0 === $gp_dd ) { break; } continue; } if ( 1 === $gp_dd && $is_char( $tok[ $gp_dq ], ',' ) ) { $gp_dcm = $gp_dq; break; } } if ( $gp_dcm > $gp_pp + 2 && $gp_dcm + 1 < $n ) { $gp_dname = ''; if ( is_int( $tok[ $gp_pp + 2 ][0] ) && T_VARIABLE === $tok[ $gp_pp + 2 ][0] && $gp_dcm === $gp_pp + 3 && isset( $gp_pre_str[ (string) $tok[ $gp_pp + 2 ][1] ] ) ) { $gp_dname = (string) $gp_pre_str[ (string) $tok[ $gp_pp + 2 ][1] ]; // define($n, ..) with $n a known literal } else { $gp_dnr = $resolve_name( $gp_pp + 2 ); // literal / concat / bareword const if ( '' !== $gp_dnr[0] && 'str' === $gp_dnr[1] ) { $gp_dname = trim( (string) $gp_dnr[0] ); } } $gp_dvs = $gp_dcm + 1; $gp_dvr = $resolve_name( $gp_dvs ); // ACG-149-116 (round 17): negative-aware, same as the `const` twin above. $gp_dneg = $is_char( $tok[ $gp_dvs ], '-' ) ? 1 : 0; $gp_dint = ( $gp_dvs + $gp_dneg < $n && is_int( $tok[ $gp_dvs + $gp_dneg ][0] ) && T_LNUMBER === $tok[ $gp_dvs + $gp_dneg ][0] && ctype_digit( (string) $tok[ $gp_dvs + $gp_dneg ][1] ) ) ? ( $gp_dneg ? -(int) $tok[ $gp_dvs + $gp_dneg ][1] : (int) $tok[ $gp_dvs + $gp_dneg ][1] ) : null; $gp_darr = ( $is_char( $tok[ $gp_dvs ], '[' ) || ( is_int( $tok[ $gp_dvs ][0] ) && T_ARRAY === $tok[ $gp_dvs ][0] ) ) ? $gp_scan_arr_danger( $gp_dvs ) : array(); // ACG-149-111 (round 14, R13-003): the VALUE may be another CONSTANT that already holds an array - // `const ARR = ["system"]; define("CB", ARR);` - so copy that constant's danger map onto the new name. // Covers a bareword user constant and a class constant (`C::ARR`). Both maps are filled earlier in this // same forward pre-scan pass, so a constant declared above the define() resolves. if ( empty( $gp_darr ) && is_int( $tok[ $gp_dvs ][0] ) ) { if ( T_STRING === $tok[ $gp_dvs ][0] && isset( $gp_const_arr[ (string) $tok[ $gp_dvs ][1] ] ) && $gp_dvs + 1 < $n && ! $is_char( $tok[ $gp_dvs + 1 ], '[' ) ) { $gp_darr = $gp_const_arr[ (string) $tok[ $gp_dvs ][1] ]; } elseif ( $gp_dvs + 2 < $n && is_int( $tok[ $gp_dvs + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $gp_dvs + 1 ][0] && is_int( $tok[ $gp_dvs + 2 ][0] ) && T_STRING === $tok[ $gp_dvs + 2 ][0] && ! ( $gp_dvs + 3 < $n && $is_char( $tok[ $gp_dvs + 3 ], '[' ) ) ) { $gp_dcp = explode( chr( 92 ), strtolower( ltrim( (string) $tok[ $gp_dvs ][1], chr( 92 ) ) ) ); $gp_dck = end( $gp_dcp ) . '::' . (string) $tok[ $gp_dvs + 2 ][1]; if ( isset( $gp_cconst_arr[ $gp_dck ] ) ) { $gp_darr = $gp_cconst_arr[ $gp_dck ]; } } } if ( '' !== $gp_dname && preg_match( '/^[A-Za-z_\x80-\xff][A-Za-z0-9_\x80-\xff]*$/', $gp_dname ) ) { if ( '' !== $gp_dvr[0] && 'str' === $gp_dvr[1] ) { $gp_uconst[ $gp_dname ] = $gp_dvr[0]; } if ( null !== $gp_dint ) { $gp_uconst_int[ $gp_dname ] = $gp_dint; } // ACG-149-120 (round 20, R19-003): and for define("NAME", false). // ACG-149-120 (round 20, self-found FP): only when the keyword IS the whole argument. if ( is_int( $tok[ $gp_dvs ][0] ) && T_STRING === $tok[ $gp_dvs ][0] && in_array( strtolower( (string) $tok[ $gp_dvs ][1] ), array( 'true', 'false' ), true ) && ! ( $gp_dvs + 1 < $n && $is_char( $tok[ $gp_dvs + 1 ], '(' ) ) && ( $gp_dvs + 1 >= $n || $is_char( $tok[ $gp_dvs + 1 ], ')' ) || $is_char( $tok[ $gp_dvs + 1 ], ',' ) || ( is_int( $tok[ $gp_dvs + 1 ][0] ) && in_array( $tok[ $gp_dvs + 1 ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) && $gp_dvs + 2 < $n && ( $is_char( $tok[ $gp_dvs + 2 ], ')' ) || $is_char( $tok[ $gp_dvs + 2 ], ',' ) ) ) ) ) { $gp_uconst_int[ $gp_dname ] = ( 'true' === strtolower( (string) $tok[ $gp_dvs ][1] ) ) ? 1 : 0; } if ( is_int( $tok[ $gp_dvs ][0] ) && T_STRING === $tok[ $gp_dvs ][0] && 'null' === strtolower( (string) $tok[ $gp_dvs ][1] ) ) { $gp_isnull[ 'c:' . $gp_dname ] = 1; } if ( ! empty( $gp_darr ) ) { $gp_const_arr[ $gp_dname ] = $gp_darr; } // ACG-149-092 (MS-001): define() of an array // ACG-149-115 (round 17, R16-003): the layout too, so a define()d array can be a splice replacement. if ( $is_char( $tok[ $gp_dvs ], '[' ) || ( is_int( $tok[ $gp_dvs ][0] ) && T_ARRAY === $tok[ $gp_dvs ][0] ) ) { $gp_dlay = $gp_arr_layout( $gp_dvs ); if ( null !== $gp_dlay ) { $gp_const_lay[ $gp_dname ] = $gp_dlay[0]; } } } } } if ( empty( $gp_cstack ) ) { continue; } // only class-scoped $this / self / static fields $gp_cid = end( $gp_cstack ); if ( $gp_cid < 0 ) { continue; } $gp_nm = ''; $gp_after = -1; if ( is_int( $gp_pt[0] ) && T_VARIABLE === $gp_pt[0] && '$this' === (string) $gp_pt[1] && $gp_pp + 2 < $n && is_int( $tok[ $gp_pp + 1 ][0] ) && T_OBJECT_OPERATOR === $tok[ $gp_pp + 1 ][0] && is_int( $tok[ $gp_pp + 2 ][0] ) && T_STRING === $tok[ $gp_pp + 2 ][0] ) { $gp_nm = strtolower( (string) $tok[ $gp_pp + 2 ][1] ); $gp_after = $gp_pp + 3; // $this->NAME } elseif ( is_int( $gp_pt[0] ) && T_DOUBLE_COLON === $gp_pt[0] && $gp_pp - 1 >= 0 && is_int( $tok[ $gp_pp - 1 ][0] ) // ACG-149-084 (siege 17 #8): PHP tokenises `static` as T_STATIC (not T_STRING), so static::$NAME= was missed. && ( ( T_STRING === $tok[ $gp_pp - 1 ][0] && in_array( strtolower( (string) $tok[ $gp_pp - 1 ][1] ), array( 'self', 'static' ), true ) ) || ( defined( 'T_STATIC' ) && T_STATIC === $tok[ $gp_pp - 1 ][0] ) ) && $gp_pp + 1 < $n && is_int( $tok[ $gp_pp + 1 ][0] ) && T_VARIABLE === $tok[ $gp_pp + 1 ][0] ) { $gp_nm = strtolower( (string) $tok[ $gp_pp + 1 ][1] ); $gp_after = $gp_pp + 2; // self::$NAME / static::$NAME } if ( '' === $gp_nm || isset( $gp_req_props[ $gp_cid . ':' . $gp_nm ] ) ) { continue; } // skip an optional [..] subscript chain (element write), then require a plain '=' assignment (a WRITE not ==/a read). $gp_q = $gp_after; $gp_qd = 0; $gp_qs = 0; while ( $gp_q < $n && $gp_qs++ < 200 ) { if ( $is_char( $tok[ $gp_q ], '[' ) ) { $gp_qd++; $gp_q++; continue; } if ( $is_char( $tok[ $gp_q ], ']' ) ) { if ( $gp_qd > 0 ) { $gp_qd--; } $gp_q++; continue; } if ( 0 === $gp_qd ) { break; } $gp_q++; } if ( ! ( $gp_q < $n && $is_char( $tok[ $gp_q ], '=' ) && ! ( $gp_q + 1 < $n && $is_char( $tok[ $gp_q + 1 ], '=' ) ) ) ) { continue; } // ACG-149-083 (siege 16 ROOT D): decide whether the property VALUE is request-derived with the SAME source // analyser the main taint tracker uses ($rhs_src on the RHS after '='), NOT a crude "any super token in the // statement" scan. That crude scan branded a property tainted when the request appeared ONLY as a ternary/ // isset CONDITION (`$this->views = !empty($_GET['a']) ? array(..) : array(..)`, both branches fixed) or ONLY // as the KEY selecting a FIXED sub-map (`$this->m = $reg[$_POST['k']]`) - in both the stored value is fixed, // so the dispatch is bounded. $rhs_src already models condition-only supers and fixed-key selection, so the // pre-scan and the sink arms now agree by construction. (RHS-only naturally ignores an element-write KEY.) if ( $rhs_src( $gp_q + 1 ) > 0 ) { $gp_req_props[ $gp_cid . ':' . $gp_nm ] = 1; } } // ACG-149-096 (round 9, R8-001): propagate INHERITED / INTERFACE class constants. A child `C extends P` / // `C implements I` sees P's / I's constants under `C::F`, so copy each ancestor's string/array const into the // child. ACG-149-098/099 (round 10, R9-001): the override rule is NEAREST-ANCESTOR-WINS - the closest ancestor // that DEFINES a const name binds it, and a nearer definition (the child's own, or a nearer ancestor's) SHADOWS // a farther one even when it is SAFE. A flat "any dangerous ancestor const" copy branded `class G{const CB= // ["system"];} class P extends G{const CB=["strlen"];} class C extends P{}` critical (C::CB is P's SAFE value), // because a SAFE override is stored in neither $gp_cconst nor $gp_cconst_arr. So walk ancestors nearest-first // (BFS order) and bind each NAME once, using $gp_cconst_defined (every declaration, safe or not) as the authority. if ( ! empty( $gp_class_parents ) && ( count( $gp_cconst ) + count( $gp_cconst_arr ) ) < 3000 ) { $gp_defnames = array(); // classlower => { CONST => 1 } (per-file, small) foreach ( $gp_cconst_defined as $gp_dk => $gp_dv ) { $gp_cc = strpos( $gp_dk, '::' ); if ( false !== $gp_cc ) { $gp_defnames[ substr( $gp_dk, 0, $gp_cc ) ][ substr( $gp_dk, $gp_cc + 2 ) ] = 1; } } foreach ( $gp_class_parents as $gp_ic => $gp_anc_list ) { $gp_queue = $gp_anc_list; $gp_seen_anc = array(); $gp_order = array(); $gp_bfs = 0; while ( ! empty( $gp_queue ) && $gp_bfs++ < 500 && self::scan_budget_ok() ) { $gp_anc = (string) array_shift( $gp_queue ); if ( '' === $gp_anc || $gp_anc === $gp_ic || isset( $gp_seen_anc[ $gp_anc ] ) ) { continue; } $gp_seen_anc[ $gp_anc ] = 1; $gp_order[] = $gp_anc; // NEAREST-FIRST (FIFO queue) if ( isset( $gp_class_parents[ $gp_anc ] ) ) { foreach ( $gp_class_parents[ $gp_anc ] as $gp_gp ) { $gp_queue[] = $gp_gp; } } } if ( empty( $gp_order ) ) { continue; } $gp_resolved = array(); $gp_add = array(); $gp_add_arr = array(); foreach ( $gp_order as $gp_anc ) { if ( ! isset( $gp_defnames[ $gp_anc ] ) ) { continue; } foreach ( $gp_defnames[ $gp_anc ] as $gp_name => $gp_one ) { if ( isset( $gp_resolved[ $gp_name ] ) ) { continue; } // a nearer ancestor already bound this name $gp_resolved[ $gp_name ] = 1; if ( isset( $gp_cconst_defined[ $gp_ic . '::' . $gp_name ] ) ) { continue; } // the child overrides it - its own value wins $gp_ak = $gp_anc . '::' . $gp_name; $gp_nk = $gp_ic . '::' . $gp_name; if ( isset( $gp_cconst[ $gp_ak ] ) && ! isset( $gp_cconst[ $gp_nk ] ) ) { $gp_add[ $gp_nk ] = $gp_cconst[ $gp_ak ]; } if ( isset( $gp_cconst_arr[ $gp_ak ] ) && ! isset( $gp_cconst_arr[ $gp_nk ] ) ) { $gp_add_arr[ $gp_nk ] = $gp_cconst_arr[ $gp_ak ]; } } } foreach ( $gp_add as $gp_kk => $gp_vv ) { $gp_cconst[ $gp_kk ] = $gp_vv; } foreach ( $gp_add_arr as $gp_kk => $gp_vv ) { $gp_cconst_arr[ $gp_kk ] = $gp_vv; } } } // ACG-149-123 (round 23, R22-003): apply the `use const … as …` aliases now that EVERY declaration has been // collected, so the import resolves whether it sits above or below the const. An alias only fills a name the // pre-scan left EMPTY, so a real declaration of that name always wins and no already-resolving code changes // verdict. It inherits the maps' existing namespace flattening - two same-named consts in different namespaces // were already indistinguishable here, and the alias adds a spelling, not a new ambiguity. foreach ( $gp_uconst_alias as $gp_ucA => $gp_ucE ) { list( $gp_ucT, $gp_ucP ) = $gp_ucE; // ACG-149-124 (round 24, self-found FP): the import must name the namespace the constant was really // DECLARED in. Without this test `use const Acme\Guard\Legacy\ESCAPER as X` bound X to the file's own // `Acme\Guard\ESCAPER` - a different constant with a different value - and reported innocent code critical. if ( ! isset( $gp_uconst_ns[ $gp_ucT ] ) || $gp_uconst_ns[ $gp_ucT ] !== $gp_ucP ) { continue; } if ( isset( $gp_uconst[ $gp_ucT ] ) && ! isset( $gp_uconst[ $gp_ucA ] ) ) { $gp_uconst[ $gp_ucA ] = $gp_uconst[ $gp_ucT ]; } if ( isset( $gp_uconst_int[ $gp_ucT ] ) && ! isset( $gp_uconst_int[ $gp_ucA ] ) ) { $gp_uconst_int[ $gp_ucA ] = $gp_uconst_int[ $gp_ucT ]; } if ( isset( $gp_const_arr[ $gp_ucT ] ) && ! isset( $gp_const_arr[ $gp_ucA ] ) ) { $gp_const_arr[ $gp_ucA ] = $gp_const_arr[ $gp_ucT ]; } if ( isset( $gp_const_lay[ $gp_ucT ] ) && ! isset( $gp_const_lay[ $gp_ucA ] ) ) { $gp_const_lay[ $gp_ucA ] = $gp_const_lay[ $gp_ucT ]; } if ( isset( $gp_isnull[ 'c:' . $gp_ucT ] ) && ! isset( $gp_isnull[ 'c:' . $gp_ucA ] ) ) { $gp_isnull[ 'c:' . $gp_ucA ] = 1; } } for ( $i = 0; $i < $n; $i++ ) { $e = $tok[ $i ]; // ---- scope / brace bookkeeping ---- // ACG-143-006 (adversarial review, 2026-07-19): PHP's interpolation braces are ASYMMETRIC. // `"a{$x}b"` OPENS with the array token T_CURLY_OPEN (and `"${x}"` with // T_DOLLAR_OPEN_CURLY_BRACES) but CLOSES with a plain '}' char. Only the close was counted // here, so every interpolated string decremented the brace depth without a matching // increment, popped the enclosing function scope EARLY, and re-exposed the PARENT scope for // the rest of the method. A file-level `$cb = 'extract';` then leaked into a bounded // `$cb = $this->callbacks['render']; $cb( $_POST[..] );` dispatcher and reported ordinary // widget code as CRITICAL malware. This exact asymmetry is documented at the argument // splitter above -- it was simply never applied to the scope tracker. if ( is_int( $e[0] ) && ( T_CURLY_OPEN === $e[0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $e[0] ) ) ) { $bd++; continue; } if ( $is_char( $e, '{' ) ) { if ( $pending_fn ) { // entering a function/closure body → new scope, params are fresh locals // ACG-140-001: $danger_cb is scoped exactly like $tainted. Keyed by bare variable NAME with // no scope, a harmless `$f = Closure::fromCallable('call_user_func')` in one method poisoned // an unrelated `$f` in another — turning a bounded `$f = $this->handlers['x']; $f($_POST[..])` // dispatcher into CRITICAL MALWARE. `$f` is one of the most common local names in PHP, so // that was an Elementor-scale false positive introduced by my own fix. // ACG-147-002 (P2): $const_str is scoped EXACTLY like $danger_cb - same stack, same // per-function reset. A constant-string fact that outlives its function is a false // positive, and $f/$c are among the most common local names in PHP. // ACG-148-005 (self-review, adversarial agent 3): $gp_sock_var / $gp_sock_data are // scoped EXACTLY like $danger_cb / $const_str. Keyed by bare variable NAME with no scope, // a socket handle $s and a socket-read $r in one function poisoned an UNRELATED function // whose locals reuse those names ($s/$r/$out/$data/$line/$response are among the most // common in PHP): a later `$s=fopen($file); $r=fread($s); system($r);` — reading a LOCAL // FILE, not a socket — was reported as a CRITICAL reverse shell. Per-function reset kills // the cross-contamination; a real reverse shell lives within one function (or file scope, // which has no reset), so no detection is lost. $scopes[] = $tainted; $cb_scopes[] = $danger_cb; $cs_scopes[] = $const_str; $sk_scopes[] = $gp_sock_var; $sd_scopes[] = $gp_sock_data; $als_scopes[] = $gp_arr_lit; $awh_scopes[] = $gp_arr_whole; $fca_scopes[] = $gp_fc_arr; $adg_scopes[] = $gp_arr_danger; $bnm_scopes[] = $gp_bound_nm; $uref_scopes[] = $gp_cur_uref; $gp_cur_uref = $pending_use_ref; $base[] = $bd + 1; $tainted = array(); $danger_cb = array(); $const_str = array(); $gp_sock_var = array(); $gp_sock_data = array(); $gp_arr_lit = array(); $gp_arr_whole = array(); $gp_fc_arr = array(); $gp_arr_danger = array(); $gp_bound_nm = array(); foreach ( $pending_params as $pn ) { unset( $tainted[ $pn ] ); } // ACG-149-008: a `use (...)` clause IMPORTS the outer binding, so the outer FACT must // travel with it. Without this the fresh scope loses it and // `$c = $_POST['c']; $g = function () use ( $c ) { system($c); };` is missed - which it // was on every build. (v1.0.148 appeared to catch the multi-variable form only as a // side effect of the scope bug fixed just above; the single-variable form always slipped.) if ( ! empty( $pending_use ) ) { $gp_o_t = end( $scopes ); $gp_o_cb = end( $cb_scopes ); $gp_o_cs = end( $cs_scopes ); $gp_o_sk = end( $sk_scopes ); $gp_o_sd = end( $sd_scopes ); $gp_o_al = end( $als_scopes ); $gp_o_fca = end( $fca_scopes ); $gp_o_adg = end( $adg_scopes ); $gp_o_bnm = end( $bnm_scopes ); foreach ( $pending_use as $gp_un ) { if ( isset( $gp_o_t[ $gp_un ] ) ) { $tainted[ $gp_un ] = $gp_o_t[ $gp_un ]; } if ( isset( $gp_o_cb[ $gp_un ] ) ) { $danger_cb[ $gp_un ] = $gp_o_cb[ $gp_un ]; } if ( isset( $gp_o_cs[ $gp_un ] ) ) { $const_str[ $gp_un ] = $gp_o_cs[ $gp_un ]; } if ( isset( $gp_o_sk[ $gp_un ] ) ) { $gp_sock_var[ $gp_un ] = $gp_o_sk[ $gp_un ]; } if ( isset( $gp_o_sd[ $gp_un ] ) ) { $gp_sock_data[ $gp_un ] = $gp_o_sd[ $gp_un ]; } // ACG-149-068 (siege 10 #1): a fixed dispatch map CAPTURED via use() keeps its // array-literal (bounded-table) fact, exactly like its five siblings above - otherwise a // ubiquitous WP AJAX closure router `$h=array(...); function() use($h){ $h[$_POST['k']](...); }` // lost the demotion and fired critical malware. if ( isset( $gp_o_al[ $gp_un ] ) ) { $gp_arr_lit[ $gp_un ] = $gp_o_al[ $gp_un ]; } // ACG-149-088: an array-callable-holding var captured via use() keeps its fact too. if ( isset( $gp_o_fca[ $gp_un ] ) ) { $gp_fc_arr[ $gp_un ] = $gp_o_fca[ $gp_un ]; } // ACG-149-090 (MS-004): a var holding a dangerous literal-array slot keeps its fact via use(). if ( isset( $gp_o_adg[ $gp_un ] ) ) { $gp_arr_danger[ $gp_un ] = $gp_o_adg[ $gp_un ]; } // ACG-149-130: a name-bounded callee captured via use() keeps its bound - the ubiquitous // `$p = "su_ajax_"; add_action("wp_ajax_x", function () use ($p) { $f = $p . $_POST['a']; … });` if ( isset( $gp_o_bnm[ $gp_un ] ) ) { $gp_bound_nm[ $gp_un ] = $gp_o_bnm[ $gp_un ]; } } } $pending_fn = false; $pending_params = array(); $pending_use = array(); $pending_use_ref = array(); } $bd++; continue; } if ( $is_char( $e, '}' ) ) { $bd--; if ( ! empty( $base ) && $bd < end( $base ) ) { // ACG-149-124 (round 24): a `use (&$v)` capture is the SAME BINDING, so the closure body's effect on // $v must not be silently undone by the scope pop. Round 23 wrote the INNER value through, which was // FLOW-INSENSITIVE: a closure merely REGISTERED (`add_action("shutdown", function () use (&$h) {…})`) // and never called still applied its mutation to every later read - an innocent `esc_html` call // reported critical. The rule that needs no flow analysis: if the body CHANGED the fact, the outer // value is no longer knowable, so RETIRE it; if the body left it alone, keep the outer value. That // still costs nothing on `use (&$cb) { count($cb); }`, where $cb[0] really IS dangerous. // Only the MALWARE-PROVING maps are touched; the demotion facts keep the plain restore, because // retiring THOSE could delete a bounded-table demotion - the false-positive direction. $gp_wt_adg = array(); $gp_wt_cb = array(); foreach ( $gp_cur_uref as $gp_rn ) { $gp_wt_adg[ $gp_rn ] = isset( $gp_arr_danger[ $gp_rn ] ) ? $gp_arr_danger[ $gp_rn ] : null; $gp_wt_cb[ $gp_rn ] = isset( $danger_cb[ $gp_rn ] ) ? $danger_cb[ $gp_rn ] : null; } array_pop( $base ); $tainted = (array) array_pop( $scopes ); $danger_cb = (array) array_pop( $cb_scopes ); $const_str = (array) array_pop( $cs_scopes ); $gp_sock_var = (array) array_pop( $sk_scopes ); $gp_sock_data = (array) array_pop( $sd_scopes ); $gp_arr_lit = (array) array_pop( $als_scopes ); $gp_arr_whole = (array) array_pop( $awh_scopes ); $gp_fc_arr = (array) array_pop( $fca_scopes ); $gp_arr_danger = (array) array_pop( $adg_scopes ); $gp_bound_nm = (array) array_pop( $bnm_scopes ); foreach ( $gp_wt_adg as $gp_rn => $gp_rv ) { $gp_ov = isset( $gp_arr_danger[ $gp_rn ] ) ? $gp_arr_danger[ $gp_rn ] : null; if ( $gp_rv !== $gp_ov ) { unset( $gp_arr_danger[ $gp_rn ] ); } // the body changed it -> unknowable $gp_oc = isset( $danger_cb[ $gp_rn ] ) ? $danger_cb[ $gp_rn ] : null; if ( $gp_wt_cb[ $gp_rn ] !== $gp_oc ) { unset( $danger_cb[ $gp_rn ] ); } } $gp_cur_uref = (array) array_pop( $uref_scopes ); } continue; } // ACG-143-008 (adversarial review): a REBINDING retires the dangerous-callable fact. Only a // plain `$v = ...` assignment did, so // $cb = 'system'; foreach ( $handlers as $cb ) { break; } return $cb( $_POST['a'] ); // kept the stale fact on a variable the loop had already overwritten, and reported ordinary // dispatcher code as CRITICAL malware. foreach-as binds its targets exactly like an assignment. // ACG-147-002: a foreach-as rebinding retires the constant-string fact as well. if ( is_int( $e[0] ) && T_AS === $e[0] && ! empty( $const_str ) ) { // ACG-149-037: same precision as the socket retirement - stop at a statement boundary, // and retire only a depth-0 target that is not itself subscripted (foreach element write). for ( $k = $i + 1, $d = 0, $gp_s = 0; $k < $n && $gp_s++ < 200; $k++ ) { if ( $is_char( $tok[ $k ], ';' ) || $is_char( $tok[ $k ], '{' ) || ( 0 === $d && $is_char( $tok[ $k ], '}' ) ) ) { break; } if ( $is_char( $tok[ $k ], '(' ) || $is_char( $tok[ $k ], '[' ) ) { $d++; continue; } if ( $is_char( $tok[ $k ], ']' ) ) { if ( $d > 0 ) { $d--; } continue; } if ( $is_char( $tok[ $k ], ')' ) ) { if ( 0 === $d ) { break; } $d--; continue; } if ( is_int( $tok[ $k ][0] ) && T_VARIABLE === $tok[ $k ][0] && 0 === $d && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '[' ) ) ) { unset( $const_str[ $tok[ $k ][1] ] ); } } } if ( is_int( $e[0] ) && T_AS === $e[0] && ! empty( $danger_cb ) ) { // ACG-149-037: same precision as the socket retirement - stop at a statement boundary, // and retire only a depth-0 target that is not itself subscripted (foreach element write). for ( $k = $i + 1, $d = 0, $gp_s = 0; $k < $n && $gp_s++ < 200; $k++ ) { if ( $is_char( $tok[ $k ], ';' ) || $is_char( $tok[ $k ], '{' ) || ( 0 === $d && $is_char( $tok[ $k ], '}' ) ) ) { break; } if ( $is_char( $tok[ $k ], '(' ) || $is_char( $tok[ $k ], '[' ) ) { $d++; continue; } if ( $is_char( $tok[ $k ], ']' ) ) { if ( $d > 0 ) { $d--; } continue; } if ( $is_char( $tok[ $k ], ')' ) ) { if ( 0 === $d ) { break; } $d--; continue; } if ( is_int( $tok[ $k ][0] ) && T_VARIABLE === $tok[ $k ][0] && 0 === $d && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '[' ) ) ) { unset( $danger_cb[ $tok[ $k ][1] ] ); } } } // ACG-149-091 (reviewer round 4, MS-003): a foreach over an ARRAY LITERAL that contains a dangerous // callable name binds the value var to that name on the matching iteration - // `foreach (["system"] as $f) { $f($_POST[..]); }`. Runs AFTER the retire block above so the SET wins. // Any-element-dangerous flags the value var (a safe array records nothing; retired on rebind). if ( is_int( $e[0] ) && T_AS === $e[0] ) { $gp_fs = $i - 1; $gp_fsd = 0; $gp_fss = 0; $gp_fopen = -1; while ( $gp_fs >= 0 && $gp_fss++ < 2000 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_fs ], ')' ) || $is_char( $tok[ $gp_fs ], ']' ) ) { $gp_fsd++; } elseif ( $is_char( $tok[ $gp_fs ], '(' ) ) { if ( 0 === $gp_fsd ) { $gp_fopen = $gp_fs; break; } $gp_fsd--; } elseif ( $is_char( $tok[ $gp_fs ], '[' ) ) { if ( $gp_fsd > 0 ) { $gp_fsd--; } } elseif ( $is_char( $tok[ $gp_fs ], ';' ) || $is_char( $tok[ $gp_fs ], '{' ) || $is_char( $tok[ $gp_fs ], '}' ) ) { break; } $gp_fs--; } if ( $gp_fopen >= 0 && $gp_fopen + 1 < $n && ! empty( $gp_scan_arr_danger( $gp_fopen + 1 ) ) ) { $gp_val_var = ''; $gp_vk = $i + 1; $gp_vd = 0; $gp_vs = 0; $gp_seen_arrow = false; while ( $gp_vk < $n && $gp_vs++ < 200 ) { $vx = $tok[ $gp_vk ]; if ( $is_char( $vx, '(' ) || $is_char( $vx, '[' ) ) { $gp_vd++; } elseif ( $is_char( $vx, ']' ) ) { if ( $gp_vd > 0 ) { $gp_vd--; } } elseif ( $is_char( $vx, ')' ) ) { if ( 0 === $gp_vd ) { break; } $gp_vd--; } elseif ( 0 === $gp_vd && is_int( $vx[0] ) && T_DOUBLE_ARROW === $vx[0] ) { $gp_seen_arrow = true; $gp_val_var = ''; } elseif ( 0 === $gp_vd && is_int( $vx[0] ) && T_VARIABLE === $vx[0] ) { $gp_val_var = (string) $vx[1]; } $gp_vk++; } if ( '' !== $gp_val_var ) { $danger_cb[ $gp_val_var ] = 1; } } } // ACG-149-014 (review finding #26): the SOCKET facts are retired by a rebinding exactly // like $tainted / $const_str / $danger_cb above. Without this, `$d = fgets($sock); // foreach ( $rows as $d ) { system($d); }` - a stale fact on a variable the loop had // already overwritten - reported ordinary loop code as a CRITICAL reverse shell. if ( is_int( $e[0] ) && T_AS === $e[0] && ( ! empty( $gp_sock_var ) || ! empty( $gp_sock_data ) ) ) { // ACG-149-035: a loop target that is ALSO named in the foreach SOURCE is re-derived from // itself (`foreach (explode(';', $c) as $c)`), so its socket fact survives. Collect the // source variables by walking back to the enclosing `foreach (`. $gp_src_vars = array(); $gp_fb = $i - 1; $gp_fbd = 0; $gp_fbb = 0; $gp_fbs = 0; while ( $gp_fb >= 0 && $gp_fbs++ < 400 ) { if ( $is_char( $tok[ $gp_fb ], ']' ) ) { $gp_fbb++; $gp_fbd++; } elseif ( $is_char( $tok[ $gp_fb ], ')' ) ) { $gp_fbd++; } elseif ( $is_char( $tok[ $gp_fb ], '[' ) ) { if ( 0 === $gp_fbd ) { break; } $gp_fbd--; if ( $gp_fbb > 0 ) { $gp_fbb--; } } elseif ( $is_char( $tok[ $gp_fb ], '(' ) ) { if ( 0 === $gp_fbd ) { break; } $gp_fbd--; } // ACG-149-040: a var inside a [ ] is a subscript KEY, not a source value - do not spare it. elseif ( 0 === $gp_fbb && is_int( $tok[ $gp_fb ][0] ) && T_VARIABLE === $tok[ $gp_fb ][0] ) { $gp_src_vars[ $tok[ $gp_fb ][1] ] = 1; } elseif ( $is_char( $tok[ $gp_fb ], ';' ) || $is_char( $tok[ $gp_fb ], '{' ) || $is_char( $tok[ $gp_fb ], '}' ) ) { break; } $gp_fb--; } for ( $k = $i + 1, $d = 0, $gp_s = 0; $k < $n && $gp_s++ < 200; $k++ ) { // ACG-149-019: stop at a statement boundary. Without this a trait adaptation // `use A { m as n; }` (T_AS, no closing ')') let the walk run forward and unset // socket facts belonging to unrelated later code. if ( $is_char( $tok[ $k ], ';' ) || $is_char( $tok[ $k ], '{' ) || ( 0 === $d && $is_char( $tok[ $k ], '}' ) ) ) { break; } if ( $is_char( $tok[ $k ], '(' ) || $is_char( $tok[ $k ], '[' ) ) { $d++; continue; } if ( $is_char( $tok[ $k ], ']' ) ) { if ( $d > 0 ) { $d--; } continue; } if ( $is_char( $tok[ $k ], ')' ) ) { if ( 0 === $d ) { break; } $d--; continue; } // ACG-149-029: retire only a DIRECT loop target - at bracket-depth 0 and not itself // subscripted. `foreach ($rows as $store[$s])` rebinds an ELEMENT, not $store or the // index $s, so neither socket fact should be dropped. if ( is_int( $tok[ $k ][0] ) && T_VARIABLE === $tok[ $k ][0] && 0 === $d && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '[' ) ) && ! isset( $gp_src_vars[ $tok[ $k ][1] ] ) ) { // ACG-149-035: re-derived from itself unset( $gp_sock_var[ $tok[ $k ][1] ], $gp_sock_data[ $tok[ $k ][1] ] ); } } } // Same axis, destructuring form: `[ $a, $cb ] = $pairs;` and `list( $a, $cb ) = $pairs;` // rebind every target REGARDLESS of what the right-hand side is. // ACG-149-014 (review finding #33): the socket facts are in this rebinding set too. if ( $is_char( $e, '=' ) && $i > 0 && ( ! empty( $danger_cb ) || ! empty( $gp_sock_var ) || ! empty( $gp_sock_data ) // ACG-149-091 (round 4, MS-003): also enter to SET a danger fact when the RHS is an array literal. || ( $i + 1 < $n && ( $is_char( $tok[ $i + 1 ], '[' ) || ( is_int( $tok[ $i + 1 ][0] ) && T_ARRAY === $tok[ $i + 1 ][0] ) ) ) ) && ( $is_char( $tok[ $i - 1 ], ']' ) || $is_char( $tok[ $i - 1 ], ')' ) ) ) { $gp_close = $is_char( $tok[ $i - 1 ], ']' ) ? ']' : ')'; $gp_open = ']' === $gp_close ? '[' : '('; // ACG-149-040: unified bracket depth so an INNER subscript (`$arr[$c]`) or grouping does // not contribute a target; only the destructure's own top-level ($d == 1) targets count. $j = $i - 2; $d = 1; $gp_s = 0; $gp_vars = array(); while ( $j >= 0 && $d > 0 && $gp_s++ < 400 ) { if ( $is_char( $tok[ $j ], ')' ) || $is_char( $tok[ $j ], ']' ) ) { $d++; } elseif ( $is_char( $tok[ $j ], '(' ) || $is_char( $tok[ $j ], '[' ) ) { $d--; if ( 0 === $d ) { break; } } elseif ( 1 === $d && is_int( $tok[ $j ][0] ) && T_VARIABLE === $tok[ $j ][0] ) { $gp_vars[] = $tok[ $j ][1]; } $j--; } // For the paren form this is only a destructure when `list` introduces it; a bare // `foo( $x ) = ...` is not valid PHP, but `$a = ( $b ) = $c` must not be mistaken for one. // ACG-149-019: `$arr[$k] = ...` is a SUBSCRIPT assignment, not a list destructure. Its // opening '[' is preceded by a variable / ')' / ']'; a real `[ $a, $b ] = ...` destructure // opens at an expression boundary. Treating a subscript as a destructure retired the socket // fact of a KEY variable - `$history[$cmd] = time();` in a reverse shell silenced it. // ACG-149-024: a '[' opens a list DESTRUCTURE only at an expression boundary; anything // else (a variable, a property name after ->/::, ')', ']') makes it a SUBSCRIPT. This // covers `$this->history[$c] = ...` (property subscript) which the earlier variable-only // test missed, retiring the socket fact of the key. $gp_boundary = ( $j <= 0 ); if ( $j >= 1 ) { $gp_pb = $tok[ $j - 1 ]; // ACG-149-029: '}' is NOT a boundary here - `$this->{$prop}[$c]=` / `${$name}[$c]=` // close a dynamic NAME, not a statement block, and treating the following '[' as a // destructure retired the key's socket fact. ':' (after a case label / ternary) is. $gp_boundary = $is_char( $gp_pb, ';' ) || $is_char( $gp_pb, '{' ) || $is_char( $gp_pb, ':' ) || $is_char( $gp_pb, '(' ) || $is_char( $gp_pb, ',' ) || $is_char( $gp_pb, '=' ) || ( is_int( $gp_pb[0] ) && ( ( defined( 'T_DOUBLE_ARROW' ) && T_DOUBLE_ARROW === $gp_pb[0] ) || T_RETURN === $gp_pb[0] || ( defined( 'T_OPEN_TAG' ) && T_OPEN_TAG === $gp_pb[0] ) ) ); } // ACG-149-024b: the `[ ... ]` bracket form needs the expression-boundary test (to tell a // destructure from a subscript); the `list( ... )` PAREN form is unambiguous - `list` itself // is the marker - so it is a destructure regardless of what precedes it. $gp_is_list = ( ']' === $gp_close && $gp_boundary ) || ( ')' === $gp_close && $j >= 1 && is_int( $tok[ $j - 1 ][0] ) && defined( 'T_LIST' ) && T_LIST === $tok[ $j - 1 ][0] ); if ( $gp_is_list && 0 === $d ) { // ACG-149-029: a target that also appears in the RHS is re-supplied by a value-preserving // no-op (`list($d) = [$d]`), so its socket fact survives and must not be retired. $gp_rhs_vars = array(); for ( $gp_rv = $i + 1, $gp_rvd = 0, $gp_rvs = 0; $gp_rv < $n && $gp_rvs++ < 400 && self::scan_budget_ok(); $gp_rv++ ) { $gp_rvx = $tok[ $gp_rv ]; if ( $is_char( $gp_rvx, '(' ) || $is_char( $gp_rvx, '[' ) ) { $gp_rvd++; continue; } if ( $is_char( $gp_rvx, ')' ) || $is_char( $gp_rvx, ']' ) ) { $gp_rvd--; continue; } if ( 0 === $gp_rvd && $is_char( $gp_rvx, ';' ) ) { break; } if ( is_int( $gp_rvx[0] ) && T_VARIABLE === $gp_rvx[0] ) { $gp_rhs_vars[ $gp_rvx[1] ] = 1; } } foreach ( $gp_vars as $gp_vn ) { unset( $danger_cb[ $gp_vn ] ); if ( ! isset( $gp_rhs_vars[ $gp_vn ] ) ) { unset( $gp_sock_var[ $gp_vn ], $gp_sock_data[ $gp_vn ] ); } } // ACG-149-091/092 (round 4/5, MS-003/MS-lower-1): if the RHS is an ARRAY LITERAL, a dangerous element // flags the target at the SAME key - `[$f] = ["system"]` (positional) and `["x" => $f] = ["x" => // "system"]` (keyed) - as a dangerous callable. Runs AFTER the retire above so the SET wins. if ( $i + 1 < $n && ( $is_char( $tok[ $i + 1 ], '[' ) || ( is_int( $tok[ $i + 1 ][0] ) && T_ARRAY === $tok[ $i + 1 ][0] ) ) ) { $gp_dset = $gp_scan_arr_danger( $i + 1 ); if ( ! empty( $gp_dset ) ) { $gp_pos = 0; $gp_lk = $j + 1; $gp_ld = 1; $gp_lst = 0; $gp_el_start = $j + 1; $gp_el_key = null; $gp_has_key = false; while ( $gp_lk < $i - 1 && $gp_lst++ < 3000 ) { $lx = $tok[ $gp_lk ]; if ( $is_char( $lx, '[' ) || $is_char( $lx, '(' ) ) { $gp_ld++; } elseif ( $is_char( $lx, ']' ) || $is_char( $lx, ')' ) ) { $gp_ld--; } elseif ( 1 === $gp_ld && is_int( $lx[0] ) && T_DOUBLE_ARROW === $lx[0] ) { list( $gp_el_key, ) = $gp_key_at( $gp_el_start ); $gp_has_key = true; } elseif ( 1 === $gp_ld && $is_char( $lx, ',' ) ) { $gp_pos++; $gp_el_start = $gp_lk + 1; $gp_el_key = null; $gp_has_key = false; } elseif ( 1 === $gp_ld && is_int( $lx[0] ) && T_VARIABLE === $lx[0] ) { $gp_uk = $gp_has_key ? $gp_el_key : $gp_pos; if ( null !== $gp_uk && isset( $gp_dset[ $gp_uk ] ) && is_string( $gp_dset[ $gp_uk ] ) ) { $danger_cb[ (string) $lx[1] ] = 1; } } $gp_lk++; } } } } } // (7b) ACG-148-002: an IMMEDIATELY-INVOKED closure/arrow that runs a command on its own // parameter. `(fn($c)=>system($c))($_REQUEST['c'])` is a complete backdoor in one line and // was entirely invisible: the shell arm needs the request value inside the command's own // argument list, and here it arrives through the closure's PARAMETER. // ACG-149-030: the immediately-invoked-closure shape, allowing a `static` prefix - // `(static function(){...})()` / `(static fn()=>...)()` put T_STATIC between the '(' and the // T_FUNCTION/T_FN, so the fixed-offset '(' check missed the whole backdoor. $gp_cf_iife = ( is_int( $e[0] ) && ( T_FUNCTION === $e[0] || ( defined( 'T_FN' ) && T_FN === $e[0] ) ) && $i > 0 && ( $is_char( $tok[ $i - 1 ], '(' ) || ( is_int( $tok[ $i - 1 ][0] ) && T_STATIC === $tok[ $i - 1 ][0] && $i > 1 && $is_char( $tok[ $i - 2 ], '(' ) ) ) ); // ACG-149-017: the shape is present but the per-file budget is spent (an attacker prepended // no-op IIFEs to burn it). Do not let the arm skip silently - flag the file fail-visible. if ( $gp_cf_iife && $gp_cf_total >= 200000 ) { self::$analysis_truncated = true; } if ( $gp_cf_iife && $gp_cf_total < 200000 ) { $gp_cf_is_arrow = ( defined( 'T_FN' ) && T_FN === $e[0] ); // 1. collect the closure's own parameter names $gp_cf_k = $i + 1; $gp_cf_par = array(); $gp_cf_s = 0; $gp_cf_ds = 0; // ACG-149-030: reset per firing while ( $gp_cf_k < $n && $gp_cf_s++ < 200 && ! $is_char( $tok[ $gp_cf_k ], '(' ) ) { $gp_cf_k++; } if ( $gp_cf_k < $n ) { $gp_cf_d = 1; $gp_cf_k++; while ( $gp_cf_k < $n && $gp_cf_d > 0 && $gp_cf_s++ < 400 ) { if ( $is_char( $tok[ $gp_cf_k ], '(' ) ) { $gp_cf_d++; } elseif ( $is_char( $tok[ $gp_cf_k ], ')' ) ) { $gp_cf_d--; if ( 0 === $gp_cf_d ) { break; } } elseif ( 1 === $gp_cf_d && is_int( $tok[ $gp_cf_k ][0] ) && T_VARIABLE === $tok[ $gp_cf_k ][0] ) { $gp_cf_par[ $tok[ $gp_cf_k ][1] ] = 1; } $gp_cf_k++; } } // 2. find the body and its end, and the token after the closure expression $gp_cf_body = -1; $gp_cf_end = -1; if ( $gp_cf_is_arrow ) { $gp_cf_j = $gp_cf_k; while ( $gp_cf_j < $n && $gp_cf_s++ < 200 && ! ( is_int( $tok[ $gp_cf_j ][0] ) && defined( 'T_DOUBLE_ARROW' ) && T_DOUBLE_ARROW === $tok[ $gp_cf_j ][0] ) ) { $gp_cf_j++; } if ( $gp_cf_j < $n ) { $gp_cf_body = $gp_cf_j + 1; // an arrow body is a single expression: it ends at the ')' that closes the // grouping paren this closure was opened with. $gp_cf_e = $gp_cf_body; $gp_cf_d2 = 0; while ( $gp_cf_e < $n && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_cf_e ], '(' ) || $is_char( $tok[ $gp_cf_e ], '[' ) ) { $gp_cf_d2++; } elseif ( $is_char( $tok[ $gp_cf_e ], ']' ) ) { $gp_cf_d2--; } elseif ( $is_char( $tok[ $gp_cf_e ], ')' ) ) { if ( 0 === $gp_cf_d2 ) { break; } $gp_cf_d2--; } $gp_cf_e++; } $gp_cf_end = $gp_cf_e; // the ')' closing the grouping paren } } else { $gp_cf_j = $gp_cf_k; while ( $gp_cf_j < $n && $gp_cf_s++ < 400 && ! $is_char( $tok[ $gp_cf_j ], '{' ) ) { $gp_cf_j++; } if ( $gp_cf_j < $n ) { $gp_cf_body = $gp_cf_j + 1; $gp_cf_d2 = 1; $gp_cf_e = $gp_cf_body; while ( $gp_cf_e < $n && $gp_cf_d2 > 0 && self::scan_budget_ok() ) { // ACG-149-011: `"${x}"` opens with T_DOLLAR_OPEN_CURLY_BRACES and closes with a // plain '}'. Omitting the opener (the file's two other brace counters include it) // made one interpolation decrement a depth that was never incremented. if ( $is_char( $tok[ $gp_cf_e ], '{' ) || ( is_int( $tok[ $gp_cf_e ][0] ) && ( T_CURLY_OPEN === $tok[ $gp_cf_e ][0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $tok[ $gp_cf_e ][0] ) ) ) ) { $gp_cf_d2++; } elseif ( $is_char( $tok[ $gp_cf_e ], '}' ) ) { $gp_cf_d2--; if ( 0 === $gp_cf_d2 ) { break; } } $gp_cf_e++; } $gp_cf_end = $gp_cf_e + 1; // the ')' closing the grouping paren } } // 3. IMMEDIATELY INVOKED? the grouping paren must close and be followed by '(' if ( $gp_cf_body > 0 && $gp_cf_end > 0 && $gp_cf_end + 1 < $n && $is_char( $tok[ $gp_cf_end ], ')' ) && $is_char( $tok[ $gp_cf_end + 1 ], '(' ) ) { // 4. does the body run a COMMAND function on one of the closure's parameters? // ACG-149-025: a FRESH counter, so the body-finding phases above cannot starve // the detection. If even this is exhausted (an implausibly huge body) the file // is flagged fail-visible instead of silently missing the backdoor. $gp_cf_dang = false; $gp_cf_ds = 0; for ( $gp_cf_b = $gp_cf_body; $gp_cf_b < $gp_cf_end && $gp_cf_ds++ < 40000; $gp_cf_b++ ) { $gp_cf_nm = $called_fn( $gp_cf_b ); if ( '' === $gp_cf_nm || ! isset( $shell_fns[ $gp_cf_nm ] ) ) { continue; } $gp_cf_a = $gp_cf_b + 2; $gp_cf_ad = 1; while ( $gp_cf_a < $n && $gp_cf_ad > 0 && $gp_cf_ds++ < 42000 ) { if ( $is_char( $tok[ $gp_cf_a ], '(' ) ) { $gp_cf_ad++; } elseif ( $is_char( $tok[ $gp_cf_a ], ')' ) ) { $gp_cf_ad--; if ( 0 === $gp_cf_ad ) { break; } } elseif ( is_int( $tok[ $gp_cf_a ][0] ) && T_VARIABLE === $tok[ $gp_cf_a ][0] && isset( $gp_cf_par[ $tok[ $gp_cf_a ][1] ] ) ) { $gp_cf_dang = true; } $gp_cf_a++; } if ( $gp_cf_dang ) { break; } } // 5. and does the INVOCATION carry request data? if ( $gp_cf_dang ) { $gp_cf_i = $gp_cf_end + 2; $gp_cf_id = 1; $gp_cf_req = false; while ( $gp_cf_i < $n && $gp_cf_id > 0 && $gp_cf_ds++ < 45000 ) { $gp_cf_x = $tok[ $gp_cf_i ]; if ( $is_char( $gp_cf_x, '(' ) ) { $gp_cf_id++; } elseif ( $is_char( $gp_cf_x, ')' ) ) { $gp_cf_id--; } elseif ( $is_super( $gp_cf_x ) || $is_tainted( $gp_cf_x ) || $is_fn( $gp_cf_x, $req_read ) || $gp_remote_in( $gp_cf_i ) ) { $gp_cf_req = true; } // ACG-149-038: socket bytes too $gp_cf_i++; } if ( $gp_cf_req ) { $found['shellexec'] = array( 'id' => 'tk_shell_request', 'name' => 'Shell Command From Request', 'severity' => 'critical' ); } } // ACG-149-025: a body so large the detection scan itself ran out fails visible. if ( $gp_cf_ds >= 40000 ) { self::$analysis_truncated = true; } } // ACG-149-003 / -025: charge BOTH the body-finding and detection work to the per-file // budget so N firings cannot multiply the per-firing caps into an O(n x cap) hang. $gp_cf_total += $gp_cf_s + ( isset( $gp_cf_ds ) ? $gp_cf_ds : 0 ); } // a function/closure declaration: collect its params, await its body '{'. // ACG-149-038 (siege 5 #1): a `use function X\y;` IMPORT emits a T_FUNCTION after T_USE - it is NOT a // declaration and must not arm pending_fn (the next unrelated `{` then pushed a scope that emptied // $tainted, silencing a later sink). if ( is_int( $e[0] ) && ( T_FUNCTION === $e[0] || ( defined( 'T_FN' ) && T_FN === $e[0] ) ) && ! ( $i > 0 && is_int( $tok[ $i - 1 ][0] ) && T_USE === $tok[ $i - 1 ][0] ) ) { $k = $i + 1; while ( $k < $n && ! $is_char( $tok[ $k ], '(' ) && self::scan_budget_ok() ) { $k++; } $pending_params = array(); if ( $k < $n ) { $d = 1; $k++; while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $k ], '(' ) ) { $d++; } elseif ( $is_char( $tok[ $k ], ')' ) ) { $d--; } elseif ( 1 === $d && is_int( $tok[ $k ][0] ) && T_VARIABLE === $tok[ $k ][0] ) { $pending_params[] = $tok[ $k ][1]; } $k++; } } // ACG-143-007 (adversarial review): only a real BODY opens a scope. An interface or // abstract declaration -- `interface I { public function run(); }` -- has no body, but // $pending_fn stayed armed and the next unrelated '{' in the file pushed a bogus scope, // so $danger_cb was NOT per-function scoped for the remainder of any file containing one. // Arrow functions (`fn() => expr`) capture by value and likewise never open a brace body. $gp_bk = $k; $gp_bs = 0; $gp_body = false; while ( $gp_bk < $n && $gp_bs++ < 300 ) { if ( $is_char( $tok[ $gp_bk ], '{' ) ) { $gp_body = true; break; } // ACG-149-008: a closure's `use (...)` capture list is part of the SIGNATURE, and a // MULTI-variable one contains commas. Treating those as terminators meant // `function () use ( $a, $b ) { ... }` never opened a scope, so the body inherited the // enclosing function's taint - reporting CRITICAL on a variable the closure never // imported. Step over the whole clause instead. if ( is_int( $tok[ $gp_bk ][0] ) && T_USE === $tok[ $gp_bk ][0] && $gp_bk + 1 < $n && $is_char( $tok[ $gp_bk + 1 ], '(' ) ) { $gp_ud = 1; $gp_bk += 2; $gp_uamp = false; // ACG-149-123 (round 23): in PHP 8 the `&` of `use (&$v)` is NOT the character '&' - it is // T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG. Both spellings are accepted, the same way the mutator // target skip does (that exact trap cost a round already). $gp_uampt = array(); foreach ( array( 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG' ) as $gp_uan ) { if ( defined( $gp_uan ) ) { $gp_uampt[] = constant( $gp_uan ); } } while ( $gp_bk < $n && $gp_ud > 0 && $gp_bs++ < 300 ) { if ( $is_char( $tok[ $gp_bk ], '(' ) ) { $gp_ud++; } elseif ( $is_char( $tok[ $gp_bk ], ')' ) ) { $gp_ud--; } elseif ( $is_char( $tok[ $gp_bk ], '&' ) || ( is_int( $tok[ $gp_bk ][0] ) && in_array( $tok[ $gp_bk ][0], $gp_uampt, true ) ) ) { $gp_uamp = true; } elseif ( is_int( $tok[ $gp_bk ][0] ) && T_VARIABLE === $tok[ $gp_bk ][0] ) { $pending_use[] = $tok[ $gp_bk ][1]; // captured by the closure if ( $gp_uamp ) { $pending_use_ref[] = (string) $tok[ $gp_bk ][1]; } $gp_uamp = false; // the `&` binds to ONE variable, not the rest } $gp_bk++; } continue; } if ( $is_char( $tok[ $gp_bk ], ';' ) || $is_char( $tok[ $gp_bk ], ',' ) ) { break; } if ( is_int( $tok[ $gp_bk ][0] ) && defined( 'T_DOUBLE_ARROW' ) && T_DOUBLE_ARROW === $tok[ $gp_bk ][0] ) { break; } $gp_bk++; } if ( ! $gp_body ) { $pending_params = array(); $pending_use = array(); $pending_use_ref = array(); continue; } $pending_fn = true; continue; } // ---- taint propagation (current scope) ---- if ( is_int( $e[0] ) && T_VARIABLE === $e[0] && ! isset( $supers[ $e[1] ] ) ) { // base scalar assignment: $v = if ( $i + 1 < $n && is_int( $tok[ $i + 1 ][0] ) && in_array( $tok[ $i + 1 ][0], $gp_compound_eq, true ) ) { // ACG-149-085 (siege 18 #11): a COMPOUND assignment (`$cmd .= $_POST['dir']`, `$m ??= $_POST`) AUGMENTS // the LHS with the RHS, so a request RHS taints the target; a fixed RHS leaves any existing taint in place // (never unset - unlike '='). This closed a realistic webshell that built a command with .= then ran it. $lv = $rhs_src( $i + 2 ); if ( $lv ) { $tainted[ $e[1] ] = isset( $tainted[ $e[1] ] ) ? max( (int) $tainted[ $e[1] ], $lv ) : $lv; $gp_taint_pos[ $e[1] ] = $i; } // ACG-149-130 (FP round, self-found): `$fn = "su_ajax_"; $fn .= sanitize_key($_POST['act']);` is the // same bounded dispatcher written in two statements. `.=` APPENDS, so a bounding literal already in // the value cannot be removed by it - the fact survives an unbounding RHS. Every OTHER compound // operator can REPLACE the value (`$fn ??= $_POST['f']`), so those retire it. if ( defined( 'T_CONCAT_EQUAL' ) && T_CONCAT_EQUAL === $tok[ $i + 1 ][0] ) { // ACG-149-130c: RE-STAMP an existing bound at this token even when the appended RHS carries // no literal of its own. `.=` cannot remove what is already in the value, so the proof still // holds - but it must be dated HERE, or the recency test below would read it as older than // the taint this very statement adds and reject the whole `$fn = "su_ajax_"; $fn .= …` idiom. if ( $gp_bound_rhs( $i + 2 ) || isset( $gp_bound_nm[ $e[1] ] ) ) { $gp_bound_nm[ $e[1] ] = $i; } } else { unset( $gp_bound_nm[ $e[1] ] ); } } elseif ( $i + 1 < $n && $is_char( $tok[ $i + 1 ], '=' ) ) { $lv = $rhs_src( $i + 2 ); // ACG-138-R2-02b: 0 none | 1 direct | 2 indirect if ( $lv ) { $tainted[ $e[1] ] = $lv; $gp_taint_pos[ $e[1] ] = $i; } // inherit the RHS provenance level (+ACG-149-081: stamp taint position) elseif ( $bd <= end( $base ) ) { unset( $tainted[ $e[1] ] ); unset( $gp_taint_pos[ $e[1] ] ); } // KILL only at the scope's base depth // ACG-148-005 (self-review, second siege): a rebinding RETIRES the socket-handle and // socket-read facts too, exactly like $tainted / $const_str / $danger_cb below. Without // it, `$s=fsockopen(..); fclose($s); $s=fopen($file); $d=fread($s); system($d);` (a socket // handle NAME reused for a local file) and `$c=fgets($sock); $c="backup.tar"; system("tar // cf ".$c);` (a socket-read var overwritten with a literal) both reported a FALSE reverse // shell. The socket / read arms below RE-ESTABLISH the fact on the SAME statement when the // RHS genuinely is a socket open / a read on a known handle (they run on later tokens of // this assignment), so a real `$s = fsockopen(..)` is unaffected. Base-depth guarded like // its siblings, so a conditional reassignment does not drop an outer-scope fact. // ACG-148-005 (THIRD siege): retirement must NOT kill a fact the RHS still carries. // `$c = fgets($s); $c = trim($c); system($c);` — trimming the newline off a socket read is // STANDARD (fgets keeps it), and blanket retirement made that real reverse shell vanish. // Mirror the $danger_cb rule: if the RHS mentions a variable that is still socket data (or // still a socket handle), the fact PROPAGATES to the new binding; otherwise it retires. // PERF: guarded on a non-empty socket set, exactly like the $danger_cb block below — the // overwhelming majority of files never open a socket, so the common case costs nothing. // (Without this guard the RHS walk ran on EVERY assignment in every file and took the // clean-corpus run from ~50s to over 5 minutes.) if ( $bd <= end( $base ) && ( ! empty( $gp_sock_var ) || ! empty( $gp_sock_data ) ) ) { // ACG-148-005 (FIFTH siege): the socket fact PROPAGATES to $v only along a // VALUE-PRESERVING PATH — the socket var must reach $v as (a superstring/substring of) // the actual bytes, so the resulting command still IS the remote data. Modelled as: a // socket var is carried iff EVERY function enclosing it is a string-transform that could // still yield a shell command (trim/rtrim/substr/str_replace/decode/…, an ALLOW-LIST — // default deny, so an unknown or reducing wrapper like strlen/count/bin2hex/urlencode // does NOT carry), it is not inside a subscript (that is an index), and no comparison / // logical operator turns the whole expression into a bool. This replaces a deny-LIST of // reducers that four sieges proved un-completable: it defeated `strlen($other)` appearing // anywhere (FN), missed encoders like bin2hex (FP), and its arithmetic check killed // substr($c,0,-1) via the '-1' (FN). Concatenation and grouping preserve; the transform // this exists for (`$c=fgets($s); $c=trim($c); system($c);`) still fires. static $gp_preservers = null; if ( null === $gp_preservers ) { // string transforms whose output can still carry a shell command (metachars survive) $gp_preservers = array_flip( array( 'trim','rtrim','ltrim','chop','strtolower','strtoupper', 'mb_strtolower','mb_strtoupper','ucfirst','lcfirst','ucwords','nl2br','wordwrap', 'substr','mb_substr','substr_replace','str_replace','str_ireplace','preg_replace', 'preg_replace_callback','strtr','str_pad','chunk_split','stripslashes','addslashes', 'quotemeta','urldecode','rawurldecode','html_entity_decode','htmlspecialchars_decode', 'htmlspecialchars','htmlentities','base64_decode','gzinflate','gzuncompress','gzdecode', 'gzdecode','hex2bin','convert_uudecode','str_rot13','strrev','sprintf','vsprintf', 'implode','join','stripcslashes','stripslashes','mb_convert_encoding','iconv', // ACG-149-051 (siege 7 #3): more transforms whose output still carries the command bytes 'strtok','str_repeat','mb_convert_case','preg_filter','strstr','stristr','strchr','mb_convert_kana' ) ); } $gp_sk_keep = false; $gp_sd_keep = false; $gp_has_cmp = false; // ACG-149-044 (siege 6 #2): the canonical php-reverse-shell builds a DESCRIPTOR ARRAY // `$ds = array(0=>$sock, 1=>$sock, 2=>$sock)` and hands $ds to proc_open. Carry the // socket-HANDLE fact through an array-literal RHS so proc_open($ds) (checked in link 3) // fires. Harmless elsewhere - link 3 only consults it for a shell function. if ( $i + 2 < $n && ( ( is_int( $tok[ $i + 2 ][0] ) && T_ARRAY === $tok[ $i + 2 ][0] ) || $is_char( $tok[ $i + 2 ], '[' ) ) ) { $gp_da = $i + 2; $gp_das = 0; while ( $gp_da < $n && self::scan_budget_ok() && $gp_das++ < 3000 ) { if ( $is_char( $tok[ $gp_da ], ';' ) ) { break; } if ( is_int( $tok[ $gp_da ][0] ) && T_VARIABLE === $tok[ $gp_da ][0] && isset( $gp_sock_var[ $tok[ $gp_da ][1] ] ) ) { $gp_sk_keep = true; break; } $gp_da++; } } $gp_cast_pending = false; $gp_cast_gdepth = -1; // ACG-149-019: a cast neutralises only its operand $gp_pstack = array(); $gp_prev_fn = ''; // ACG-149-022 (siege #18): a closure/arrow RHS is a CALLABLE, not a value-preserving // transform of the captured bytes. `$cb = function () use ($r) {...}` must not carry // $r's socket fact to $cb (a later $cb() then false-fired tk_dyn_superglobal_call on // ordinary socket-client code). A real backdoor in the body is caught there anyway. $gp_cl_is = static function ( $t ) { return is_int( $t[0] ) && ( T_FUNCTION === $t[0] || ( defined( 'T_FN' ) && T_FN === $t[0] ) ); }; $gp_rhs_closure = ( $i + 2 < $n && ( $gp_cl_is( $tok[ $i + 2 ] ) || ( is_int( $tok[ $i + 2 ][0] ) && T_STATIC === $tok[ $i + 2 ][0] && $i + 3 < $n && $gp_cl_is( $tok[ $i + 3 ] ) ) ) ); for ( $gp_sq = $gp_rhs_closure ? $n : ( $i + 2 ), $gp_sqs = 0; $gp_sq < $n && $gp_sqs++ < 200; $gp_sq++ ) { $gp_sqx = $tok[ $gp_sq ]; if ( $is_char( $gp_sqx, '(' ) ) { // ACG-149-019: `(int)( ... )` - this group IS the cast's operand. if ( $gp_cast_pending ) { $gp_cast_gdepth = count( $gp_pstack ); $gp_cast_pending = false; } // a call level preserves iff its function is on the allow-list; a grouping paren // (no function name before it) preserves. $gp_pstack[] = ( '' === $gp_prev_fn ) || isset( $gp_preservers[ $gp_prev_fn ] ); $gp_prev_fn = ''; continue; } if ( $is_char( $gp_sqx, '[' ) ) { $gp_pstack[] = false; $gp_prev_fn = ''; continue; } // subscript = index, not the value if ( $is_char( $gp_sqx, ')' ) || $is_char( $gp_sqx, ']' ) ) { if ( empty( $gp_pstack ) ) { break; } // unmatched close ends the RHS array_pop( $gp_pstack ); $gp_prev_fn = ''; if ( $gp_cast_gdepth >= 0 && count( $gp_pstack ) <= $gp_cast_gdepth ) { $gp_cast_gdepth = -1; } continue; } if ( empty( $gp_pstack ) && ( $is_char( $gp_sqx, ';' ) || ( is_int( $gp_sqx[0] ) && T_CLOSE_TAG === $gp_sqx[0] ) ) ) { break; } // a comparison / logical operator makes the RHS a boolean, not the data. // (a NUMERIC CAST is handled below as an operand-scoped neutraliser, ACG-149-019.) // ACG-149-019: a numeric cast neutralises the operand that FOLLOWS it, not the // whole RHS. `(int)$c` drops $c; `(bool)0 . $c` drops only the 0 and $c carries. if ( is_int( $gp_sqx[0] ) && in_array( $gp_sqx[0], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) { $gp_cast_pending = true; $gp_prev_fn = ''; continue; } if ( $is_char( $gp_sqx, '<' ) || $is_char( $gp_sqx, '>' ) || ( is_int( $gp_sqx[0] ) && in_array( $gp_sqx[0], array( T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, T_SPACESHIP, T_BOOLEAN_AND, T_BOOLEAN_OR, T_LOGICAL_AND, T_LOGICAL_OR, T_LOGICAL_XOR, T_INSTANCEOF ), true ) ) ) { $gp_has_cmp = true; $gp_prev_fn = ''; continue; } if ( is_int( $gp_sqx[0] ) && T_STRING === $gp_sqx[0] ) { $gp_prev_fn = strtolower( $gp_sqx[1] ); continue; } if ( is_int( $gp_sqx[0] ) && T_VARIABLE === $gp_sqx[0] ) { // ACG-149-019: a variable that IS a cast's operand does not carry. $gp_in_cast = $gp_cast_pending || ( $gp_cast_gdepth >= 0 && count( $gp_pstack ) > $gp_cast_gdepth ); $gp_cast_pending = false; if ( $gp_in_cast ) { $gp_prev_fn = ''; continue; } $gp_all_pres = true; foreach ( $gp_pstack as $gp_pp ) { if ( ! $gp_pp ) { $gp_all_pres = false; break; } } // socket DATA carries through an all-preserving path (concat, transforms) if ( isset( $gp_sock_data[ $gp_sqx[1] ] ) && $gp_all_pres ) { $gp_sd_keep = true; } // a socket HANDLE only aliases DIRECTLY ( $s2 = $s ) — a handle inside a string // transform is nonsensical, so require top level. if ( isset( $gp_sock_var[ $gp_sqx[1] ] ) && empty( $gp_pstack ) ) { $gp_sk_keep = true; } $gp_prev_fn = ''; continue; } $gp_cast_pending = false; $gp_prev_fn = ''; } if ( $gp_has_cmp ) { $gp_sk_keep = false; $gp_sd_keep = false; } if ( ! $gp_sk_keep ) { unset( $gp_sock_var[ $e[1] ] ); } else { $gp_sock_var[ $e[1] ] = 1; } if ( ! $gp_sd_keep ) { unset( $gp_sock_data[ $e[1] ] ); } else { $gp_sock_data[ $e[1] ] = 1; } } // ACG-140-001: reassigning the variable RETIRES any dangerous-callable fact about it — // UNLESS the RHS still carries that fact. The unconditional unset was a one-line evasion // of the whole rule (found adversarially): `$f = Closure::fromCallable('system'); $f = $f;` // dropped it, as did `$g = &$f;` and `$f = $f ?? null;`. Mirroring how $tainted inherits // its RHS, the fact now PROPAGATES var-to-var, which also closes `$g = $f; $g($_POST[..]);`. // Guarded on a non-empty set so the common case costs nothing. // ACG-143-003: `$f = "system";` / `$f = "sys" . "tem";` / `$f = "\\system";` makes $f a // dangerous callable. Recorded in the SAME $danger_cb set, so every existing consumer // (the callee walk, ->__invoke, the callback APIs) reports it with no new emit path. // A harmless literal such as "strlen" is not in $danger and is never recorded. // ACG-147-002 (P2): remember the CONSTANT STRING a variable holds, so a later // operand written as `$c` resolves. Bound ONLY at the scope's base depth: an // assignment inside an if/loop may never run, and binding it would report the other // branch's vendor class as malware. Reassignment at base depth retires the fact, // exactly like $danger_cb and $tainted. $gp_cs = $resolve_name( $i + 2 ); if ( '' !== $gp_cs[0] && $bd <= end( $base ) ) { $const_str[ $e[1] ] = $gp_cs; } elseif ( $bd <= end( $base ) ) { // ACG-149-115 (round 17, R16-002): a plain INTEGER literal (`$off = 0;` / `$off = -1;`), recorded in // the SAME scope-managed map so it inherits the existing save/restore and retire-on-rebind - no new // state to desync. Stored under a distinct 'num' channel, so every NAME consumer (which requires // 'str') ignores it and this cannot leak into callable-name resolution. // ACG-149-124 (round 24): bounds-check before the read. On a truncated file $i + 2 is past the // end and this emitted "Undefined array key" on every scan. Found by the truncation fuzz, not // by the targeted probes - my probe harness had ~E_WARNING set for 23 rounds. $gp_nneg = ( $i + 2 < $n && $is_char( $tok[ $i + 2 ], '-' ) ) ? 1 : 0; if ( $i + 3 + $gp_nneg < $n && is_int( $tok[ $i + 2 + $gp_nneg ][0] ) && T_LNUMBER === $tok[ $i + 2 + $gp_nneg ][0] && ctype_digit( (string) $tok[ $i + 2 + $gp_nneg ][1] ) && ( $is_char( $tok[ $i + 3 + $gp_nneg ], ';' ) || ( is_int( $tok[ $i + 3 + $gp_nneg ][0] ) && T_CLOSE_TAG === $tok[ $i + 3 + $gp_nneg ][0] ) ) ) { $const_str[ $e[1] ] = array( ( $gp_nneg ? '-' : '' ) . (string) $tok[ $i + 2 + $gp_nneg ][1], 'num' ); } elseif ( $i + 3 < $n && is_int( $tok[ $i + 2 ][0] ) && T_STRING === $tok[ $i + 2 ][0] && 'null' === strtolower( (string) $tok[ $i + 2 ][1] ) && ( $is_char( $tok[ $i + 3 ], ';' ) || ( is_int( $tok[ $i + 3 ][0] ) && T_CLOSE_TAG === $tok[ $i + 3 ][0] ) ) ) { $const_str[ $e[1] ] = array( 'NULL', 'num' ); // ACG-149-117 (R17-003): `$len = null;` } else { unset( $const_str[ $e[1] ] ); } } // ACG-149-095 (round 8): also track the RAW (backslash-preserving) class-name string, so // `$cls="A\C"; $cls::F` and `$name="A\C::F"; constant($name)` keep the namespace separator that the // stripcslashes-based $const_str loses. Recorded at ANY depth (like $gp_arr_lit, NOT base-only) so it // survives a BRACED `namespace B { ... }` (which raises brace depth with no scope base); retired on // rebind. A class-name string must still resolve to a DANGEROUS class const to fire, so the FP risk of // the looser recording is negligible. // PERF: only a short string-literal / name RHS can be a class-name string - skip the scan (and the // decode) for a variable / number / array / call / long-blob RHS, which is most assignments. $gp_vcs = ''; if ( $i + 2 < $n && is_int( $tok[ $i + 2 ][0] ) && ( ( T_CONSTANT_ENCAPSED_STRING === $tok[ $i + 2 ][0] && strlen( (string) $tok[ $i + 2 ][1] ) < 260 ) || T_STRING === $tok[ $i + 2 ][0] || ( defined( 'T_CLASS_C' ) && T_CLASS_C === $tok[ $i + 2 ][0] ) // ACG-149-099 (R9-002): $cls = __CLASS__ || ( defined( 'T_NS_C' ) && T_NS_C === $tok[ $i + 2 ][0] ) // ACG-149-099: $cls = __NAMESPACE__ . "\C" || ( defined( 'T_STATIC' ) && T_STATIC === $tok[ $i + 2 ][0] ) // ACG-149-099: $cls = static::class || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $i + 2 ][0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $i + 2 ][0] ) ) ) { $gp_vcs = $gp_cls_str( $i + 2 ); if ( '' !== $gp_vcs && ! preg_match( '/^[\\\\A-Za-z_\\x80-\\xff][\\\\A-Za-z0-9_:\\x80-\\xff]*$/', $gp_vcs ) ) { $gp_vcs = ''; } // only a class-name / class-const-shaped string is kept (allows `\` and `::`) } if ( '' !== $gp_vcs ) { $gp_var_cls[ $e[1] ] = $gp_vcs; } else { unset( $gp_var_cls[ $e[1] ] ); } // ACG-149-081 (siege 14 #3): a socket wrapper is idiomatically built by INTERPOLATION and held in a // var - `$addr = "tcp://$ip:$port"; fopen($addr)`. $resolve_name above returns '' (the host/port are // variables), so $const_str never carries it and the fopen-socket resolver missed the wrapper. Record // the LEADING literal of an interpolated assignment (the T_ENCAPSED right after the opening quote) so // that resolver can still see the transport scheme. Base-depth-only + retired on rebind, like $const_str. if ( $bd <= end( $base ) ) { if ( $i + 3 < $n && $is_char( $tok[ $i + 2 ], '"' ) && is_int( $tok[ $i + 3 ][0] ) && defined( 'T_ENCAPSED_AND_WHITESPACE' ) && T_ENCAPSED_AND_WHITESPACE === $tok[ $i + 3 ][0] ) { $gp_str_prefix[ $e[1] ] = (string) $tok[ $i + 3 ][1]; } else { unset( $gp_str_prefix[ $e[1] ] ); } } // ACG-149-048 (siege 7 #1): remember that $var was assigned an ARRAY LITERAL. This is the // POSITIVE evidence the ACG-149-045 dispatch-table demotion requires: a bounded table is one // the developer FILLED with `array(...)`/`[...]`, never merely a base that happens to be absent // from $tainted (which every taint blind spot - list()/foreach/global/by-ref param - satisfies). // ACG-149-060 (siege 8 #7): recorded at ANY brace depth, NOT gated to the scope base like the // MALWARE-proving $const_str. A dispatch map declared inside a capability check / nonce guard / // if / foreach / try (`if(current_user_can()){ $h=array(...); $h[$_POST['op']](...); }`) is just as // bounded as one at the top level; gating a BENIGN-proving signal to base depth inverted its // safety and branded that ubiquitous pattern critical malware. Reassignment retires it at any // depth too, so a later `$h=$_POST` in another branch correctly drops the demotion. if ( $i + 2 < $n && ( ( is_int( $tok[ $i + 2 ][0] ) && T_ARRAY === $tok[ $i + 2 ][0] ) || $is_char( $tok[ $i + 2 ], '[' ) ) ) { $gp_arr_lit[ $e[1] ] = $i; $gp_arr_whole[ $e[1] ] = $i; } // ACG-149-068 (siege 10 #2): RECORD at any depth, but RETIRE only at the scope base - like // $const_str and the taint-kill. A reassignment from a NON-literal inside a branch that may never // run (`if(is_admin()){ $h=apply_filters('h',$h); }`) must not destroy the bounded-table proof for // the common path. A request reassignment is still caught: $tainted sets at any depth and blocks // the demotion via its own `! $is_tainted` guard. elseif ( $bd <= end( $base ) ) { unset( $gp_arr_lit[ $e[1] ] ); unset( $gp_arr_whole[ $e[1] ] ); } // ACG-149-130 (FP round, self-found): the NAME-BOUNDING literal, recorded exactly like the // bounded-table fact above and for the same reason - it is the POSITIVE evidence that a dynamic // callee cannot reach a dangerous function. Any depth for the same reason ($h built inside a // capability check is just as bounded), and RETIRED on a rebind at the scope base so a later // `$fn = $_POST['f']` cannot inherit the demotion. // ACG-149-130c: retired at ANY brace depth, and stamped with the assignment's TOKEN INDEX. // This is where it differs from its sibling $gp_arr_lit, deliberately. That fact is recorded at // any depth but retired only at the scope base, so a branch that may never run cannot destroy // it. A NAME BOUND is not that kind of fact: it is a PROOF that the callee cannot be a dangerous // function, and a proof that fails on ONE path is not a proof. My first cut copied the sibling's // rule and an adversarial pass immediately produced // $fn = "su_ajax_"; if ( isset($_GET['d']) ) { $fn = $_GET['c']; } $fn( $_GET['x'] ); // - a stale bound on a variable now holding raw request data - in `if`, `foreach`, `while`, // `try`, `switch` and `??=` bodies alike. The index is the recency clock for the consumer test // below: writes this arm never sees (list(), foreach-as, a by-ref out-param) all stamp // $gp_taint_pos, so a bound older than the taint is no longer about the current value. if ( $gp_bound_rhs( $i + 2 ) ) { $gp_bound_nm[ $e[1] ] = $i; } else { unset( $gp_bound_nm[ $e[1] ] ); } // ACG-149-130c: `$ref = &$fn` makes $ref THE SAME BINDING, so a later `$ref = $_POST['f']` // rewrites $fn without this arm ever seeing $fn on a left-hand side. The alias target's bound // is therefore no longer knowable - retire it. if ( $i + 2 < $n ) { $gp_amp = $i + 2; while ( $gp_amp < $n && is_int( $tok[ $gp_amp ][0] ) && T_WHITESPACE === $tok[ $gp_amp ][0] ) { $gp_amp++; } if ( $gp_amp + 1 < $n && ( $is_char( $tok[ $gp_amp ], '&' ) || ( is_int( $tok[ $gp_amp ][0] ) && defined( 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG' ) && T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG === $tok[ $gp_amp ][0] ) ) ) { $gp_amp2 = $gp_amp + 1; while ( $gp_amp2 < $n && is_int( $tok[ $gp_amp2 ][0] ) && T_WHITESPACE === $tok[ $gp_amp2 ][0] ) { $gp_amp2++; } if ( $gp_amp2 < $n && is_int( $tok[ $gp_amp2 ][0] ) && T_VARIABLE === $tok[ $gp_amp2 ][0] ) { unset( $gp_bound_nm[ $tok[ $gp_amp2 ][1] ] ); } } } // ACG-149-088 (external reviewer, pre-1.0.2 BLOCKER): remember that $var was assigned the // GLOBAL ["Closure","fromCallable"] array callable, so `$cb=["Closure","fromCallable"]; // $cb("system")($_POST[..])` fires like the ::-token form. This is a MALWARE-proving fact, // so - exactly like $const_str - it is bound AND retired ONLY at the scope base: a // conditional assignment may never run, and binding it there could brand the other branch's // value as global. A vendor's own `["Vendor\Closure","fromCallable"]` is not global (interior // '\'), so the helper never records it. if ( $bd <= end( $base ) ) { $gp_fca_lit = ( $i + 2 < $n ) ? $gp_fc_global_arr( $i + 2 ) : array( false, $i + 2 ); if ( $gp_fca_lit[0] ) { $gp_fc_arr[ $e[1] ] = 1; } else { unset( $gp_fc_arr[ $e[1] ] ); } } // ACG-149-090 (reviewer round 3, MS-004): remember which CONSTANT indices of a literal-array // assignment hold a DANGEROUS global function name, so `$cb=["system"]; $cb[0]($_POST[..])` and // `call_user_func($cb[0], $_POST[..])` fire as request-controlled command execution. MALWARE-proving, // so - like $const_str / $gp_fc_arr - it is bound AND retired ONLY at the scope base (a conditional // assignment may never run; a safe array of callables records nothing, so no benign table is flagged). if ( $bd <= end( $base ) ) { $gp_adg_set = ( $i + 2 < $n ) ? $gp_scan_arr_danger( $i + 2 ) : array(); // ACG-149-093/094 (round 6/7, MS-003): a LIMITED var-to-var copy of a KNOWN literal-array danger // map - `$cb=["system"]; $x=$cb; $x[0]($_POST)` (and the `$x =& $cb` REFERENCE form). ONLY when the // RHS is a single bare variable already holding a danger map and the statement ends right after it, // so this is a copy of a known literal array, NOT general copy/taint tracking. if ( empty( $gp_adg_set ) ) { $gp_rvp = ( $i + 2 < $n && ( $is_char( $tok[ $i + 2 ], '&' ) || ( is_int( $tok[ $i + 2 ][0] ) && '&' === (string) $tok[ $i + 2 ][1] ) ) ) ? $i + 3 : $i + 2; // ACG-149-094: skip the `&` of a reference assignment if ( $gp_rvp + 1 < $n && is_int( $tok[ $gp_rvp ][0] ) && T_VARIABLE === $tok[ $gp_rvp ][0] && isset( $gp_arr_danger[ $tok[ $gp_rvp ][1] ] ) && ( $is_char( $tok[ $gp_rvp + 1 ], ';' ) || ( is_int( $tok[ $gp_rvp + 1 ][0] ) && T_CLOSE_TAG === $tok[ $gp_rvp + 1 ][0] ) ) ) { $gp_adg_set = $gp_arr_danger[ $tok[ $gp_rvp ][1] ]; } } // ACG-149-097 (round 9, self-found): a copy of an ARRAY-valued CLASS CONSTANT into a var, then // subscripted - `class C{const CB=["system"];} $cb=C::CB; $cb[0]($_POST)` (incl. inherited C::CB, // self/static/parent, \A\C, $cls). The direct `C::CB[0]` form already fires via $resolve_name; this // wires the intermediate-var spelling by copying the SAME danger-only map $gp_cconst_arr holds // (populated ONLY from $gp_scan_arr_danger, so it never carries a benign array - FP-safe like the // literal path). RHS must be exactly `::` ending the statement (no trailing [..], // which is the already-handled scalar form). PERF: gated on `::` at the single-token class part. if ( empty( $gp_adg_set ) && $i + 3 < $n && is_int( $tok[ $i + 3 ][0] ) && T_DOUBLE_COLON === $tok[ $i + 3 ][0] && is_int( $tok[ $i + 2 ][0] ) && ( T_STRING === $tok[ $i + 2 ][0] || T_VARIABLE === $tok[ $i + 2 ][0] || ( defined( 'T_STATIC' ) && T_STATIC === $tok[ $i + 2 ][0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $i + 2 ][0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $i + 2 ][0] ) ) ) { list( $gp_ccc_cls, $gp_ccc_p ) = $gp_class_of( $i + 2 ); if ( '' !== $gp_ccc_cls && $gp_ccc_p + 2 < $n && is_int( $tok[ $gp_ccc_p ][0] ) && T_DOUBLE_COLON === $tok[ $gp_ccc_p ][0] && is_int( $tok[ $gp_ccc_p + 1 ][0] ) && T_STRING === $tok[ $gp_ccc_p + 1 ][0] && 'class' !== strtolower( (string) $tok[ $gp_ccc_p + 1 ][1] ) && ( $is_char( $tok[ $gp_ccc_p + 2 ], ';' ) || ( is_int( $tok[ $gp_ccc_p + 2 ][0] ) && T_CLOSE_TAG === $tok[ $gp_ccc_p + 2 ][0] ) ) && isset( $gp_cconst_arr[ $gp_ccc_cls . '::' . (string) $tok[ $gp_ccc_p + 1 ][1] ] ) ) { $gp_adg_set = $gp_cconst_arr[ $gp_ccc_cls . '::' . (string) $tok[ $gp_ccc_p + 1 ][1] ]; } } if ( ! empty( $gp_adg_set ) ) { $gp_arr_danger[ $e[1] ] = $gp_adg_set; } else { unset( $gp_arr_danger[ $e[1] ] ); } } // ACG-147-008: ONLY a 'str' value may be tested against $danger. $danger is a list // of GLOBAL FUNCTION names; a 'sym' value is a namespace-sensitive CLASS symbol // (`Exec::class` under `use Vendor\Cli\Exec`, or a user constant `SYSTEM`), and // testing it here reported ordinary vendor code as CRITICAL malware. $gp_lit_nm = ( 'str' === $gp_cs[1] ) ? $gp_cs[0] : ''; if ( '' !== $gp_lit_nm && $danger_name( $gp_lit_nm ) ) { $danger_cb[ $e[1] ] = 1; continue; } // ACG-149-125 (round 24b, R24-001): `$f = array_pop(...);` / `$f = current(...);` - the first-class // callable syntax. Bound at the scope base like its siblings, and retired on any other assignment // so a later `$f = something_else` cannot leave a stale wrapper behind. if ( $bd <= end( $base ) ) { unset( $gp_fcc_fn[ $e[1] ] ); // ACG-149-127 (round 24d, R24C-001/003): ask the ONE callable-name resolver. The first cut here // understood only `(...)`, so `$f = Closure::fromCallable("array_pop");` and // `$f = (new ReflectionFunction("array_pop"))->getClosure();` left the map empty - which is the // whole of R24C-001. Any spelling the resolver knows now lands here with no per-spelling code. if ( $i + 3 < $n ) { $gp_ffn2 = (string) $gp_callable_name( $i + 2 ); if ( '' !== $gp_ffn2 ) { $gp_fcc_fn[ $e[1] ] = $gp_ffn2; } } } // ACG-149-123 (round 23, R22-001/R22-002): the RHS is a value-returning array call - // `$f = array_pop($cb);`, `$f = current($cb);`, `$r = array_splice($cb,0,1);`. A scalar return is // recorded in the SAME $danger_cb set as `$f = "system";`, so the callee walk, ->__invoke and every // callback API report it with no new emit path; an ARRAY return becomes a danger map, so `$r[0](…)` // and `call_user_func($r[0],…)` fire through the round-3 MS-004 model. Bound ONLY at the scope base, // exactly like $const_str / $danger_cb / $gp_arr_danger above, and only when the call is the WHOLE // right-hand side - `array_pop($cb) . "x"` is not a callable (the round-20 "must be whole" lesson). if ( $bd <= end( $base ) ) { $gp_vr = $gp_arr_valret( $i + 2 ); if ( $gp_vr[2] > 0 && $gp_vr[2] < $n && ( $is_char( $tok[ $gp_vr[2] ], ';' ) || ( is_int( $tok[ $gp_vr[2] ][0] ) && T_CLOSE_TAG === $tok[ $gp_vr[2] ][0] ) ) ) { if ( '' !== $gp_vr[0] && $danger_name( ltrim( strtolower( trim( (string) $gp_vr[0] ) ), '\\' ) ) ) { $danger_cb[ $e[1] ] = 1; continue; } if ( ! empty( $gp_vr[1] ) ) { $gp_arr_danger[ $e[1] ] = $gp_vr[1]; } } } if ( ! empty( $danger_cb ) ) { $gp_rhs_cb = false; $gp_rhs_concat = false; for ( $q = $i + 2, $qd = 0; $q < $n && self::scan_budget_ok(); $q++ ) { $qx = $tok[ $q ]; if ( $is_char( $qx, '(' ) || $is_char( $qx, '[' ) ) { $qd++; continue; } if ( $is_char( $qx, ')' ) || $is_char( $qx, ']' ) ) { if ( 0 === $qd ) { break; } $qd--; continue; } if ( 0 === $qd && ( $is_char( $qx, ';' ) || ( is_int( $qx[0] ) && T_CLOSE_TAG === $qx[0] ) ) ) { break; } // ACG-143-005 (adversarial review): a CONCATENATION builds a DIFFERENT name. // `$prefix = 'exec'; $fn = $prefix . '_handler';` resolves to the plugin's own // exec_handler(), never to exec(), so carrying the fact across '.' is unsound and // fired on ordinary dispatcher code. NOTE: the dangerous variable appears BEFORE // the '.' in token order, so neither fact may short-circuit the walk -- an earlier // version of this guard broke on the variable and never saw the concatenation. if ( 0 === $qd && $is_char( $qx, '.' ) ) { $gp_rhs_concat = true; continue; } if ( is_int( $qx[0] ) && T_VARIABLE === $qx[0] && isset( $danger_cb[ $qx[1] ] ) ) { $gp_rhs_cb = true; continue; } } if ( $gp_rhs_concat ) { $gp_rhs_cb = false; } if ( $gp_rhs_cb ) { $danger_cb[ $e[1] ] = 1; } else { unset( $danger_cb[ $e[1] ] ); } } continue; } // element / property assignment taints the BASE var: $a[..] = / $o->p = $k = $i + 1; // ACG-149-086 (siege 19 #3) REVERTED after siege-19 adversarial review: extending the element-write // taint to a CHAIN of subscripts (`$h['x']['cb']=$req`) tainted the WHOLE base $h, so a DISJOINT // sibling read (`$h['schedule']['email']=$req; exec($h['paths']['mysqldump'])`) became a CRITICAL // shell FALSE POSITIVE on ordinary backup/config code - the owner's #1 fear. The benefit (a NESTED // element-write reverse shell) is contrived, the 1-level form is unchanged and still caught, so the // single-group skip is restored. The nested-element write is a documented residual (same // element-INSENSITIVE limit the 1-level arm has always had). // ACG-149-124 (round 24): BOUNDS-CHECK $k before reading it. A truncated file leaves $k past the end // here, and the out-of-range reads emitted PHP warnings on every scan. if ( $k < $n && $is_char( $tok[ $k ], '[' ) ) { $d = 1; $k++; while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $k ], '[' ) ) { $d++; } elseif ( $is_char( $tok[ $k ], ']' ) ) { $d--; } $k++; } } elseif ( $k < $n && is_int( $tok[ $k ][0] ) && T_OBJECT_OPERATOR === $tok[ $k ][0] ) { $k += 2; } // ACG-138-R2-02b: an ELEMENT/PROPERTY write deposits taint into a container FIELD; reading it // back is INDIRECT (level 2) — UNLESS the base is ALREADY directly tainted ($data=$_POST; // $data['x']=… — a read still pulls direct request data), in which case keep the stronger level. if ( $k > $i + 1 && $k < $n && $is_char( $tok[ $k ], '=' ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '=' ) ) && $rhs_src( $k + 1 ) ) { $tainted[ $e[1] ] = isset( $tainted[ $e[1] ] ) ? min( (int) $tainted[ $e[1] ], 2 ) : 2; } // ACG-149-071 (siege 11 #2): a dispatch table built by literal element WRITES/APPENDS // (`$map['save']='do_save'; $map['load']='do_load';`) with no `= array()` initializer is just as // bounded as the array-literal form - the reachable callables are fixed developer strings. Record the // base in $gp_arr_lit so the demotion recognises it, exactly like the initialised twin. A request // element value taints the base above and still blocks the demotion via `! $is_tainted`. if ( $k > $i + 1 && $k < $n && $is_char( $tok[ $k ], '=' ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '=' ) ) && $k + 1 < $n && ( ( is_int( $tok[ $k + 1 ][0] ) && ( in_array( $tok[ $k + 1 ][0], array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER, T_ARRAY, T_FUNCTION ), true ) || ( defined( 'T_FN' ) && T_FN === $tok[ $k + 1 ][0] ) ) ) || $is_char( $tok[ $k + 1 ], '[' ) ) ) { $gp_arr_lit[ $e[1] ] = $i; } // ACG-149-073 (siege 12 #1): array-callable/closure values are bounded too // ACG-149-090 (MS-004): keep the dangerous-slot snapshot CURRENT under element writes. A single // CONSTANT-index write RE-RESOLVES just that slot, so `$cb=["system"]; $cb[0]="strlen"; $cb[0]($_POST)` // is CLEAN (reassigned to a safe callable) and `$cb=[]; $cb[0]="system"; $cb[0]($_POST)` FIRES (built by // element write). Base-depth-only, like the array-literal record. // ACG-149-092/094 (round 5/7, MS-lower-3 / R6-004): a `$cb[] = "system"` element write, where the key // is an int / string / numeric-string / user const / CLASS CONST (`$cb[K::X]="system"`). $gp_key_at // resolves the whole (possibly multi-token) key; the write must be exactly `$cb[ ] = `. $gp_adg_idx = null; $gp_adg_ekp = -1; if ( $bd <= end( $base ) && $k > $i + 1 && $k < $n && $is_char( $tok[ $k ], '=' ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '=' ) ) && $is_char( $tok[ $i + 1 ], '[' ) ) { list( $gp_adg_ek, $gp_adg_ekp ) = $gp_key_at( $i + 2 ); if ( null !== $gp_adg_ek && $gp_adg_ekp < $n && $is_char( $tok[ $gp_adg_ekp ], ']' ) && $gp_adg_ekp + 1 === $k ) { $gp_adg_idx = $gp_adg_ek; } } // ACG-149-104 (round 12, R11-001): an APPEND write `$cb[] = "system"`. PHP puts the value at the array's // next auto index, so `$cb=[]; $cb[]="system";` is `$cb[0]` - the same webshell as the keyed // `$cb[0]="system"` form that has fired since round 4, one spelling apart. The index is the base LITERAL's // next auto index plus the number of EARLIER appends of this same var (counted by scanning, deliberately // NOT a stored counter: a counter that desynced from the scope-restored $gp_arr_lit could map the value // onto the WRONG slot and brand a safe callable there - an FP). Unknown length -> stay null -> the // dynamic-index branch below retires the fact (fail toward clean). if ( null === $gp_adg_idx && $bd <= end( $base ) && $k > $i + 1 && $k < $n && $is_char( $tok[ $k ], '=' ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '=' ) ) && $is_char( $tok[ $i + 1 ], '[' ) && $is_char( $tok[ $i + 2 ], ']' ) && $i + 3 === $k // exactly `$var [ ] =` // NOTE: keyed on $gp_arr_whole, NOT $gp_arr_lit. The element-write arm above re-points $gp_arr_lit at // the CURRENT statement (so a table built purely by writes is recognised as bounded), which for an // append means it points at this very `$cb[] =` line - the literal would never be found. // $gp_arr_whole is written ONLY by a whole-array assignment, so it still holds the literal's position. && isset( $gp_arr_whole[ $e[1] ] ) && $i - (int) $gp_arr_whole[ $e[1] ] < 2000 ) { // PERF (measured): resolve the appended VALUE *first* and bail unless it is a dangerous global name. // An append is ubiquitous in ordinary code (`$out[] = $item;`), and computing the literal's auto index // plus counting earlier appends for EVERY one of them is O(distance) each - it TIMED THE 6.6k-file // CORPUS OUT (3m21s vs 53s) while the harness and the perf-chain both stayed green. A DANGEROUS // appended name is effectively absent from clean code, so the index work now runs almost never. $gp_apv = $resolve_name( $k + 1 ); if ( '' !== $gp_apv[0] && 'str' === $gp_apv[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_apv[0] ) ), '\\' ) ) ) { // ACG-149-120 (round 20, self-found FP): a removal earlier in the scope invalidates the // literal's index space, so the append index cannot be derived from it. Fail clean. $gp_apx = $gp_arr_removed( $e[1], (int) $gp_arr_whole[ $e[1] ] + 2, $i ) ? null : $gp_arr_auto_next( (int) $gp_arr_whole[ $e[1] ] + 2 ); if ( null !== $gp_apx ) { // ACG-149-108: the SHARED append counter, so `$cb[]=…` and `array_push($cb,…)` agree on the index. $gp_apc2 = $gp_append_count( $e[1], (int) $gp_arr_whole[ $e[1] ] + 2, $i ); if ( $gp_apc2 >= 0 ) { $gp_adg_idx = $gp_apx + $gp_apc2; } } } } if ( null !== $gp_adg_idx ) { $gp_adg_r = ( $k + 1 < $n ) ? $resolve_name( $k + 1 ) : array( '', '' ); if ( '' !== $gp_adg_r[0] && 'str' === $gp_adg_r[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_adg_r[0] ) ), '\\' ) ) ) { $gp_arr_danger[ $e[1] ][ $gp_adg_idx ] = ltrim( strtolower( trim( (string) $gp_adg_r[0] ) ), '\\' ); // ACG-149-092: store the NAME leaf (nested-value model) } elseif ( isset( $gp_arr_danger[ $e[1] ][ $gp_adg_idx ] ) ) { unset( $gp_arr_danger[ $e[1] ][ $gp_adg_idx ] ); if ( empty( $gp_arr_danger[ $e[1] ] ) ) { unset( $gp_arr_danger[ $e[1] ] ); } } } // ACG-149-090/092: a DYNAMIC-index element write to a TRACKED var invalidates the snapshot - we can no // longer say which slot holds what - so retire the whole fact (fail toward clean). // ACG-149-105 (round 13, R12-001 - a REGRESSION my round-12 append introduced): an APPEND (`$cb[] = …`) // must NEVER reach this arm. An append only ADDS the next auto index; it cannot overwrite an existing // key, so it cannot invalidate what we already know. The round-12 append path bails out early unless the // appended VALUE is dangerous (a deliberate perf gate), which left every SAFE append falling through to // here and WIPING the whole map - so `$cb[]="system"; $cb[]="strlen";` lost the proven slot 0 and the // webshell went clean again. Exclude the empty-subscript shape. elseif ( isset( $gp_arr_danger[ $e[1] ] ) && $k > $i + 1 && $k < $n && $is_char( $tok[ $k ], '=' ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '=' ) ) && $is_char( $tok[ $i + 1 ], '[' ) && ! $is_char( $tok[ $i + 2 ], ']' ) ) { unset( $gp_arr_danger[ $e[1] ] ); } // ACG-149-049 (siege 7 gap #9): a descriptor array built by element WRITES - `$ds[0]=$sock; $ds[1]=$sock;` // - deposits a socket HANDLE into the array. ACG-149-044 carried only an inline array LITERAL, so the // canonical proc_open reverse shell that wires the socket in incrementally scanned clean. When the sole // RHS of an element write is a known socket handle, the base becomes a handle too, so link 3 sees it // inside proc_open()/popen()'s descriptor argument. if ( $k > $i + 1 && $k < $n && $is_char( $tok[ $k ], '=' ) && ! ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '=' ) ) && $k + 1 < $n && is_int( $tok[ $k + 1 ][0] ) && T_VARIABLE === $tok[ $k + 1 ][0] && isset( $gp_sock_var[ $tok[ $k + 1 ][1] ] ) && $k + 2 < $n && ( $is_char( $tok[ $k + 2 ], ';' ) || $is_char( $tok[ $k + 2 ], ',' ) || ( is_int( $tok[ $k + 2 ][0] ) && T_CLOSE_TAG === $tok[ $k + 2 ][0] ) ) ) { $gp_sock_var[ $e[1] ] = 1; } } // list/array destructure [ $a, $b ] = if ( $is_char( $e, '=' ) && $i > 0 && $is_char( $tok[ $i - 1 ], ']' ) && $rhs_src( $i + 1 ) ) { $j = $i - 2; $d = 1; while ( $j >= 0 && $d > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $j ], ']' ) ) { $d++; } elseif ( $is_char( $tok[ $j ], '[' ) ) { $d--; } elseif ( $d > 0 && is_int( $tok[ $j ][0] ) && T_VARIABLE === $tok[ $j ][0] ) { $tainted[ $tok[ $j ][1] ] = 1; } $j--; } } // ACG-149-047 (siege 7 #1/#5): the taint tracker saw only '=' and the short-array `[..]=` // destructure, so `list($t)=$_POST`, `foreach($_POST as $t)` and their key/value forms left the // bound variable UNtainted. That lost direct request-driven sinks (`foreach($_POST as $c){ system($c); }` // scanned clean) AND let the ACG-149-045 dispatch-table demotion mistake a request-derived base for a // fixed table. A value bound from a request source IS request data. // (a) list( $a, $b ) = - the parenthesis-delimited sibling of the [..]= arm above. if ( $is_char( $e, '=' ) && $i > 2 && $is_char( $tok[ $i - 1 ], ')' ) && $rhs_src( $i + 1 ) ) { $gp_lj = $i - 2; $gp_ld = 1; $gp_ls = 0; while ( $gp_lj >= 0 && $gp_ld > 0 && $gp_ls++ < 4000 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_lj ], ')' ) ) { $gp_ld++; } elseif ( $is_char( $tok[ $gp_lj ], '(' ) ) { $gp_ld--; if ( 0 === $gp_ld ) { break; } } $gp_lj--; } if ( $gp_lj >= 1 && is_int( $tok[ $gp_lj - 1 ][0] ) && T_LIST === $tok[ $gp_lj - 1 ][0] ) { for ( $gp_lk = $gp_lj + 1; $gp_lk < $i - 1; $gp_lk++ ) { if ( is_int( $tok[ $gp_lk ][0] ) && T_VARIABLE === $tok[ $gp_lk ][0] ) { $tainted[ $tok[ $gp_lk ][1] ] = 1; $gp_taint_pos[ $tok[ $gp_lk ][1] ] = $i; } } } } // (b) foreach ( as [$k =>] $v ) taints the loop variable(s). The source is tested by // walking back to the enclosing `foreach (`; if any token there is request-derived ($is_req covers a // superglobal, an already-tainted intermediate, or a request-reading function), every T_VARIABLE after // `as` up to the header's ')' becomes tainted. if ( is_int( $e[0] ) && T_AS === $e[0] ) { // ACG-149-061 (siege 8 #1): walk back to the enclosing `foreach (` open paren, then test the SOURCE // with $rhs_src - which skips a request-controlled SUBSCRIPT KEY of a NON-request base. The earlier // per-token $is_req scan tainted the loop value of `foreach($cfg[$_POST['k']] as $v)`, where $_POST is // only the key and the iterated values are developer literals - a critical FP that flipped on // inline-vs-temp. $rhs_src also correctly reports explode(',',$_POST) and a tainted-base source. $gp_is_fe = false; $gp_fe_open = -1; $gp_fs = $i - 1; $gp_fsd = 0; $gp_fss = 0; while ( $gp_fs >= 0 && $gp_fss++ < 4000 && self::scan_budget_ok() ) { $gp_fx = $tok[ $gp_fs ]; if ( $is_char( $gp_fx, ')' ) || $is_char( $gp_fx, ']' ) ) { $gp_fsd++; } elseif ( $is_char( $gp_fx, '(' ) || $is_char( $gp_fx, '[' ) ) { if ( 0 === $gp_fsd ) { $gp_is_fe = ( $gp_fs > 0 && is_int( $tok[ $gp_fs - 1 ][0] ) && T_FOREACH === $tok[ $gp_fs - 1 ][0] ); $gp_fe_open = $gp_fs; break; } $gp_fsd--; } elseif ( $is_char( $gp_fx, ';' ) || $is_char( $gp_fx, '{' ) || $is_char( $gp_fx, '}' ) ) { break; } $gp_fs--; } // ACG-149-062 (siege 8 #10): a reverse shell laundered through a foreach - fgets($s) into $c then // foreach over array($c), or foreach over explode(newline, $buf) - carries SOCKET facts, not request // taint. rhs_src does not see gp_sock_data/gp_sock_var, so scan the source (foreach open .. as) for a // socket-data or socket-handle variable and propagate that fact onto the loop targets. $gp_fe_req = ( $gp_is_fe && $gp_fe_open >= 0 && $rhs_src( $gp_fe_open + 1 ) ); $gp_fe_sd = false; $gp_fe_sk = false; $gp_fe_read = false; if ( $gp_is_fe && $gp_fe_open >= 0 && ( ! empty( $gp_sock_data ) || ! empty( $gp_sock_var ) ) ) { $gp_ss = $gp_fe_open + 1; while ( $gp_ss < $i && self::scan_budget_ok() ) { $gp_sx = $tok[ $gp_ss ]; // ACG-149-067 (siege 9 #5): a socket var that is ONLY a subscript KEY of a NON-socket base is // an index, not an iterated value - foreach($cfg[$buf] as $v) iterates $cfg, not $buf. Skip // the whole subscript, exactly as $rhs_src does for the request path (ACG-149-061). if ( $is_char( $gp_sx, '[' ) ) { $gp_sb = $subscript_base( $gp_ss ); if ( null !== $gp_sb && ! isset( $gp_sock_data[ $gp_sb[1] ] ) && ! isset( $gp_sock_var[ $gp_sb[1] ] ) ) { $gp_sdp = 1; $gp_ss++; while ( $gp_ss < $i && $gp_sdp > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_ss ], '[' ) ) { $gp_sdp++; } elseif ( $is_char( $tok[ $gp_ss ], ']' ) ) { $gp_sdp--; } $gp_ss++; } continue; } } // ACG-149-067 (siege 9 #3): a socket READ (fread/fgets/...) applied to a handle INSIDE the // source produces remote DATA - foreach(explode(',', fread($s)) as $c) iterates data, not the // handle. Note the read fn name so a source handle is reclassified data below. if ( is_int( $gp_sx[0] ) && T_STRING === $gp_sx[0] && isset( $gp_sock_reads[ strtolower( (string) $gp_sx[1] ) ] ) ) { $gp_fe_read = true; } elseif ( is_int( $gp_sx[0] ) && T_VARIABLE === $gp_sx[0] ) { if ( isset( $gp_sock_data[ $gp_sx[1] ] ) ) { $gp_fe_sd = true; } if ( isset( $gp_sock_var[ $gp_sx[1] ] ) ) { $gp_fe_sk = true; } } $gp_ss++; } // a handle READ in the source yields DATA, not a handle: reclassify so a system()/passthru() sink // (which fires on socket DATA, not on a bare handle) matches the loop values. if ( $gp_fe_read && $gp_fe_sk ) { $gp_fe_sd = true; $gp_fe_sk = false; } } if ( $gp_fe_req || $gp_fe_sd || $gp_fe_sk ) { $gp_ft = $i + 1; $gp_ftd = 1; $gp_fts = 0; while ( $gp_ft < $n && $gp_ftd > 0 && $gp_fts++ < 4000 && self::scan_budget_ok() ) { $gp_tx = $tok[ $gp_ft ]; if ( $is_char( $gp_tx, '(' ) || $is_char( $gp_tx, '[' ) ) { $gp_ftd++; } elseif ( $is_char( $gp_tx, ')' ) || $is_char( $gp_tx, ']' ) ) { $gp_ftd--; if ( 0 === $gp_ftd ) { break; } } elseif ( is_int( $gp_tx[0] ) && T_VARIABLE === $gp_tx[0] ) { if ( $gp_fe_req ) { $tainted[ $gp_tx[1] ] = 1; $gp_taint_pos[ $gp_tx[1] ] = $i; } if ( $gp_fe_sd ) { $gp_sock_data[ $gp_tx[1] ] = 1; } if ( $gp_fe_sk ) { $gp_sock_var[ $gp_tx[1] ] = 1; } } $gp_ft++; } } } // ---- sinks ---- // (1) DYNAMIC CALL — a call '(' whose CALLEE primary-expression holds request data (callee only). if ( $is_char( $e, '(' ) && $i > 0 ) { $p = $tok[ $i - 1 ]; $is_call = $is_char( $p, ']' ) || $is_char( $p, ')' ) || ( is_int( $p[0] ) && ( T_VARIABLE === $p[0] || T_CONSTANT_ENCAPSED_STRING === $p[0] || T_STRING === $p[0] ) ); if ( $is_call && is_int( $p[0] ) && T_STRING === $p[0] ) { if ( isset( $kw[ strtolower( $p[1] ) ] ) ) { $is_call = false; } if ( $is_call && $i - 2 >= 0 && is_int( $tok[ $i - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $i - 2 ][0] || T_DOUBLE_COLON === $tok[ $i - 2 ][0] || T_FUNCTION === $tok[ $i - 2 ][0] ) ) { $is_call = false; } } // ACG-149-045 (siege 6 #3): a `$table[$key](...)` callee whose BASE is a fixed (untainted, // non-superglobal) variable is a BOUNDED dispatch table - it can only invoke an entry the // developer registered, so a request key + request arg is the ordinary WordPress AJAX-router // idiom, not a request-CHOSEN function. Demote to review, unlike `$_POST['fn'](...)` where the // base itself IS request data. $gp_sub_table = false; $gp_slot_danger = false; if ( $is_call && $is_char( $tok[ $i - 1 ], ']' ) ) { $gp_stj = $i - 2; $gp_std = 1; $gp_sts = 0; while ( $gp_stj >= 0 && $gp_std > 0 && $gp_sts++ < 400 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_stj ], ']' ) ) { $gp_std++; } elseif ( $is_char( $tok[ $gp_stj ], '[' ) ) { $gp_std--; if ( 0 === $gp_std ) { break; } } $gp_stj--; } if ( $gp_stj >= 1 && is_int( $tok[ $gp_stj - 1 ][0] ) && T_VARIABLE === $tok[ $gp_stj - 1 ][0] && ! $is_super( $tok[ $gp_stj - 1 ] ) && ! $is_tainted( $tok[ $gp_stj - 1 ] ) && isset( $gp_arr_lit[ $tok[ $gp_stj - 1 ][1] ] ) ) { $gp_sub_table = true; } // ACG-149-048: fixed-array base ONLY // ACG-149-090/092 (MS-004 / round 5 MS-002/MS-003): a `$base[key]...[key](...)` callee whose base var // holds a NESTED literal array with a DANGEROUS name at the resolved subscript path is a hidden // webshell (`$cb=["system"]; $cb[0](..)`, `$cb=["a"=>["b"=>"system"]]; $cb["a"]["b"](..)`, // `$cb[K::X](..)`). Walk back through ALL subscript groups to the base var, then descend the danger // map along the SAME chain; a proven-dangerous leaf OVERRIDES the benign-table demotion. A safe slot, // a wrong key, or a partial path records/returns nothing, so a benign dispatch table stays bounded. $gp_bp = $i - 1; $gp_bd = 0; $gp_bs = 0; $gp_firstopen = -1; while ( $gp_bp >= 0 && $gp_bs++ < 2000 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_bp ], ']' ) ) { $gp_bd++; } elseif ( $is_char( $tok[ $gp_bp ], '[' ) ) { $gp_bd--; if ( 0 === $gp_bd ) { $gp_firstopen = $gp_bp; if ( $gp_bp >= 1 && $is_char( $tok[ $gp_bp - 1 ], ']' ) ) { $gp_bp--; continue; } break; } } $gp_bp--; } if ( $gp_firstopen >= 1 && is_int( $tok[ $gp_firstopen - 1 ][0] ) && T_VARIABLE === $tok[ $gp_firstopen - 1 ][0] && isset( $gp_arr_danger[ $tok[ $gp_firstopen - 1 ][1] ] ) ) { list( $gp_leaf, $gp_dend ) = $gp_arr_descend( $gp_arr_danger[ $tok[ $gp_firstopen - 1 ][1] ], $gp_firstopen ); if ( null !== $gp_leaf && $gp_dend === $i ) { $gp_slot_danger = true; $gp_sub_table = false; } } // ACG-149-102 (round 11, R10-003): the callee base is an INLINE literal array in grouping parens - // `(["system"])[0](...)`. The subscript's `[` is preceded by the `)` that closes the array's parens; // find the matching `(`, require it to wrap an array literal, then descend the SAME subscript chain. elseif ( $gp_firstopen >= 1 && $is_char( $tok[ $gp_firstopen - 1 ], ')' ) ) { $gp_ib = $gp_firstopen - 1; $gp_ibd = 0; $gp_ibs = 0; $gp_iopen = -1; while ( $gp_ib >= 0 && $gp_ibs++ < 2000 ) { if ( $is_char( $tok[ $gp_ib ], ')' ) ) { $gp_ibd++; } elseif ( $is_char( $tok[ $gp_ib ], '(' ) ) { $gp_ibd--; if ( 0 === $gp_ibd ) { $gp_iopen = $gp_ib; break; } } $gp_ib--; } // skip NESTED grouping parens `((["system"]))[0]` to the array literal (one extra paren must not evade it). $gp_ias = $gp_iopen; while ( $gp_ias >= 0 && $gp_ias + 1 < $n && $gp_ias < $gp_iopen + 8 && $is_char( $tok[ $gp_ias ], '(' ) && $is_char( $tok[ $gp_ias + 1 ], '(' ) ) { $gp_ias++; } $gp_iarr = $gp_ias + 1; if ( $gp_iopen >= 0 && $gp_iarr < $n && ( $is_char( $tok[ $gp_iarr ], '[' ) || ( is_int( $tok[ $gp_iarr ][0] ) && T_ARRAY === $tok[ $gp_iarr ][0] ) ) ) { $gp_iam = $gp_scan_arr_danger( $gp_iarr ); if ( ! empty( $gp_iam ) ) { list( $gp_leaf, $gp_dend ) = $gp_arr_descend( $gp_iam, $gp_firstopen ); if ( null !== $gp_leaf && $gp_dend === $i ) { $gp_slot_danger = true; $gp_sub_table = false; } } } // ACG-149-103 (round 12, self-found): the base is a `constant("CB")` CALL - `constant("CB")[0](..)`. // $resolve_name's constant() branch already descends an array constant's subscript, so resolve the // whole callee primary from the `constant` token. (The reviewer's R11-002 listed only the // callback-API spellings; the BARE direct call needed the callee walk, which had no non-variable base.) elseif ( $gp_iopen >= 1 && is_int( $tok[ $gp_iopen - 1 ][0] ) && 'constant' === ltrim( strtolower( (string) $tok[ $gp_iopen - 1 ][1] ), chr( 92 ) ) ) { // ACG-149-106 (R12-002): `\constant("CB")[0](..)` too $gp_cr = $resolve_name( $gp_iopen - 1 ); if ( '' !== $gp_cr[0] && 'str' === $gp_cr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_cr[0] ) ), '\\' ) ) ) { $gp_slot_danger = true; $gp_sub_table = false; } } // ACG-149-123 (round 23, R22-001): the base is an array function that RETURNS AN ARRAY - // `array_splice($cb,0,1)[0]($_POST[..])`. The helper descends the subscript chain itself, and // $gp_vr[2] === $i proves the descent consumed the WHOLE chain up to this invocation. elseif ( $gp_iopen >= 1 ) { $gp_vr = $gp_arr_valret( $gp_iopen - 1 ); if ( '' !== $gp_vr[0] && $gp_vr[2] === $i && $danger_name( ltrim( strtolower( trim( (string) $gp_vr[0] ) ), '\\' ) ) ) { $gp_slot_danger = true; $gp_sub_table = false; } } } // ACG-149-103 (round 12, self-found): the base is a BAREWORD global array CONSTANT - `CB[0](..)` after // `define("CB",["system"])` / `const CB=["system"]`. The parenthesised `(CB[0])(..)` and // `call_user_func(CB[0],..)` spellings already fired through $resolve_name; the BARE direct call reached // only this callee walk, which tested a T_VARIABLE base exclusively. The reviewer ASSUMED this form was // covered (he used it as his "already works" control) - it was not. $resolve_name's bareword-const-array // branch does the descent, so route the callee primary through it. elseif ( $gp_firstopen >= 1 && is_int( $tok[ $gp_firstopen - 1 ][0] ) && T_STRING === $tok[ $gp_firstopen - 1 ][0] && isset( $gp_const_arr[ (string) $tok[ $gp_firstopen - 1 ][1] ] ) ) { $gp_cr = $resolve_name( $gp_firstopen - 1 ); if ( '' !== $gp_cr[0] && 'str' === $gp_cr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_cr[0] ) ), '\\' ) ) ) { $gp_slot_danger = true; $gp_sub_table = false; } } } if ( $is_call ) { // ACG-105 fresh-eyes (2026-06-30): distinguish a SUPERGLOBAL used DIRECTLY as the // callee primary (a request array element invoked as the function) — which no legitimate // code does, so it is a confirmed request-controlled-callee backdoor — from a TAINTED // VARIABLE callee (a local that was assigned from request input and later called, or a // router table), which legitimate frameworks (TGMPA, dispatchers) produce by // validating-then-calling. $hit_super marks the former. // ACG-122: $gp_method_call — the callee was reached through -> or :: , i.e. $this->$m() / // Foo::$m(). Such a call can only reach a METHOD THAT EXISTS ON THAT CLASS; a plain $f() // can reach ANY php function, including system/exec. That difference is what separates a // validated dispatcher from a webshell (see the tk_dyn_request_callee_var block below). // ACG-137-B3 (self-review of the v1.0.137 diff, 2026-07-17): $gp_traversed_call — the callee // primary is the RETURN VALUE of a call, so the operator we are about to meet does NOT // govern it. See the $gp_method_call assignment below for why this distinction is the // whole bug. // ACG-147-007 (P3a): resolve the callee PRIMARY through grouping parens and a // subscript before the walk. The walk only ever tested a BARE adjacent variable, so // one wrapping paren defeated every factory fix in this file - including my own: // $f = Closure::fromCallable('system'); ($f)($_POST['a']); -> 0 findings // $a = ['system']; $a[0]($_POST['a']); -> 0 findings // Until this landed, every callable-factory detection was one character from bypass. // The callee primary sits BEFORE this '(' . When it is a parenthesised group - // `($f)(...)` , `(($f))(...)` - walk back over the balanced group(s) and test the // variable inside. When it is a subscript - `$a[0](...)` - walk back over the // bracket group to its base variable. $gp_wrapped_danger = false; $gp_prim_bound = false; // ACG-149-130b: is the grouped callee's PRIMARY a name-bounded variable? // ACG-149-090 (MS-004): a proven dangerous literal-array slot at a constant index IS a dangerous // callee (`$cb=["system"]; $cb[0]($_POST[..])`) - carry it into the shared callee-danger verdict. if ( $gp_slot_danger ) { $gp_wrapped_danger = true; } // ACG-149-091 (round 4, MS-002): a PARENTHESISED constant/class-constant callee - `(F)($_POST[..])`, // `(C::F)($_POST[..])` - resolves to a hidden dangerous name. Distinguish a GROUPING paren (the // callee) from a CALL's arg list (`channel(F)(..)`, where F is an ARGUMENT) by the token before the // group's '(': a name / ')' / ']' means it is a call, so the operand inside is not the callee. if ( ! $gp_wrapped_danger && $i > 0 && $is_char( $tok[ $i - 1 ], ')' ) ) { $gp_gj = $i - 2; $gp_gd = 1; $gp_gs = 0; while ( $gp_gj >= 0 && $gp_gd > 0 && $gp_gs++ < 400 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_gj ], ')' ) ) { $gp_gd++; } elseif ( $is_char( $tok[ $gp_gj ], '(' ) ) { $gp_gd--; if ( 0 === $gp_gd ) { break; } } $gp_gj--; } if ( 0 === $gp_gd && $gp_gj >= 0 ) { $gp_gpre = ( $gp_gj > 0 ) ? $tok[ $gp_gj - 1 ] : null; $gp_is_group = ( null === $gp_gpre || ! ( $is_char( $gp_gpre, ')' ) || $is_char( $gp_gpre, ']' ) || ( is_int( $gp_gpre[0] ) && ( T_STRING === $gp_gpre[0] || T_VARIABLE === $gp_gpre[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $gp_gpre[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $gp_gpre[0] ) ) ) ) ); if ( $gp_is_group ) { $gp_gr = $resolve_name( $gp_gj + 1 ); if ( '' !== $gp_gr[0] && 'str' === $gp_gr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_gr[0] ) ), '\\' ) ) ) { $gp_wrapped_danger = true; } } elseif ( null !== $gp_gpre && is_int( $gp_gpre[0] ) && ( T_STRING === $gp_gpre[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $gp_gpre[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $gp_gpre[0] ) ) && ! ( $gp_gj - 2 >= 0 && is_int( $tok[ $gp_gj - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_gj - 2 ][0] || T_DOUBLE_COLON === $tok[ $gp_gj - 2 ][0] ) ) ) { // ACG-149-092 (round 5, MS-lower-2): a resolvable CALL-HEAD callee whose RETURN is invoked - // `constant("F")($_POST[..])`, `strrev("metsys")($_POST[..])`. $resolve_name resolves only // constant()/the transforms; any other function returns '' and stays clean. $gp_gr = $resolve_name( $gp_gj - 1 ); if ( '' !== $gp_gr[0] && 'str' === $gp_gr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_gr[0] ) ), '\\' ) ) ) { $gp_wrapped_danger = true; } // ACG-149-123 (round 23, R22-001/R22-002): the same shape for an ARRAY function whose // RETURN is invoked - `array_pop($cb)($_POST[..])`, `current($cb)($_POST[..])`. if ( ! $gp_wrapped_danger ) { $gp_vr = $gp_arr_valret( $gp_gj - 1 ); if ( '' !== $gp_vr[0] && $gp_vr[2] === $i && $danger_name( ltrim( strtolower( trim( (string) $gp_vr[0] ) ), '\\' ) ) ) { $gp_wrapped_danger = true; } } } elseif ( null !== $gp_gpre && is_int( $gp_gpre[0] ) && T_VARIABLE === $gp_gpre[0] && ! ( $gp_gj - 2 >= 0 && is_int( $tok[ $gp_gj - 2 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_gj - 2 ][0] || T_DOUBLE_COLON === $tok[ $gp_gj - 2 ][0] ) ) ) { // ACG-149-125 (round 24b, R24-001): a VARIABLE call head whose RETURN is invoked - // `$f = current(...); $f($cb)($_POST[..])` (a first-class callable) and // `$f = "array_pop"; $f($cb)($_POST[..])` (a variable holding the helper's name). // ONLY the value-return model is asked here: running $resolve_name on a variable CALL // HEAD would answer with the variable's own string value, which is a different claim. $gp_vr = $gp_arr_valret( $gp_gj - 1 ); if ( '' !== $gp_vr[0] && $gp_vr[2] === $i && $danger_name( ltrim( strtolower( trim( (string) $gp_vr[0] ) ), '\\' ) ) ) { $gp_wrapped_danger = true; } } elseif ( $gp_gj >= 2 && is_int( $tok[ $gp_gj - 1 ][0] ) && T_STRING === $tok[ $gp_gj - 1 ][0] && in_array( strtolower( (string) $tok[ $gp_gj - 1 ][1] ), array( 'invoke', 'invokeargs' ), true ) && is_int( $tok[ $gp_gj - 2 ][0] ) && T_OBJECT_OPERATOR === $tok[ $gp_gj - 2 ][0] ) { // ACG-149-126 (round 24c, R24B-001): `(new ReflectionFunction("current"))->invoke($cb)(…)`. // The T_STRING arm above excludes method calls on purpose, so Reflection's invoke needs // its own arm; the value-return model checks that the object really is a // ReflectionFunction over one of the helpers. $gp_vr = $gp_arr_valret( $gp_gj - 1 ); if ( '' !== $gp_vr[0] && $gp_vr[2] === $i && $danger_name( ltrim( strtolower( trim( (string) $gp_vr[0] ) ), '\\' ) ) ) { $gp_wrapped_danger = true; } } elseif ( $gp_gj >= 1 && $is_char( $tok[ $gp_gj - 1 ], ')' ) ) { // ACG-149-125 (round 24b, found by the WIDENED matrix, not by the reviewer): the call // head is itself a parenthesised group - the INLINE first-class callable // `(array_pop(...))($cb)(…)`, with no intermediate variable. Walk back to that group's // `(` and let the value-return model decide; it accepts only an exact `(...)` // group, so an ordinary `foo($x)($_POST)` chain resolves to nothing and stays clean. $gp_ho = -1; $gp_hd = 0; for ( $gp_hz = $gp_gj - 1; $gp_hz >= 0 && $gp_hz > $gp_gj - 60; $gp_hz-- ) { if ( $is_char( $tok[ $gp_hz ], ')' ) ) { $gp_hd++; continue; } if ( $is_char( $tok[ $gp_hz ], '(' ) ) { $gp_hd--; if ( 0 === $gp_hd ) { $gp_ho = $gp_hz; break; } } } if ( $gp_ho >= 0 && $gp_ho < $gp_gj - 1 ) { $gp_vr = $gp_arr_valret( $gp_ho ); if ( '' !== $gp_vr[0] && $gp_vr[2] === $i && $danger_name( ltrim( strtolower( trim( (string) $gp_vr[0] ) ), '\\' ) ) ) { $gp_wrapped_danger = true; } } } } } $gp_pj = $i - 1; $gp_pstep = 0; while ( $gp_pj > 0 && $gp_pstep++ < 40 ) { if ( $is_char( $tok[ $gp_pj ], ')' ) || $is_char( $tok[ $gp_pj ], ']' ) ) { $gp_close = $is_char( $tok[ $gp_pj ], ')' ) ? ')' : ']'; $gp_open = ( ')' === $gp_close ) ? '(' : '['; $gp_pd = 1; while ( $gp_pj > 0 && $gp_pd > 0 && $gp_pstep++ < 400 ) { $gp_pj--; if ( $is_char( $tok[ $gp_pj ], $gp_close ) ) { $gp_pd++; } elseif ( $is_char( $tok[ $gp_pj ], $gp_open ) ) { $gp_pd--; } } if ( ']' === $gp_close ) { $gp_pj--; // step onto the base variable } else { // ACG-148-001: step INTO the group, then skip any FURTHER opening // parens - `(($f))` and `((($f)))` are the same expression as `($f)`, // and stopping at the first inner '(' let one extra character defeat // the whole mechanism. $gp_pj++; while ( $gp_pj < $n && $gp_pstep++ < 40 && $is_char( $tok[ $gp_pj ], '(' ) ) { $gp_pj++; } } continue; } break; } // ACG-143-012 applies here too: `new $class(...)` is a CLASS position, never a call, // so an instantiation must not inherit the dangerous-callable fact (fixtures PC3/PC4). if ( $gp_pj > 0 && $gp_pj < $n && ! ( $gp_pj > 0 && is_int( $tok[ $gp_pj - 1 ][0] ) && T_NEW === $tok[ $gp_pj - 1 ][0] ) ) { $gp_prim = $tok[ $gp_pj ]; // ACG-149-130b: the PRIMARY is where a grouped callee's identity lives, so `($fn)($_POST)` // and `((($fn)))($_POST)` carry the name bound too - the back-walk below only sees the // variable at depth > 0 and would otherwise lose it to one pair of parentheses. $gp_prim_bound = ( is_int( $gp_prim[0] ) && T_VARIABLE === $gp_prim[0] && $gp_name_bound( $gp_prim[1] ) ); if ( is_int( $gp_prim[0] ) && T_VARIABLE === $gp_prim[0] && isset( $danger_cb[ $gp_prim[1] ] ) ) { $gp_wrapped_danger = true; } elseif ( is_int( $gp_prim[0] ) && T_CONSTANT_ENCAPSED_STRING === $gp_prim[0] && $gp_pj === $i - 1 ) { // ONLY when the literal is IMMEDIATELY before the '(' . After walking back // over a group we would be inside a CALL'S ARGUMENT LIST, where a literal is // an argument, not the callee: `channel("system")($_POST['m'])` passes the // name to a developer function. Arm (4g) already owns the grouped form, and // without this test seven fixtures flipped to CRITICAL on clean code. // ACG-147-009: a STRING LITERAL is directly invokable since PHP 7 - // `"system"($_POST['c'])` is the shortest request-controlled command backdoor // there is, 26 bytes with no variable and no factory, and it was invisible on // v1.0.146 too. Resolved through P1 so the concat and paren forms come along. $gp_pr = $resolve_name( $gp_pj ); if ( '' !== $gp_pr[0] && 'str' === $gp_pr[1] && $danger_name( $gp_pr[0] ) ) { $gp_wrapped_danger = true; } } } $j = $i - 1; $d = 0; $hit = false; $hit_super = false; $expect = true; $steps = 0; $traversed = false; $gp_method_call = false; $gp_traversed_call = false; $gp_callee_indirect = false; $gp_callee_danger = false; $gp_lit_bounded = false; while ( $j >= 0 && $steps < 5000 && self::scan_budget_ok() ) { $steps++; $x = $tok[ $j ]; if ( $d > 0 ) { if ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { $d++; } elseif ( $is_char( $x, '(' ) || $is_char( $x, '[' ) ) { $d--; if ( 0 === $d ) { $expect = true; } } elseif ( $is_req( $x ) ) { $hit = true; } $j--; continue; } if ( $expect ) { // ACG-137-B3: record WHICH KIND of group we traversed. ')' means the callee is a call's // return value (unbounded — it can be any callable the callee chose to return); ']' means // the callee came out of a table the developer registered (bounded). $traversed conflated // the two, which is why gating on it alone re-breaks the table dispatchers. if ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { // ACG-137-B3 (self-review round 2): ONLY THE FIRST GROUP DEFINES THE CALLEE // PRIMARY. The walk runs backwards from the callee's '(', so the first group // it crosses is the primary; anything further left is upstream of it. Round 1 // set this flag on ANY ')' anywhere in the chain, which made it sticky: // $this->getHandlers()[$_GET['a']]($_POST['x']) // has a ']' primary (a registered table — bounded — must stay REVIEW), but the // getter's ')' upstream set the flag, so the '->' stopped demoting and a // legitimate framework dispatcher became CRITICAL MALWARE. The direct form // $this->handlers[...]() still passed, which is exactly why my own fixtures // missed it. Guarding on ! $traversed pins the flag to the primary itself. if ( ! $traversed && $is_char( $x, ')' ) ) { $gp_traversed_call = true; } $d = 1; $traversed = true; $j--; continue; } // ACG-106 fresh-eyes (2026-07-01): a VARIABLE callee primary ($_POST['x']() or a tainted // $c()) is request-controlled. A literal function NAME in PLAIN callee position is a normal // static call — even a request READER (filter_input(), getallheaders()): calling filter_input // is not "calling request-controlled code", so a bare reader call no longer makes a review // item. BUT if we traversed the reader's own (...)/[...] first, it is the reader's RETURN // VALUE / element that is being called (filter_input(..)(), getallheaders()['x']()) — that IS // a request-driven callee → keep it as a review item ($traversed gate). if ( is_int( $x[0] ) && ( T_VARIABLE === $x[0] || T_STRING === $x[0] ) ) { // ACG-149-006: socket-derived bytes are request-equivalent for a dynamic callee too. // `$s=fsockopen(); $c=fgets($s); $c();` was silent while the identical // shape fed from $_POST was critical. The demotion rules below (bounded // table / method call / indirect primary) still apply, so validated // dispatchers stay out of red exactly as before. if ( T_VARIABLE === $x[0] && ( $is_req( $x ) || isset( $gp_sock_data[ $x[1] ] ) ) ) { $hit = true; if ( $gp_name_bound( $x[1] ) ) { $gp_lit_bounded = true; } if ( $is_super( $x ) ) { $hit_super = true; } elseif ( isset( $tainted[ $x[1] ] ) && 2 === (int) $tainted[ $x[1] ] ) { $gp_callee_indirect = true; } } // ACG-138-R2-02b: indirect callee taint → review, not malware (+ACG-149-130: a name-bounded callee too) // ACG-139-001: the callee variable holds a factory-produced DANGEROUS callable // (`$f = Closure::fromCallable('system')`). Not request-derived, so $is_req is // false — but calling it with request data is a command executed on that data. // ACG-143-012 (adversarial review): `new $class(...)` is a CLASS position. A // literal like 'Assert' / 'Exec' collides with a dangerous FUNCTION name, but an // instantiation can never invoke that function -- it constructs a class of that // name. Ordinary namespaced factories (`$class = 'Assert'; new $class($_POST[..])`) // were reported as CRITICAL malware. elseif ( T_VARIABLE === $x[0] && isset( $danger_cb[ $x[1] ] ) && ! ( $j > 0 && is_int( $tok[ $j - 1 ][0] ) && T_NEW === $tok[ $j - 1 ][0] ) ) { $gp_callee_danger = true; } elseif ( $traversed && T_STRING === $x[0] && $is_fn( $x, $req_read ) ) { $hit = true; } $expect = false; $j--; continue; } break; } if ( is_int( $x[0] ) && ( T_OBJECT_OPERATOR === $x[0] || T_DOUBLE_COLON === $x[0] || T_NS_SEPARATOR === $x[0] ) ) { // ACG-137-B3: THE DEMOTION MUST BE GOVERNED BY THE CALLEE PRIMARY ITSELF. // // This set $gp_method_call on ANY -> / :: anywhere in the chain, so: // Closure::fromCallable( $_POST['f'] )( $_POST['a'] ) // — raw superglobal callee, raw superglobal argument, a textbook webshell — was demoted // to a REVIEW ITEM. The walk had already skipped the (...) of fromCallable and then met // the '::' of Closure::fromCallable, which belongs to the INNER call, not to the callee. // The justification in the comment above ("can only reach a method that EXISTS ON THAT // CLASS — a bounded, developer-defined set") is TRUE for $this->$m(), and FALSE for a // return value: Closure::fromCallable($_POST['f']) returns whatever callable the request // names, `system` included. The rule was right; its SCOPE was wrong. // // $gp_traversed_call is exactly the signal that the operator is upstream of a group whose // RESULT is the callee — and it was already being computed here, just never read. // Deliberately NOT gated on $traversed (which is also true for a ']'): that would undo // the bounded-table demotion and put a red malware alarm back on Elementor's // $this->handlers[$_GET['a']]() dispatcher. Traversing '(' = unbounded (do not demote); // traversing '[' = a registered table (keep demoting). if ( ( T_OBJECT_OPERATOR === $x[0] || T_DOUBLE_COLON === $x[0] ) && ! $gp_traversed_call ) { $gp_method_call = true; } $expect = true; $j--; continue; } break; } // ACG-148-015 (self-review, second siege): a coverage notice on step-cap exhaustion was // REMOVED here. It fired on a legitimate large immediately-invoked closure // (`$x = (function(){ …250-entry config array… })()`): the backward callee walk dives into // the closure's preceding group and spends its 5000-step budget on the BODY, not on callee // depth, so an ordinary compiled-config / DI-container idiom got flagged "partially // scanned". The only thing the notice caught was a callee obfuscated with >1666 SUBSCRIPTS // — a construct no real code produces, already bounded by the file-size and memory limits — // so the FP on legitimate closures far outweighed it. That synthetic evasion is now an // accepted, documented engine limit (like the other step caps throughout this file). if ( $gp_wrapped_danger ) { $gp_callee_danger = true; } if ( $gp_prim_bound ) { $gp_lit_bounded = true; } // ACG-149-130b: `($fn)($_POST)` keeps the bound // ACG-149-130d (adversarial pass): if the resolver has PROVEN the callee is a dangerous name, // "no dangerous name can contain this literal" is a contradiction, not a bound. Belt-and-braces // against any future way of reaching a wrong bound: the proof of danger always wins. if ( $gp_callee_danger ) { $gp_lit_bounded = false; } if ( $hit_super ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } elseif ( $hit || $gp_callee_danger ) { // ACG-122 (audit 2026-07-16): the ONE-VARIABLE-HOP webshell. // // ACG-110 moved obf_var_func to the smell list on the reasoning that the malicious form // "stays malware as tk_dyn_request_callee (direct) / obf_varvar_func_input". That reasoning // does not hold for one variable hop: `$f = $_POST['f']; $f($_POST['a']);` is neither the // DIRECT form ($_POST['f'](...) — needs $hit_super) nor the var-var form (${$_GET['v']}()), // so its only findings were smells and the file landed under a green "No malware found" // headline with total_threats = 0. That is a textbook webshell reported as clean. // // Reclassifying a smell is only FN-safe if the DANGEROUS sub-case keeps a detector of its // own. This is that detector — deliberately NARROW, so the ACG-110 false-positive work is // not undone: a tainted callee ALONE stays a review item (that is the TGMPA / router / // validated-dispatcher shape the taint engine cannot tell apart, because it cannot see // in_array()/allowlist guards). It only becomes malware when the call ALSO takes RAW // request data as an argument — i.e. both WHAT to run and WHAT to run it on come straight // from the request. A validated dispatcher checks the callee against an allowlist and // passes structured arguments; it does not hand the raw superglobal straight through. // Args are matched on $is_super / $req_read only (raw request), NOT on $is_tainted, to // keep the rule tight. // // SECOND narrowing, and the corpus is why it exists: a first cut of this rule flagged // Elementor's template-library manager — `$action = get_super_global_value($_REQUEST, // 'library_action'); ... if (in_array($action, $whitelist_methods, true)) { $this->$action // ($_REQUEST); }` — as CRITICAL MALWARE. That code is guarded by a capability check, a // nonce verification AND an in_array() allowlist, none of which the taint engine can see; // it is exactly the legitimate dispatcher ACG-110 protected, and shipping it would have // put a red malware alarm on millions of Elementor sites. // The principled difference: `$this->$m()` / `Foo::$m()` can only reach a method that // EXISTS ON THAT CLASS — a bounded, developer-defined set. A PLAIN `$f()` can reach ANY // php function, `system` included. Only the plain form is a webshell, so method/static // dispatch stays a review item ($gp_method_call). Verified: fixtures 14/14, clean corpus // 33 -> 33 with ZERO new findings. $gp_ad = 1; $gp_ak = $i + 1; $gp_arg_req = false; $gp_as = 0; while ( $gp_ak < $n && $gp_ad > 0 && $gp_as < 5000 && self::scan_budget_ok() ) { $gp_as++; $gp_ax = $tok[ $gp_ak ]; if ( $is_char( $gp_ax, '(' ) ) { $gp_ad++; } elseif ( $is_char( $gp_ax, ')' ) ) { $gp_ad--; } // ACG-135-002 (review round 3): a SANITISED request value counts too. // $f = $_POST['f']; $a = sanitize_text_field($_POST['a']); $f($a); // The first cut matched raw request args only ($is_super/$req_read), so this shape // stayed a review item. sanitize_text_field() strips HTML/control characters — it is // not a callable allowlist and not shell escaping, so it does nothing to make the // argument safe for system()/exec()/passthru(). What makes this malware is the // CALLEE being attacker-chosen; the argument only has to be attacker-influenced. // $is_tainted covers the sanitised/derived case; the callee narrowness (tainted // variable + plain $f(), never $this->$m()) is what keeps dispatchers out. elseif ( $is_super( $gp_ax ) || $is_fn( $gp_ax, $req_read ) || $is_tainted( $gp_ax ) ) { $gp_arg_req = true; } $gp_ak++; } // ACG-140-001 (adversarial review): $gp_callee_danger was OR'd IN FRONT of the demotions, // so it also bypassed the bounded-table demotion ACG-137-B3 added to keep Elementor-style // `$this->handlers[...]` dispatchers out of red. It is not needed here at all: the // fromCallable arm already sets $hit for a dangerous callee, so the ordinary condition // reports it — while a genuinely bounded/method primary still demotes, as it must. // THIRD narrowing, ACG-149-130 (FP round, self-found - and it is the WordPress AJAX router): // $act = sanitize_key( $_POST['act'] ); // $fn = 'su_ajax_' . $act; // if ( function_exists( $fn ) ) { $fn( $_POST ); } // Eight realistic dispatchers of this shape were reported as CRITICAL MALWARE. It is the same // principle the method-dispatch narrowing above rests on - "can only reach a bounded set" - just // proved differently: `$this->$m()` is bounded by the CLASS, and `'su_ajax_' . $x` is bounded by // the LITERAL, because a concatenation keeps its literal parts and no dangerous name contains // "su_ajax_". So the callee cannot be system/exec/eval whatever the request supplies, and it // stays a review item ($hit -> tk_dyn_superglobal_call) exactly like the Elementor case. // The literals that CAN complete into a dangerous name keep firing: "sys"."tem", $x."tem", // "system".$pad, "" . $_POST['f'] - see $gp_lit_bounds / $gp_bound_rhs. if ( $gp_arg_req && ! $gp_method_call && ! $gp_callee_indirect && ! $gp_sub_table && ! $gp_lit_bounded ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee_var', 'name' => 'Request-Controlled Dynamic Call (via variable)', 'severity' => 'critical' ); } elseif ( $hit ) { // ACG-140-001: only a REQUEST-influenced callee ($hit) degrades to the review item. // A factory-produced dangerous callable ($gp_callee_danger) that is invoked WITHOUT // request data is ordinary code — `$f = Closure::fromCallable('call_user_func'); // $f('do_action','init');` is a normal idiom, and my first cut set $hit for it and so // put a review item on every such call. Emit nothing for that case. $found['dyn'] = array( 'id' => 'tk_dyn_superglobal_call', 'name' => 'Dynamic Call From Request', 'severity' => 'critical' ); } } } } $prev_op = ( $i > 0 && is_int( $tok[ $i - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $i - 1 ][0] || T_DOUBLE_COLON === $tok[ $i - 1 ][0] || T_FUNCTION === $tok[ $i - 1 ][0] ) ); // (2) extract()/parse_str() of request data. $gp_xf = $called_fn( $i ); if ( ( 'extract' === $gp_xf || 'parse_str' === $gp_xf ) ) { $k = $i + 2; $d = 1; $hit = false; $gp_x2arg = false; while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { $x = $tok[ $k ]; if ( $is_char( $x, '(' ) || $is_char( $x, '[' ) ) { $d++; } elseif ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { $d--; } elseif ( 1 === $d && $is_char( $x, ',' ) ) { $gp_x2arg = true; } elseif ( $is_super( $x ) || $is_tainted( $x ) ) { $hit = true; } $k++; } // ACG-149-085 (self-review): tk_extract_superglobal is SCOPE POLLUTION - only the ONE-argument form // creates request-named variables in the current scope. `parse_str($str, $result)` (two args) stores the // parsed pairs in $result and pollutes nothing, so it is SAFE - firing on it branded WP core's own // URL/query parsing (`$u.=$_SERVER['REQUEST_URI']; parse_str(parse_url($u)['query'],$qv)`) CRITICAL (FP). // extract() has no such safe form. A request map captured into $result is still followed by the by-ref // taint arm, so a real `parse_str($_POST,$m); $m[$_GET]()` dispatch still fires (as tk_dyn_request_callee). if ( $hit && ! ( 'parse_str' === $gp_xf && $gp_x2arg ) ) { $found['extract'] = array( 'id' => 'tk_extract_superglobal', 'name' => 'Extract Request Vars', 'severity' => 'medium' ); } } // (3) eval/assert whose argument uses request data OR reads an external stream/file. $is_eval = ( is_int( $e[0] ) && T_EVAL === $e[0] ); $is_assert = ( is_int( $e[0] ) && T_STRING === $e[0] && 'assert' === strtolower( $e[1] ) ); if ( ( $is_eval || $is_assert ) && ! $prev_op && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $d = 1; $k = $i + 2; $concat = ''; $hit = false; // ACG-149-026: for ASSERT only, track whether a tainted token is inside a bool/numeric // guard call or the argument carries a top-level comparison - either means it is tested, // not eval'd. eval() is unaffected (a comparison there can still reach code via a ternary). $gp_ev_guard = array(); $gp_ev_prevfn = ''; $gp_ev_cmp = false; $gp_ev_ternary = false; // ACG-149-041 while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { $x = $tok[ $k ]; if ( $is_char( $x, '(' ) ) { $gp_ev_guard[] = ( '' !== $gp_ev_prevfn && isset( $gp_bool_guards[ $gp_ev_prevfn ] ) ); $gp_ev_prevfn = ''; $d++; } elseif ( $is_char( $x, ')' ) ) { if ( ! empty( $gp_ev_guard ) ) { array_pop( $gp_ev_guard ); } $gp_ev_prevfn = ''; $d--; } elseif ( $is_assert && 1 === $d && is_int( $x[0] ) && in_array( $x[0], array( T_IS_IDENTICAL, T_IS_NOT_IDENTICAL, T_IS_EQUAL, T_IS_NOT_EQUAL, T_IS_SMALLER_OR_EQUAL, T_IS_GREATER_OR_EQUAL, T_SPACESHIP, T_BOOLEAN_AND, T_BOOLEAN_OR, T_LOGICAL_AND, T_LOGICAL_OR ), true ) ) { $gp_ev_cmp = true; } elseif ( $is_assert && 1 === $d && ( $is_char( $x, '<' ) || $is_char( $x, '>' ) ) ) { $gp_ev_cmp = true; } // ACG-149-041 (siege 5 #8/#10): a top-level ternary '?' means a comparison is only the // CONDITION; the branch value can still be eval-code, so the comparison must not suppress. elseif ( $is_assert && 1 === $d && $is_char( $x, '?' ) ) { $gp_ev_ternary = true; } // ACG-148 (self-review, agent 1): a bare $stream_read here treated ANY file read as tainted, // so eval(file_get_contents('/fixed/tpl.php')) — a legitimate cache/template loader — was // called CRITICAL. The only request channel a stream read adds over the checks below is // php://input, and that is already caught by the concat scan (its literal lands in $concat). // So the read function itself is not a taint source; its ARGUMENT is (super/tainted/req/php://input). elseif ( ( $is_super( $x ) && ! $gp_srv_path( $k ) ) || $is_tainted( $x ) || $is_fn( $x, $req_read ) || $gp_remote_in( $k ) ) { // ACG-149-026: for assert, a value inside is_string()/intval()/count()/... is tested, not code. $gp_ev_ing = false; if ( $is_assert ) { foreach ( $gp_ev_guard as $gp_ev_g ) { if ( $gp_ev_g ) { $gp_ev_ing = true; break; } } } if ( ! $gp_ev_ing ) { $hit = true; } $gp_ev_prevfn = ''; } elseif ( is_int( $x[0] ) && T_STRING === $x[0] ) { $gp_ev_prevfn = strtolower( (string) $x[1] ); } elseif ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $concat .= $decode( $x[1] ); $gp_ev_prevfn = ''; } $k++; } if ( ( $hit && ! ( $is_assert && $gp_ev_cmp && ! $gp_ev_ternary ) ) || false !== strpos( strtolower( $concat ), 'php://input' ) ) { $found['evalin'] = array( 'id' => 'tk_eval_request', 'name' => 'Eval Request Data', 'severity' => 'critical' ); } } // (4) include/require of request data. // ACG-107 fresh-eyes (2026-07-01): split like the dynamic-call sink. A superglobal DIRECTLY in the // include path (a raw request value used directly as the include target) is a confirmed request-driven include → malware. A tainted VARIABLE // (include $plugin_page where $plugin_page came from $_GET) is the validated-admin-page-loader pattern that // WordPress core itself (wp-admin/admin.php, update.php) and plugins (Yoast tools.php) use — guarded by // validate_file()/plugin_basename()/in_array() allowlists the taint engine cannot see. Flagging the // indirect form as a red threat false-positived WP core on every offline site. Indirect → review. if ( is_int( $e[0] ) && ( T_INCLUDE === $e[0] || T_INCLUDE_ONCE === $e[0] || T_REQUIRE === $e[0] || T_REQUIRE_ONCE === $e[0] ) ) { $k = $i + 1; $d = 0; $hit = false; $hit_super = false; $gp_wpfeed = false; $gp_path = ''; $gp_run = false; for ( ; $k < $n && self::scan_budget_ok(); $k++ ) { $x = $tok[ $k ]; // ACG-140-002b: a bracket/paren ENDS a literal concatenation run too. These branches // `continue` before the run bookkeeping below, so without resetting here the run survived // across a subscript and fused unrelated literals — `include( $base['wp-'] . 'feed.php' )` // fused the ARRAY KEY with the next literal and reported CRITICAL malware. if ( $is_char( $x, '(' ) || $is_char( $x, '[' ) ) { $d++; $gp_path = ''; $gp_run = false; continue; } if ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { if ( 0 === $d ) { break; } $d--; $gp_path = ''; $gp_run = false; continue; } if ( 0 === $d && $is_char( $x, ';' ) ) { break; } // ACG-140-002b (adversarial review): a PHP CLOSE TAG also terminates a statement. Without // this, the scan ran to EOF on the ordinary template idiom "include locate_template(..)" // followed by a close tag instead of a semicolon — WP core, Elementor, CF7 and every // Twenty* theme do this — swallowing every literal in the rest of the file. A // malware-CLEANUP plugin listing the backdoor filename further down was then reported as // CRITICAL malware. It also disproved my own earlier comment claiming prose "can never // open this branch": prose AFTER an unterminated include did exactly that. // (Do not write the close tag literally here — it would end this PHP block mid-comment.) if ( 0 === $d && is_int( $x[0] ) && T_CLOSE_TAG === $x[0] ) { break; } // ACG-149-024: a LITERAL server-set key ($_SERVER['DOCUMENT_ROOT']) is not request // data here either - `require $_SERVER['DOCUMENT_ROOT'].'/wp-load.php'` is the // canonical WordPress bootstrap, not a request-path include. // ACG-149-081 (siege 14 #7): a request key that only PICKS which entry of a FIXED view/template // table is included (`$views=array('list'=>'list.php',..); require $dir.$views[$_GET['view']]` or // `include $this->tpl[$_GET['v']]`) contributes no path bytes of its own - the same bounded-selector // reasoning the shell/callee arms apply. A super used only as a boolean condition is likewise not a // path. A super taken DIRECTLY as the path (`include $_GET['page'].'.php'`) is not a fixed key and // still fires. if ( $is_super( $x ) && ! $gp_srv_path( $k ) && ! $gp_super_is_fixedkey( $k ) && ! $gp_super_is_cond( $k ) ) { $hit_super = true; } elseif ( $is_tainted( $x ) || $is_fn( $x, $req_read ) || $gp_remote_in( $k ) ) { $hit = true; } // ACG-149-033: socket bytes too // ACG-139-002 (reviewer 2, 2026-07-17): the WP-VCD loader, detected on ACTIVE CODE ONLY. // This replaces the wpfeed_2 CONTENT signature I shipped in v1.0.139, which was a raw-content // regex and therefore blind to context: it reported CRITICAL MALWARE for the filename inside a // COMMENT (`// include_once(... "/../../wp-feed.php")`) and inside an ordinary STRING // (`echo "to install, include wp-feed.php manually"`). A critical, never-downgrade verdict on a // code comment is exactly the false positive this round exists to eliminate — my own regression. // Here it is token-driven, so it is sound by construction: the token list DROPS comments, and a // string literal is ONE token, so the word "include" inside prose is not a T_INCLUDE and can // never open this branch. Only a real include/require STATEMENT whose path expression names the // dropped backdoor matches. // ACG-140-002 (adversarial review): accumulate EVERY literal form in the path expression. // My first cut looked only at T_CONSTANT_ENCAPSED_STRING and so REGRESSED two shapes the // old regex did catch — a double-quoted interpolated path `include("$dir/wp-feed.php")` // and a heredoc path — because both tokenise as T_ENCAPSED_AND_WHITESPACE, not as a // constant string. It also left a one-token evasion: `include('wp-'.'feed.php')`, two // literals neither of which contains the name. Both are closed by testing each segment // AND their concatenation (the same accumulate-then-test shape the eval arm uses). $gp_seg = ''; if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $gp_seg = $decode( $x[1] ); } elseif ( is_int( $x[0] ) && defined( 'T_ENCAPSED_AND_WHITESPACE' ) && T_ENCAPSED_AND_WHITESPACE === $x[0] ) { $gp_seg = (string) $x[1]; } if ( '' !== $gp_seg ) { // ACG-140-002b (adversarial review): the run may only continue across a literal '.' // concatenation. Blindly appending EVERY literal in the expression fused unrelated // fragments into the backdoor name and reported ordinary path-building as CRITICAL // malware — a false positive my own concat fix introduced: // include( str_replace('wp-','',$name) . 'feed.php' ); // 'wp-' + 'feed.php' // include( $dir . '/wp-' . $type . 'feed.php' ); // split by a variable // include( $base['wp-'] . 'feed.php' ); // literal is an ARRAY KEY // A variable, a call argument, a comma or a bracket BREAKS the run (handled below), so // only genuinely adjacent literals fuse. $gp_path = $gp_run ? ( $gp_path . $gp_seg ) : $gp_seg; $gp_run = false; // only a following '.' revives it if ( $names_backdoor( $gp_seg ) ) { $gp_wpfeed = true; } // single-literal / ternary arm if ( $names_backdoor( $gp_path ) ) { $gp_wpfeed = true; } // 'wp-' . 'feed.php' } elseif ( $is_char( $x, '.' ) ) { $gp_run = true; // concatenation keeps the run alive } elseif ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $const_str[ $x[1] ] ) ) { // ACG-148-014 (self-review, siege [15]): resolve an include target held in a VARIABLE // through P2, so `$f = 'wp-feed.php'; include $f;` — the decomposed remote-loader form — // is caught like the literal / concat paths. $const_str is per-scope and retired on // rebinding, so this carries no stale value; wp-feed.php is a known loader name no // legitimate plugin includes via a variable. if ( $names_backdoor( (string) $const_str[ $x[1] ][0] ) ) { $gp_wpfeed = true; } $gp_path = ''; $gp_run = false; } else { $gp_path = ''; $gp_run = false; // anything else ends it } } // Ordered most-specific first: a named WP-VCD loader is a confirmed backdoor, not a generic // request-path include. is_malware_name is false-by-shape here (it is an ACTIVE sink), so it // inherits never_downgrade via the wp_malware execution-category rule, like wpvcd_2. if ( $gp_wpfeed ) { $found['inc'] = array( 'id' => 'tk_wpfeed_loader', 'name' => 'WP-Feed Backdoor Loader', 'severity' => 'critical' ); } elseif ( $hit_super ) { $found['inc'] = array( 'id' => 'tk_include_request', 'name' => 'Include Request Path', 'severity' => 'high' ); } elseif ( $hit ) { $found['inc'] = array( 'id' => 'tk_include_request_var', 'name' => 'Include From Request Variable', 'severity' => 'high' ); } } // (4c) CALLABLE FACTORY — `Closure::fromCallable()` (ACG-139-001, reviewer 2, 2026-07-17). // // The callee walk only asks whether the callable is REQUEST-derived, so it caught // `Closure::fromCallable($_POST['f'])(…)` and `$f=$_POST['f']; Closure::fromCallable($f)(…)` // but returned NO FINDINGS for a LITERAL dangerous name: // Closure::fromCallable('system')($_POST['cmd']); // <- trivial bypass, undetected // Closure::fromCallable('assert')($_POST['x']); // That is the China-Chopper idea in a new wrapper: wrapping a command function in a factory // runs the command on the request value just the same — the same reasoning that already puts // `call_user_func('system', $_POST[..])` in $danger for the callback APIs (ACG-105). // // Both consumption shapes are covered, because the 2-step form is the same axis and was also // undetected (verified): the IMMEDIATE invocation `fromCallable('system')($_POST[..])`, and the // ASSIGNED form `$f = fromCallable('system'); $f($_POST[..]);` (recorded in $danger_cb and // reported at the callee walk). // // FP GUARD (reviewer 2 asked for this explicitly): an ARRAY/OBJECT callable // `Closure::fromCallable([$obj,'method'])` must NOT become critical just because the METHOD is // named `exec`/`extract`/`assert` — it can only reach a method on that object, never the global // function. Same bounded-set reasoning as R2-01. `$cb_obj` gates it, and a request argument is // still required, so an ordinary `fromCallable('strlen')` factory stays clean. // ACG-147-004: the METHOD half is an operand too - `Closure::$m(...)` with $m='fromCallable' // reaches the same factory. Resolved through P1 so a variable / concat / literal all work. $gp_fc_m = ''; if ( $i > 0 && is_int( $tok[ $i - 1 ][0] ) && T_DOUBLE_COLON === $tok[ $i - 1 ][0] && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { if ( is_int( $e[0] ) && T_STRING === $e[0] ) { $gp_fc_m = strtolower( (string) $e[1] ); } else { $gp_fc_r = $resolve_name( $i ); if ( '' !== $gp_fc_r[0] ) { $gp_fc_m = strtolower( $gp_fc_r[0] ); } } } // ACG-147-004: the CLASS half is an OPERAND. `$c::`, `("Closure")::`, `("Clo"."sure")::` and // `$c` holding the name all reach PHP's own \Closure; only a single token was accepted before. $gp_fc_cls = false; if ( 'fromcallable' === $gp_fc_m && $i - 2 >= 0 ) { // Find where the class operand STARTS, then resolve FORWARD from there with P1. // A ')' means the operand is a parenthesised expression - walk back to its '('. // Anything else is a single token (a bareword or a variable). $gp_cs2 = $i - 2; if ( $is_char( $tok[ $gp_cs2 ], ')' ) ) { $gp_cd2 = 1; $gp_cw2 = 0; while ( $gp_cs2 > 0 && $gp_cw2++ < 200 ) { $gp_cs2--; if ( $is_char( $tok[ $gp_cs2 ], ')' ) ) { $gp_cd2++; } elseif ( $is_char( $tok[ $gp_cs2 ], '(' ) ) { $gp_cd2--; if ( 0 === $gp_cd2 ) { break; } } } } $gp_fc_cls = ( $gp_cs2 >= 0 ) && $class_operand_is_global( $gp_cs2, 'closure' ); } if ( 'fromcallable' === $gp_fc_m && $gp_fc_cls ) { $k = $i + 2; $d = 1; $cb_danger = false; $cb_obj = false; $cb_tainted = false; $steps = 0; $cb_concat = ''; while ( $k < $n && $d > 0 && $steps < 5000 && self::scan_budget_ok() ) { $steps++; $x = $tok[ $k ]; if ( $is_char( $x, '(' ) ) { $d++; } elseif ( $is_char( $x, ')' ) ) { $d--; if ( 0 === $d ) { break; } } else { // ACG-141-004: NOT depth-gated. Gating on `1 === $d` let one extra paren hide the name // (`fromCallable(('system'))`, `'sys' . ('tem')`) while the callback-API arm — which is // not depth-gated — caught the identical shape. Two arms of one model must not disagree. if ( $is_char( $x, '[' ) || ( is_int( $x[0] ) && ( T_ARRAY === $x[0] || T_OBJECT_OPERATOR === $x[0] || T_DOUBLE_COLON === $x[0] ) ) ) { $cb_obj = true; } elseif ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] ) { $nm = strtolower( trim( $decode( $x[1] ) ) ); if ( $danger_name( $nm ) ) { $cb_danger = true; } $cb_concat .= $nm; // ACG-140-001: fuse split literals — see below } // ACG-141-002: a REQUEST-DERIVED callable in the factory. The `(...)` invocation form was // covered by the callee walk, but the object forms below are not reachable from it, so // the factory arm has to recognise it itself. // ACG-145-002: a VARIABLE proven to hold a dangerous callable is exactly as // dangerous as the literal spelled in place. $danger_cb is per-function scoped // and retired on rebinding, so this inherits those guarantees. elseif ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $danger_cb[ $x[1] ] ) ) { $cb_danger = true; } elseif ( ( $is_super( $x ) && ! $gp_srv_path( $k ) ) || $is_tainted( $x ) || $is_fn( $x, $req_read ) || $gp_remote_in( $k ) ) { $cb_tainted = true; } } $k++; } // ACG-140-001 (adversarial review): `Closure::fromCallable('sys' . 'tem')` is a ONE-TOKEN // evasion of the fix above — two literals, neither of which is a dangerous name. Testing the // fused literal closes it, the same accumulate-then-test shape the include arm uses. if ( ! $cb_danger && '' !== $cb_concat && $danger_name( $cb_concat ) ) { $cb_danger = true; } // ACG-149-089 (external reviewer round 3, MS-001): the factory ARGUMENT is an OPERAND - resolve the // WHOLE arg through P1 ($resolve_name), so a transform (strrev/base64_decode/str_rot13), a concat, or a // const-var producing a dangerous GLOBAL name is caught, exactly as the call_user_func sibling already // does. `Closure::fromCallable(strrev('metsys'))(..)` was invisible while // `call_user_func('Closure::fromCallable', strrev('metsys'))(..)` fired. An array-callable arg resolves // to '' (FG guard intact); a harmless name fails $danger_name. // ACG-149-102 (round 11, R10-003): also run when $cb_obj is set even if $cb_danger already fired. An // INLINE array callable `(["system"])[0]` makes the token-walk set BOTH $cb_danger (it sees the "system" // literal) AND $cb_obj (it sees the `[`), so the old `! $cb_danger` guard skipped the $cb_obj-clearing // resolve and the bounded-object flag survived. Resolving the WHOLE arg proves it is a hidden NAME. if ( ! $cb_danger || $cb_obj ) { // ACG-149-091 (round 4, MS-002): a class-constant arg (`C::F`) sets $cb_obj via its `::`, but if the // WHOLE arg resolves to a dangerous callable STRING it is a hidden NAME, not a bounded method - so // resolve regardless of $cb_obj and, on a dangerous hit, clear it. A genuine `Foo::method` / // `[$obj,'m']` never resolves through P1, so it stays bounded (FG guards intact). $gp_fc_ar = $resolve_name( $i + 2 ); if ( '' === $gp_fc_ar[0] ) { $gp_fc_ial = $gp_inline_arr_leaf( $i + 2 ); if ( '' !== $gp_fc_ial ) { $gp_fc_ar = array( $gp_fc_ial, 'str' ); } } // ACG-149-102 (R10-003): inline `(["system"])[0]` arg // ACG-149-126 (round 24c): try the value-return model whenever what we have is not ITSELF a // dangerous name. `Closure::fromCallable("current")($cb)` resolves to "current" - harmless - so // gating on "resolved nothing" skipped the model and never looked at the array slot behind it. if ( '' === $gp_fc_ar[0] || ! $danger_name( ltrim( strtolower( trim( (string) $gp_fc_ar[0] ) ), '\\' ) ) ) { $gp_fc_vr = $gp_arr_valret( $i + 2 ); if ( '' !== $gp_fc_vr[0] ) { $gp_fc_ar = array( $gp_fc_vr[0], 'str' ); } } // ACG-149-123 (R22-001): `Closure::fromCallable(array_pop($cb))` if ( '' === $gp_fc_ar[0] ) { $gp_fc_ial = $gp_var_arr_leaf( $i + 2 ); if ( '' !== $gp_fc_ial ) { $gp_fc_ar = array( $gp_fc_ial, 'str' ); } } // ACG-149-104 (R11-001): a `$cb[0]` arg from a literal/keyed/APPENDED danger slot if ( '' !== $gp_fc_ar[0] && $danger_name( ltrim( strtolower( trim( (string) $gp_fc_ar[0] ) ), '\\' ) ) ) { $cb_danger = true; $cb_obj = false; } } if ( ( $cb_danger || $cb_tainted ) && ! $cb_obj ) { // ACG-141-002 (reviewer 2): a Closure is an OBJECT, so the produced callable is invokable // three ways — and only the first was covered, which is exactly the "one shape at a time" // trap he called out: // Closure::fromCallable('system')( $_POST['a'] ); // direct // Closure::fromCallable('system')->__invoke( $_POST['a'] ); // object invocation // Closure::fromCallable('system')->call( $obj, $_POST['a'] ); // rebound invocation // All three execute the same command on the same request data, so all three are found here. // ACG-141-004: ask the shared helper WHERE the invocation args are, instead of testing // fixed offsets. That closes `(Closure::fromCallable('system'))($_POST)` (a wrapping // paren shifted every offset) and `->bindTo(null)($_POST)` (a 4th invocation form the // enumeration simply did not list). $inv = $invocation_args( $k, $wrap_before( $i - 2 ) ); if ( $inv ) { // Require request data in the invocation args, so a factory invoked on developer data is // not swept in. For ->call() the first argument is the bound object; scanning the whole // list is deliberately conservative and cannot miss the request value. $a = $inv; $ad = 1; $areq = false; $asteps = 0; while ( $a < $n && $ad > 0 && $asteps < 5000 && self::scan_budget_ok() ) { $asteps++; $ax = $tok[ $a ]; if ( $is_char( $ax, '(' ) ) { $ad++; } elseif ( $is_char( $ax, ')' ) ) { $ad--; } elseif ( $is_super( $ax ) || $is_fn( $ax, $req_read ) || $is_tainted( $ax ) ) { $areq = true; } $a++; } if ( $areq ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } } elseif ( $cb_danger && ( $gp_bt = $i - 2 - $wrap_before( $i - 2 ) - 1 ) >= 1 && $is_char( $tok[ $gp_bt ], '=' ) && is_int( $tok[ $gp_bt - 1 ][0] ) && T_VARIABLE === $tok[ $gp_bt - 1 ][0] ) { // ASSIGNED form: `$f = Closure::fromCallable('system');` — tok[i-2] is the class name, // tok[i-3] the '=', tok[i-4] the target variable. Reported when $f is later invoked. // (A request-derived callable needs no entry here: the RHS taints $f the normal way.) $danger_cb[ $tok[ $gp_bt - 1 ][1] ] = 1; } } } // (4c-value) ACG-149-088 (external reviewer, pre-1.0.2 BLOCKER) — Closure::fromCallable spelled // as a STRING or ARRAY *value* and invoked directly. (4c) keyed on the T_DOUBLE_COLON token, so // it caught `Closure::fromCallable('system')($_POST['a'])` but NOT the identical webshell written // as a runtime callable VALUE, which PHP resolves to the very same global \Closure::fromCallable: // ("Closure::fromCallable")("system")($_POST['a']); // parenthesised string // ("Closure"."::fromCallable")("system")($_POST['a']); // concatenated string // $f="Closure::fromCallable"; $f("system")($_POST['a']); // string in a variable // (["Closure","fromCallable"])("system")($_POST['a']); // inline array callable // $cb=["Closure","fromCallable"]; $cb("system")($_POST['a']);// array in a variable // All five returned NO findings. FP GUARD: only PHP's GLOBAL \Closure fires. A runtime STRING // class name is FULLY QUALIFIED (namespace/imports do NOT apply), so "Closure" (no interior '\') // is global but "Vendor\Closure" is a different, vendor-defined class — the $gp_fc_global_pair / // $gp_fc_global_arr helpers enforce exactly that, so the Vendor\Closure forms stay clean. The // ::-token forms (FC/FG) never enter here (their factory '(' is preceded by `fromCallable`, a // T_STRING), so (4c) still owns them and its $cb_obj / request-arg guards are unaffected. if ( $is_char( $e, '(' ) && $i > 0 ) { $gp_fcv_global = false; $gp_fcp = $tok[ $i - 1 ]; if ( is_int( $gp_fcp[0] ) && T_VARIABLE === $gp_fcp[0] ) { // `$f( ... )` — the callee is a variable holding the callable VALUE. if ( isset( $gp_fc_arr[ $gp_fcp[1] ] ) ) { $gp_fcv_global = true; // array-var form } else { $gp_fcr = $resolve_name( $i - 1 ); // string-var form (via $const_str) if ( 'str' === $gp_fcr[1] && false !== ( $gp_dc = strpos( $gp_fcr[0], '::' ) ) ) { $gp_fcv_global = $gp_fc_global_pair( substr( $gp_fcr[0], 0, $gp_dc ), substr( $gp_fcr[0], $gp_dc + 2 ) ); } } } elseif ( $is_char( $gp_fcp, ')' ) ) { // `( )( ... )` — the callee is a PARENTHESISED value. Walk back to the matching '('. $gp_pp = $i - 1; $gp_pd = 0; $gp_ps = 0; while ( $gp_pp >= 0 && $gp_ps++ < 5000 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_pp ], ')' ) ) { $gp_pd++; } elseif ( $is_char( $tok[ $gp_pp ], '(' ) ) { $gp_pd--; if ( 0 === $gp_pd ) { break; } } $gp_pp--; } // The '(' is a GROUPING paren (the group IS the callee) only when it does NOT open a // call/subscript argument list — otherwise `foo("Closure::fromCallable")(...)` would misread // foo's ARGUMENT as the callee. Same exclusion (4g) uses. $gp_intro = ( $gp_pd === 0 && $gp_pp > 0 && ( ( is_int( $tok[ $gp_pp - 1 ][0] ) && ( T_STRING === $tok[ $gp_pp - 1 ][0] || T_VARIABLE === $tok[ $gp_pp - 1 ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $gp_pp - 1 ][0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $gp_pp - 1 ][0] ) || ( defined( 'T_NAME_RELATIVE' ) && T_NAME_RELATIVE === $tok[ $gp_pp - 1 ][0] ) ) ) || $is_char( $tok[ $gp_pp - 1 ], ')' ) || $is_char( $tok[ $gp_pp - 1 ], ']' ) ) ); if ( 0 === $gp_pd && $gp_pp >= 0 && ! $gp_intro ) { $gp_fcr = $resolve_name( $gp_pp + 1 ); // string / concat inside the parens if ( 'str' === $gp_fcr[1] && false !== ( $gp_dc = strpos( $gp_fcr[0], '::' ) ) ) { $gp_fcv_global = $gp_fc_global_pair( substr( $gp_fcr[0], 0, $gp_dc ), substr( $gp_fcr[0], $gp_dc + 2 ) ); } if ( ! $gp_fcv_global ) { $gp_al = $gp_fc_global_arr( $gp_pp + 1 ); // inline ["Closure","fromCallable"] if ( $gp_al[0] ) { $gp_fcv_global = true; } } } } if ( $gp_fcv_global ) { // The '(...)' at $i is the FACTORY ARG (the wrapped callable). Scan it for a dangerous // global callable — a literal name, split literals fused, or a proven $danger_cb variable — // OR request data. An ARRAY/OBJECT callable is a bounded METHOD, never the global function // (the FG-guard reasoning), so it disqualifies. This mirrors (4c)'s own factory-arg scan. $gp_fk = $i + 1; $gp_fd = 1; $gp_fc_danger = false; $gp_fc_obj = false; $gp_fc_tnt = false; $gp_fc_concat = ''; $gp_fcs = 0; while ( $gp_fk < $n && $gp_fd > 0 && $gp_fcs++ < 5000 && self::scan_budget_ok() ) { $gp_fx = $tok[ $gp_fk ]; if ( $is_char( $gp_fx, '(' ) ) { $gp_fd++; } elseif ( $is_char( $gp_fx, ')' ) ) { $gp_fd--; if ( 0 === $gp_fd ) { break; } } else { if ( $is_char( $gp_fx, '[' ) || ( is_int( $gp_fx[0] ) && ( T_ARRAY === $gp_fx[0] || T_OBJECT_OPERATOR === $gp_fx[0] || T_DOUBLE_COLON === $gp_fx[0] ) ) ) { $gp_fc_obj = true; } elseif ( is_int( $gp_fx[0] ) && T_CONSTANT_ENCAPSED_STRING === $gp_fx[0] ) { $gp_fnm = strtolower( trim( $decode( $gp_fx[1] ) ) ); if ( $danger_name( $gp_fnm ) ) { $gp_fc_danger = true; } $gp_fc_concat .= $gp_fnm; } elseif ( is_int( $gp_fx[0] ) && T_VARIABLE === $gp_fx[0] && isset( $danger_cb[ $gp_fx[1] ] ) ) { $gp_fc_danger = true; } elseif ( ( $is_super( $gp_fx ) && ! $gp_srv_path( $gp_fk ) ) || $is_tainted( $gp_fx ) || $is_fn( $gp_fx, $req_read ) || $gp_remote_in( $gp_fk ) ) { $gp_fc_tnt = true; } } $gp_fk++; } if ( ! $gp_fc_danger && '' !== $gp_fc_concat && $danger_name( $gp_fc_concat ) ) { $gp_fc_danger = true; } if ( ( $gp_fc_danger || $gp_fc_tnt ) && ! $gp_fc_obj ) { // $gp_fk is the factory arg's matching ')'. The trailing '(...)' (or ->__invoke / // ->bindTo chain) is the INVOCATION; require request data in it, exactly like (4c). $gp_inv = $invocation_args( $gp_fk, 0 ); if ( $gp_inv ) { $gp_ia = $gp_inv; $gp_iad = 1; $gp_iareq = false; $gp_ias = 0; while ( $gp_ia < $n && $gp_iad > 0 && $gp_ias++ < 5000 && self::scan_budget_ok() ) { $gp_iax = $tok[ $gp_ia ]; if ( $is_char( $gp_iax, '(' ) ) { $gp_iad++; } elseif ( $is_char( $gp_iax, ')' ) ) { $gp_iad--; } elseif ( $is_super( $gp_iax ) || $is_fn( $gp_iax, $req_read ) || $is_tainted( $gp_iax ) ) { $gp_iareq = true; } $gp_ia++; } if ( $gp_iareq ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } } } } } // (4f) REFLECTION CALLABLE FACTORY — `(new ReflectionFunction('system'))->invoke($_POST['x'])` // (ACG-141-004). Another member of the same family: a literal dangerous name turned into an // invokable object. It reuses the SAME normalizer and the SAME invocation helper, which is the // point of centralising — a new factory costs one condition, not a new sub-model. // ACG-147-004: the class after `new` is an OPERAND. The arm previously required a NAME // token, so `new $rf(...)` (T_VARIABLE), `new ("ReflectionFunction")(...)` and // `new (RF::class)(...)` never entered it at all - a one-variable bypass of the whole arm. $gp_rf_ok = false; $gp_rf_arg = $i + 1; // ACG-149-011: on PHP 7.4 - a version this plugin's header declares support for - // `new \ReflectionFunction(...)` tokenises as T_NEW + T_NS_SEPARATOR + T_STRING, so the // predecessor of the NAME is the separator and this arm was never entered. On PHP 8 the // name is a single T_NAME_FULLY_QUALIFIED token and $i-1 is already T_NEW, so stepping // over an absent separator changes nothing there. $gp_nw = $i - 1; $gp_rf_abs = false; if ( $gp_nw >= 0 && is_int( $tok[ $gp_nw ][0] ) && T_NS_SEPARATOR === $tok[ $gp_nw ][0] ) { $gp_rf_abs = true; $gp_nw--; // an explicit leading '\' means the GLOBAL class } if ( $gp_nw >= 0 && is_int( $tok[ $gp_nw ][0] ) && T_NEW === $tok[ $gp_nw ][0] ) { if ( $is_char( $e, '(' ) ) { // `new ( ) ( args )` - resolve inside the group, then the ctor args // begin after its ')'. $gp_rf_ok = $class_operand_is_global( $i, 'reflectionfunction' ); $gp_rd = 1; $gp_rk = $i + 1; $gp_rs = 0; while ( $gp_rk < $n && $gp_rd > 0 && $gp_rs++ < 500 ) { if ( $is_char( $tok[ $gp_rk ], '(' ) ) { $gp_rd++; } elseif ( $is_char( $tok[ $gp_rk ], ')' ) ) { $gp_rd--; if ( 0 === $gp_rd ) { break; } } $gp_rk++; } $gp_rf_arg = $gp_rk + 1; } else { // Plain `new ReflectionFunction( args )`: the operand is the single name token at // $i, so the ctor's '(' is the very next token. // ACG-149-011: with an explicit leading '\' the reference is absolute, so it is the // global class no matter what namespace we are in. Needed on PHP 7.4, where the name // arrives as a BARE T_STRING and the resolver would otherwise qualify it into the // current namespace and answer "not the global class" - a false negative on exactly // the `namespace App; new \ReflectionFunction($_POST['fn'])` evasion ACG-148-006 closed. $gp_rf_ok = $gp_rf_abs ? ( 'reflectionfunction' === strtolower( (string) ( $tok[ $i ][1] ?? '' ) ) ) : $class_operand_is_global( $i, 'reflectionfunction' ); $gp_rf_arg = $i + 1; } } if ( $gp_rf_ok && $gp_rf_arg < $n && $is_char( $tok[ $gp_rf_arg ], '(' ) ) { $rk = $gp_rf_arg + 1; $rd = 1; $r_danger = false; $r_obj = false; $r_concat = ''; $rsteps = 0; while ( $rk < $n && $rd > 0 && $rsteps++ < 5000 && self::scan_budget_ok() ) { $rx = $tok[ $rk ]; if ( $is_char( $rx, '(' ) ) { $rd++; } elseif ( $is_char( $rx, ')' ) ) { $rd--; if ( 0 === $rd ) { break; } } else { // ACG-147-006 (the bracket bug): a '[' is an ARRAY-CALLABLE signal only when it // OPENS an operand. A SUBSCRIPT on a variable/`)`/`]` is just an index, and treating // it as an array callable silenced `new ReflectionFunction( $_POST['fn'] )` - the // most natural request-controlled webshell there is - by its own subscript. $gp_rprev = ( $rk > 0 ) ? $tok[ $rk - 1 ] : null; $gp_rsub = ( null !== $gp_rprev && ( ( is_int( $gp_rprev[0] ) && T_VARIABLE === $gp_rprev[0] ) || $is_char( $gp_rprev, ')' ) || $is_char( $gp_rprev, ']' ) ) ); if ( ( $is_char( $rx, '[' ) && ! $gp_rsub ) || ( is_int( $rx[0] ) && ( T_ARRAY === $rx[0] || T_OBJECT_OPERATOR === $rx[0] || T_DOUBLE_COLON === $rx[0] ) ) ) { $r_obj = true; } elseif ( is_int( $rx[0] ) && T_CONSTANT_ENCAPSED_STRING === $rx[0] ) { $rn = strtolower( trim( $decode( $rx[1] ) ) ); if ( $danger_name( $rn ) ) { $r_danger = true; } $r_concat .= $rn; } // ACG-145-002: this arm had NO variable branch at all, so both // `$f = "system"; new ReflectionFunction($f)` and the request-derived // `$f = $_POST['f']; new ReflectionFunction($f)` were missed entirely - the // second is a textbook webshell: the caller picks the function, then runs it // on request data. elseif ( is_int( $rx[0] ) && T_VARIABLE === $rx[0] && isset( $danger_cb[ $rx[1] ] ) ) { $r_danger = true; } elseif ( $is_super( $rx ) || $is_tainted( $rx ) || $is_fn( $rx, $req_read ) ) { $r_danger = true; } } $rk++; } if ( ! $r_danger && '' !== $r_concat && $danger_name( $r_concat ) ) { $r_danger = true; } // ACG-149-089 (external reviewer round 3, MS-003): resolve the constructor arg through P1 so a // transform (strrev/base64_decode/...), a concat or a const-var producing a dangerous global name is // caught, exactly like the Closure::fromCallable sibling. `new ReflectionFunction(strrev('metsys'))` // was invisible while the assigned form `$f=strrev('metsys'); new ReflectionFunction($f)` fired. // ACG-149-102 (round 11, R10-003): also run when $r_obj is set even if $r_danger already fired - an // INLINE array `(["system"])[0]` makes the walk set BOTH (the "system" literal AND the `[`), so the old // `! $r_danger` guard left the bounded-object flag on. Mirrors the Closure::fromCallable sibling. if ( ! $r_danger || $r_obj ) { // ACG-149-091 (round 4, MS-002): a class-constant ctor arg (`C::F`) sets $r_obj via its `::`, but a // WHOLE-arg resolution to a dangerous callable STRING is a hidden name, not a bounded method - // resolve regardless of $r_obj and clear it on a dangerous hit. A genuine Foo::method never resolves. $gp_rf_ares = $resolve_name( $gp_rf_arg + 1 ); if ( '' === $gp_rf_ares[0] ) { $gp_rf_ial = $gp_inline_arr_leaf( $gp_rf_arg + 1 ); if ( '' !== $gp_rf_ial ) { $gp_rf_ares = array( $gp_rf_ial, 'str' ); } } // ACG-149-102 (R10-003): inline `(["system"])[0]` arg if ( '' === $gp_rf_ares[0] || ! $danger_name( ltrim( strtolower( trim( (string) $gp_rf_ares[0] ) ), '\\' ) ) ) { $gp_rf_vr = $gp_arr_valret( $gp_rf_arg + 1 ); if ( '' !== $gp_rf_vr[0] ) { $gp_rf_ares = array( $gp_rf_vr[0], 'str' ); } } // ACG-149-123 (R22-001): `new ReflectionFunction(array_pop($cb))` if ( '' === $gp_rf_ares[0] ) { $gp_rf_ial = $gp_var_arr_leaf( $gp_rf_arg + 1 ); if ( '' !== $gp_rf_ial ) { $gp_rf_ares = array( $gp_rf_ial, 'str' ); } } // ACG-149-104 (R11-001): a `$cb[0]` arg from a literal/keyed/APPENDED danger slot if ( '' !== $gp_rf_ares[0] && $danger_name( ltrim( strtolower( trim( (string) $gp_rf_ares[0] ) ), '\\' ) ) ) { $r_danger = true; $r_obj = false; } } if ( $r_danger && ! $r_obj ) { // ACG-143-002: the ASSIGNED form was open while the identical assigned Closure form was // closed - the same axis, so it is recorded in the SAME $danger_cb set and reported by // the existing machinery when the variable is invoked. $gp_rt = $i - 1 - $wrap_before( $i - 1 ) - 1; if ( $gp_rt >= 1 && $is_char( $tok[ $gp_rt ], '=' ) && is_int( $tok[ $gp_rt - 1 ][0] ) && T_VARIABLE === $tok[ $gp_rt - 1 ][0] ) { $danger_cb[ $tok[ $gp_rt - 1 ][1] ] = 1; } $rinv = $invocation_args( $rk, $wrap_before( $i - 1 ) ); if ( $rinv ) { $ra = $rinv; $rad = 1; $rareq = false; $rasteps = 0; while ( $ra < $n && $rad > 0 && $rasteps++ < 5000 && self::scan_budget_ok() ) { $rax = $tok[ $ra ]; if ( $is_char( $rax, '(' ) ) { $rad++; } elseif ( $is_char( $rax, ')' ) ) { $rad--; } elseif ( $is_super( $rax ) || $is_fn( $rax, $req_read ) || $is_tainted( $rax ) ) { $rareq = true; } $ra++; } if ( $rareq ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } } } } // (4g) PARENTHESISED LITERAL CALLABLE — `("system")($_POST['a'])` (ACG-143-003). // No factory, no call_user_func: PHP invokes a string as a function directly. The fused literal // goes through the SAME $danger_name normalizer, so "sys"."tem" and "\\system" are covered too. // ACG-143-011 (adversarial review, 2026-07-19): this exclusion list predated PHP 8's name // tokens, so a NAMESPACED call's argument list was mistaken for a grouping paren: // \App\Logging\channel( 'system' )( $_POST['msg'] ) // is a developer-defined channel() receiving a log-channel NAME and returning a writer -- the // string is an ARGUMENT, never the callee. The comment on this arm asserted the case was // impossible; it was simply untested. A false claim in a comment is a defect of its own. if ( $is_char( $e, '(' ) && ! ( $i > 0 && ( ( is_int( $tok[ $i - 1 ][0] ) && ( T_STRING === $tok[ $i - 1 ][0] || T_VARIABLE === $tok[ $i - 1 ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $i - 1 ][0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $i - 1 ][0] ) || ( defined( 'T_NAME_RELATIVE' ) && T_NAME_RELATIVE === $tok[ $i - 1 ][0] ) ) ) || $is_char( $tok[ $i - 1 ], ')' ) || $is_char( $tok[ $i - 1 ], ']' ) ) ) ) { $gp_ln = $literal_name_at( $i + 1 ); if ( '' !== $gp_ln && $danger_name( $gp_ln ) ) { $gp_ge = $i + 1; $gp_gd = 1; $gp_gs = 0; while ( $gp_ge < $n && $gp_gd > 0 && $gp_gs++ < 500 ) { if ( $is_char( $tok[ $gp_ge ], '(' ) ) { $gp_gd++; } elseif ( $is_char( $tok[ $gp_ge ], ')' ) ) { $gp_gd--; if ( 0 === $gp_gd ) { break; } } $gp_ge++; } $gp_gi = $invocation_args( $gp_ge, 0 ); if ( $gp_gi ) { $ga = $gp_gi; $gad = 1; $gareq = false; $gas = 0; while ( $ga < $n && $gad > 0 && self::scan_budget_ok() ) { $gax = $tok[ $ga ]; if ( $is_char( $gax, '(' ) ) { $gad++; } elseif ( $is_char( $gax, ')' ) ) { $gad--; } elseif ( $is_super( $gax ) || $is_fn( $gax, $req_read ) || $is_tainted( $gax ) ) { $gareq = true; } $ga++; } if ( $gareq ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } } } } // (4d) PHP 8.1 FIRST-CLASS CALLABLE — `$f = system(...);` (ACG-141-003, reviewer 2, 2026-07-17). // // `system(...)` is not a call: it is a Closure that runs system. It belongs to the SAME family as // Closure::fromCallable, so leaving it as a mere review item while the factory form is malware was // the inconsistency the reviewer flagged. Recorded in the SAME $danger_cb set, so the existing // machinery reports `$f($_POST['a'])` and `$f->__invoke($_POST['a'])` without new emit paths. // // FP GUARD, and it is the whole reason this is narrow: a first-class callable of a METHOD // (`$this->exec(...)`, `Foo::exec(...)`) can only reach a method on that class — a bounded, // developer-defined set — so a `->`/`::` before the name disqualifies it, exactly as elsewhere. // The name is normalised through $danger_name, so `\system(...)` is covered too. if ( defined( 'T_ELLIPSIS' ) && is_int( $e[0] ) && ( T_STRING === $e[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $e[0] ) ) && $danger_name( $e[1] ) && $i + 3 < $n && $is_char( $tok[ $i + 1 ], '(' ) && is_int( $tok[ $i + 2 ][0] ) && T_ELLIPSIS === $tok[ $i + 2 ][0] && $is_char( $tok[ $i + 3 ], ')' ) && ! ( $i > 0 && is_int( $tok[ $i - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $i - 1 ][0] || T_DOUBLE_COLON === $tok[ $i - 1 ][0] ) ) ) { // ACG-141-004: skip grouping parens before the '=' so `$f = (system(...));` still binds. $gp_ft = $i - $wrap_before( $i ) - 1; if ( $gp_ft >= 1 && $is_char( $tok[ $gp_ft ], '=' ) && is_int( $tok[ $gp_ft - 1 ][0] ) && T_VARIABLE === $tok[ $gp_ft - 1 ][0] ) { $danger_cb[ $tok[ $gp_ft - 1 ][1] ] = 1; } } // (4e) CLOSURE OBJECT INVOCATION on a variable — `$f->__invoke($_POST['a'])` / `$f->call($o, …)` // (ACG-141-002). The callee walk only models `$f(...)`, so an assigned dangerous/request callable // invoked through the Closure object escaped it entirely. if ( is_int( $e[0] ) && T_VARIABLE === $e[0] && $i + 3 < $n && is_int( $tok[ $i + 1 ][0] ) && T_OBJECT_OPERATOR === $tok[ $i + 1 ][0] && is_int( $tok[ $i + 2 ][0] ) && T_STRING === $tok[ $i + 2 ][0] && in_array( strtolower( $tok[ $i + 2 ][1] ), array( '__invoke', 'call', 'invoke', 'invokeargs' ), true ) && $is_char( $tok[ $i + 3 ], '(' ) // ACG-141-002b (clean corpus, NOT the harness): key ONLY on a variable that PROVABLY holds a // Closure from a dangerous factory. My first cut also fired when the variable was merely // TAINTED, and `__invoke` / `call` are ordinary PHP method names — WordPress core's own // wp-includes/IXR/class-IXR-server.php does `$this->call( $method, $params )`, which became a // new finding on stock core. PSR-15 middleware, DI containers and RPC clients all use the same // names. A tainted STRING cannot be ->__invoke()'d anyway (that is a fatal, not an exploit), // so requiring $danger_cb loses no real detection: the request-derived callable reaches this // through the fromCallable arm's own $cb_tainted branch instead. && isset( $danger_cb[ $e[1] ] ) ) { $gp_indirect_cb = false; $a = $i + 4; $ad = 1; $areq = false; $asteps = 0; while ( $a < $n && $ad > 0 && $asteps < 5000 && self::scan_budget_ok() ) { $asteps++; $ax = $tok[ $a ]; if ( $is_char( $ax, '(' ) ) { $ad++; } elseif ( $is_char( $ax, ')' ) ) { $ad--; } elseif ( $is_super( $ax ) || $is_fn( $ax, $req_read ) || $is_tainted( $ax ) ) { $areq = true; } $a++; } // Same directness rule as the callee walk (ACG-138-R2-02b): a container-laundered callable // stays a review item rather than confirmed malware. if ( $areq && ! $gp_indirect_cb ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee_var', 'name' => 'Request-Controlled Dynamic Call (via variable)', 'severity' => 'critical' ); } elseif ( $areq ) { $found['dyn'] = array( 'id' => 'tk_dyn_superglobal_call', 'name' => 'Dynamic Call From Request', 'severity' => 'critical' ); } } // (5) CALLBACK APIs (call_user_func / array_map / usort / register_shutdown_function / ...): the // CALLABLE argument is request data, OR a literal dangerous-callable name with a request argument. // (4h) ACG-146-002 — the callable FACTORY invoked THROUGH a callback API. // v1.0.145 caught `Closure::fromCallable('system')( $_POST['a'] )` but not the identical act // written as `call_user_func( ['Closure','fromCallable'], 'system' )( $_POST['a'] )`. Same // result: a Closure over system(), then invoked on request data. An attacker probing the // fromCallable rule would try this first, so it belongs on the same axis, not in a later round. // Covered: ['Closure','fromCallable'] · ['\Closure',..] · [Closure::class,..] · // 'Closure::fromCallable' · and the assigned form. The class must still RESOLVE to PHP's own // \Closure, so a vendor's own namespaced Closure is not reported. // ACG-149-112 (round 14, R13-004): `$cb += ["system"]` / `$cb = $cb + [...]`, restricted to a left side that is // PROVABLY EMPTY. Under `+` the LEFT key wins, so a general model needs the left array's full key set - and // guessing there would put a fact on a slot whose real value is the safe one (a false positive, the worse // failure). But when the left side is a `[]` literal with no appends, no element writes and no removals since, // there is no ambiguity at all: every right-hand key is new, exactly like an append. That narrow, provable case // is now covered; anything else stays a documented residual. if ( is_int( $e[0] ) && T_VARIABLE === $e[0] && $i + 2 < $n && $bd <= end( $base ) && is_int( $tok[ $i + 1 ][0] ) && defined( 'T_PLUS_EQUAL' ) && T_PLUS_EQUAL === $tok[ $i + 1 ][0] && ( $is_char( $tok[ $i + 2 ], '[' ) || ( is_int( $tok[ $i + 2 ][0] ) && T_ARRAY === $tok[ $i + 2 ][0] ) ) && isset( $gp_arr_whole[ $e[1] ] ) && ! isset( $gp_arr_danger[ $e[1] ] ) && $i - (int) $gp_arr_whole[ $e[1] ] < 2000 ) { $gp_ulit = (int) $gp_arr_whole[ $e[1] ] + 2; if ( 0 === $gp_arr_auto_next( $gp_ulit ) && 0 === $gp_append_count( $e[1], $gp_ulit, $i ) && ! $gp_arr_removed( $e[1], $gp_ulit, $i ) ) { $gp_uwrite = false; // any element WRITE would occupy a key the union must not override for ( $gp_uw = $gp_ulit; $gp_uw < $i && $gp_uw < $gp_ulit + 20000; $gp_uw++ ) { if ( is_int( $tok[ $gp_uw ][0] ) && T_VARIABLE === $tok[ $gp_uw ][0] && (string) $tok[ $gp_uw ][1] === (string) $e[1] && $gp_uw + 1 < $n && $is_char( $tok[ $gp_uw + 1 ], '[' ) ) { $gp_uwrite = true; break; } } if ( ! $gp_uwrite ) { $gp_umap = $gp_scan_arr_danger( $i + 2 ); if ( ! empty( $gp_umap ) ) { $gp_arr_danger[ $e[1] ] = $gp_umap; } } } } // ACG-149-110 (round 14, R13-002 - a CRITICAL FALSE POSITIVE): `unset($cb[0])` removes exactly that key, but // the per-slot fact survived it, so `$cb=["system","strlen"]; unset($cb[0]); $cb[0](…)` was reported CRITICAL // although $cb[0] no longer exists (calling it is a PHP error, not a command execution). Delete just that slot - // never the whole map (that would lose the still-valid siblings, cf. `unset($cb[1])` which must keep 0). // unset() takes a LIST, so every `$var[]` argument is handled. if ( is_int( $e[0] ) && defined( 'T_UNSET' ) && T_UNSET === $e[0] && $i + 2 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $gp_ud = 1; for ( $gp_uq = $i + 2; $gp_uq < $n && $gp_uq < $i + 400; $gp_uq++ ) { if ( $is_char( $tok[ $gp_uq ], '(' ) ) { $gp_ud++; continue; } if ( $is_char( $tok[ $gp_uq ], ')' ) ) { $gp_ud--; if ( 0 === $gp_ud ) { break; } continue; } if ( 1 === $gp_ud && is_int( $tok[ $gp_uq ][0] ) && T_VARIABLE === $tok[ $gp_uq ][0] && isset( $gp_arr_danger[ $tok[ $gp_uq ][1] ] ) && $gp_uq + 1 < $n && $is_char( $tok[ $gp_uq + 1 ], '[' ) ) { list( $gp_uk, $gp_ukp ) = $gp_key_at( $gp_uq + 2 ); if ( null !== $gp_uk && $gp_ukp < $n && $is_char( $tok[ $gp_ukp ], ']' ) ) { unset( $gp_arr_danger[ $tok[ $gp_uq ][1] ][ $gp_uk ] ); if ( empty( $gp_arr_danger[ $tok[ $gp_uq ][1] ] ) ) { unset( $gp_arr_danger[ $tok[ $gp_uq ][1] ] ); } } else { unset( $gp_arr_danger[ $tok[ $gp_uq ][1] ] ); // a key we cannot resolve -> fail toward clean } } } } $gp_fapi = $called_fn( $i ); // ACG-149-108 (round 13, R12-004 + self-found): ARRAY MUTATORS applied to a tracked/known literal array. // `array_push($cb,"system")` is semantically identical to `$cb[]="system"` and was a 1-call bypass; it now // shares the SAME index model (base literal's next auto index + the shared append count). `array_unshift` // is NOT an append: it inserts at 0 and RENUMBERS the integer keys, so every existing int-keyed fact is // shifted by the number of inserted values - done for SAFE values too, because leaving a fact on a slot // whose value moved is a FALSE POSITIVE. Every OTHER mutator that can reorder/remove elements // (shift/pop/splice/sort/reverse/...) RETIRES the fact: we can no longer say which slot holds what, and a // stale fact there would brand a safe callable (verified: `["system","aaa"]` + sort() + `$cb[0](…)` was an FP). // Reuses the $gp_fapi name already resolved for the callback-API arm, so this costs no extra work. // ACG-149-120 (round 20, self-found FP): decide FIRST whether the target is the WHOLE variable. If a // subscript / property / static access follows, the mutation acts on something else, so the arm must not // model it - and any nested fact we hold for this variable is now unreliable, so it is retired. // ACG-149-121 (round 21, R20-003): the same mutation written INDIRECTLY is MODELLED, not just retired. // $gp_mfn is the effective callee name and $gp_mcp the position whose next token opens the argument list; // for a direct call they are the resolved builtin and $i, so every arm below is unchanged. $gp_mfn = $gp_fapi; $gp_mcp = $i; if ( is_int( $e[0] ) && T_VARIABLE === $e[0] && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) && isset( $const_str[ $e[1] ] ) ) { // `$f = "array_splice"; $f($cb, …)` - the argument list opens at $i + 1 exactly as for a direct call. // The name must be UNAMBIGUOUS at this point: $const_str keeps only the last unconditional write, so a // write inside an `if` would otherwise apply the wrong mutator kind (self-found FP). // ACG-149-121 (round 21, self-found PERF): the cheap test first. Only a name that is ALREADY a known // mutator is worth the backward scan that confirms it is unambiguous; every other dynamic call pays // nothing. (Measured: ~8-10x on a file of ordinary `$f = "strtolower"; $f(...)` dispatch.) $gp_c0 = ltrim( strtolower( trim( (string) $const_str[ $e[1] ][0] ) ), chr( 92 ) ); // ACG-149-122 (round 22, R21-002): $const_str may hold only the FIRST literal of a concatenation, so the // cheap pre-test has to accept "looks like it could become a mutator name" too, or `"array_" . "splice"` // is rejected before the resolver is ever asked. Still cheap: one prefix test. $gp_cmay = isset( $gp_mutators[ $gp_c0 ] ) || 0 === strpos( $gp_c0, 'array_' ) || in_array( $gp_c0, array( 'sort', 'rsort', 'usort', 'uasort', 'uksort', 'asort', 'arsort', 'ksort', 'krsort', 'shuffle', 'natsort', 'natcasesort' ), true ); $gp_cand = $gp_cmay ? $gp_var_names( $e[1], $i ) : $gp_c0; if ( isset( $gp_mutators[ $gp_cand ] ) ) { $gp_mfn = $gp_cand; $gp_mcp = $i; } elseif ( '' === $gp_cand ) { // the callee might be a mutator and we cannot tell which - retire what this call could touch $gp_amb = $gp_c0; if ( isset( $gp_mutators[ $gp_amb ] ) ) { for ( $gp_iq = $i + 1, $gp_id = 0; $gp_iq < $n && $gp_iq < $i + 400; $gp_iq++ ) { if ( $is_char( $tok[ $gp_iq ], '(' ) || $is_char( $tok[ $gp_iq ], '[' ) ) { $gp_id++; continue; } if ( $is_char( $tok[ $gp_iq ], ')' ) || $is_char( $tok[ $gp_iq ], ']' ) ) { $gp_id--; if ( $gp_id <= 0 ) { break; } continue; } if ( is_int( $tok[ $gp_iq ][0] ) && T_VARIABLE === $tok[ $gp_iq ][0] ) { unset( $gp_arr_danger[ (string) $tok[ $gp_iq ][1] ] ); } } } } } elseif ( 'call_user_func_array' === $gp_fapi && $i + 2 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { // `call_user_func_array("array_splice", [&$cb, 0, 1, []])` - the real arguments live in the ARRAY literal, // so point $gp_mcp at the token before its `[` and let the shared walker read it like an argument list. $gp_cua = $gp_mut_args( $i, array( 'callback', 'args' ) ); if ( null !== $gp_cua && isset( $gp_cua[0][0] ) && isset( $gp_cua[0][1] ) ) { $gp_ir = $resolve_name( $gp_cua[0][0] ); $gp_cand = ( '' !== $gp_ir[0] ) ? ltrim( strtolower( trim( (string) $gp_ir[0] ) ), chr( 92 ) ) : ''; $gp_ab = $gp_cua[0][1]; while ( $gp_ab < $n && is_int( $tok[ $gp_ab ][0] ) && in_array( $tok[ $gp_ab ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_ab++; } if ( isset( $gp_mutators[ $gp_cand ] ) ) { if ( $gp_ab < $n && $is_char( $tok[ $gp_ab ], '[' ) ) { $gp_mfn = $gp_cand; $gp_mcp = $gp_ab - 1; } else { // ACG-149-121 (round 21, self-found FP): the callee IS a mutator but its argument array is not // an inline literal - `$a = [&$cb, 0, 1]; call_user_func_array("array_splice", $a);`. The // mutation certainly happens and the target is reachable only through a REFERENCE inside $a, // so retiring the variables named in the call clears the wrong one. Wiping the whole map // (my first attempt) fixed that but silenced every array fact in the file - a one-line // evasion. Precise answer: follow the args variable to its assignment and retire the // variables it takes BY REFERENCE, plus the args variable itself. for ( $gp_iq = $i + 1, $gp_id = 0; $gp_iq < $n && $gp_iq < $i + 400; $gp_iq++ ) { if ( $is_char( $tok[ $gp_iq ], '(' ) || $is_char( $tok[ $gp_iq ], '[' ) ) { $gp_id++; continue; } if ( $is_char( $tok[ $gp_iq ], ')' ) || $is_char( $tok[ $gp_iq ], ']' ) ) { $gp_id--; if ( $gp_id <= 0 ) { break; } continue; } if ( ! is_int( $tok[ $gp_iq ][0] ) || T_VARIABLE !== $tok[ $gp_iq ][0] ) { continue; } $gp_av = (string) $tok[ $gp_iq ][1]; unset( $gp_arr_danger[ $gp_av ] ); // …and whatever that variable was built from, if it was built from an array literal. if ( isset( $gp_arr_whole[ $gp_av ] ) ) { $gp_aw = (int) $gp_arr_whole[ $gp_av ] + 2; for ( $gp_ax = $gp_aw, $gp_ad = 0; $gp_ax < $n && $gp_ax < $gp_aw + 400; $gp_ax++ ) { if ( $is_char( $tok[ $gp_ax ], '[' ) || $is_char( $tok[ $gp_ax ], '(' ) ) { $gp_ad++; continue; } if ( $is_char( $tok[ $gp_ax ], ']' ) || $is_char( $tok[ $gp_ax ], ')' ) ) { $gp_ad--; if ( $gp_ad <= 0 ) { break; } continue; } if ( is_int( $tok[ $gp_ax ][0] ) && T_VARIABLE === $tok[ $gp_ax ][0] ) { unset( $gp_arr_danger[ (string) $tok[ $gp_ax ][1] ] ); } } } } } } } } $gp_mtgt = false; $gp_mtp = -1; if ( '' !== $gp_mfn && isset( $gp_mutators[ $gp_mfn ] ) && $gp_mcp + 2 < $n && ( $is_char( $tok[ $gp_mcp + 1 ], '(' ) || $is_char( $tok[ $gp_mcp + 1 ], '[' ) ) ) { // ACG-149-121 (round 21, R20-002): the TARGET is argument 0 in POSITIONAL order, which the shared walker // reports whatever order the call was written in. push/unshift keep the positional path below (a variadic // parameter cannot be named in PHP), so a named form there still retires. $gp_ma = isset( $gp_mut_pnames[ $gp_mfn ] ) ? $gp_mut_args( $gp_mcp, $gp_mut_pnames[ $gp_mfn ] ) : null; $gp_mk0 = (int) $gp_mutators[ $gp_mfn ]; $gp_mt0 = ( null !== $gp_ma && isset( $gp_ma[0][0] ) ) ? $gp_ma[0][0] : -1; // Skip whitespace and a leading `&` (call_user_func_array passes the array BY REFERENCE). In PHP 8 that // `&` is NOT the character '&' - it is T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, which is exactly why the // first cut of this skip did nothing. (Same trap as `array:` arriving as T_ARRAY, two fixes ago.) $gp_amp = array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ); foreach ( array( 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG' ) as $gp_ampn ) { if ( defined( $gp_ampn ) ) { $gp_amp[] = constant( $gp_ampn ); } } while ( $gp_mt0 >= 0 && $gp_mt0 < $n && ( $is_char( $tok[ $gp_mt0 ], '&' ) || ( is_int( $tok[ $gp_mt0 ][0] ) && in_array( $tok[ $gp_mt0 ][0], $gp_amp, true ) ) ) ) { $gp_mt0++; } if ( $gp_mt0 >= 0 && $gp_mt0 < $n && ! ( $gp_ma[2] && ( 1 === $gp_mk0 || 2 === $gp_mk0 ) ) && is_int( $tok[ $gp_mt0 ][0] ) && T_VARIABLE === $tok[ $gp_mt0 ][0] ) { $gp_mtp = $gp_mt0; $gp_mtn = $gp_mtp + 1; while ( $gp_mtn < $n && is_int( $tok[ $gp_mtn ][0] ) && in_array( $tok[ $gp_mtn ][0], array( T_WHITESPACE, T_COMMENT, T_DOC_COMMENT ), true ) ) { $gp_mtn++; } // `]` closes the list too, because call_user_func_array's arguments arrive inside an ARRAY LITERAL. $gp_mtgt = ( $gp_mtn < $n && ( $is_char( $tok[ $gp_mtn ], ',' ) || $is_char( $tok[ $gp_mtn ], ')' ) || $is_char( $tok[ $gp_mtn ], ']' ) ) ); if ( ! $gp_mtgt ) { unset( $gp_arr_danger[ (string) $tok[ $gp_mtp ][1] ] ); } } else { // ACG-149-120 (round 20, self-found FP): the target is not a plain variable at all - NAMED arguments // (`array_splice(array: $cb, offset: 0)`), `$GLOBALS[…]`, a chained expression. The call still mutates // whatever it names, and the positional walk below cannot read it, so saying nothing would leave a // STALE fact behind on a call that really emptied the array. Retire every array variable it mentions. $gp_mseen = 0; for ( $gp_mnq = $gp_mcp + 2, $gp_mnd = 1; $gp_mnq < $n && $gp_mnq < $gp_mcp + 400; $gp_mnq++ ) { if ( $is_char( $tok[ $gp_mnq ], '(' ) || $is_char( $tok[ $gp_mnq ], '[' ) ) { $gp_mnd++; continue; } if ( $is_char( $tok[ $gp_mnq ], ')' ) || $is_char( $tok[ $gp_mnq ], ']' ) ) { $gp_mnd--; if ( 0 === $gp_mnd ) { break; } continue; } if ( is_int( $tok[ $gp_mnq ][0] ) && T_VARIABLE === $tok[ $gp_mnq ][0] ) { $gp_mseen++; unset( $gp_arr_danger[ (string) $tok[ $gp_mnq ][1] ] ); } } // ACG-149-121 (round 21): a mutator "call" that names NO variable mutates nothing we can attribute - // `array_splice(...)` is a first-class callable, `sort()` and `call_user_func_array("array_shift", [])` // are calls PHP itself rejects. My first cut wiped the whole map here, which turned one innocent // `array_reverse([3,1,2])` into a file-wide silencer. Nothing was mutated, so nothing is retired. } } if ( $gp_mtgt ) { $gp_mv = (string) $tok[ $gp_mtp ][1]; // ACG-149-123 (round 23, R22-001): snapshot the target's danger map BEFORE this call's own transform. // `array_pop($cb)($_POST[..])` invokes the RETURN, and the `(` that invokes it is reached LATER in this // same token loop - by then the popped slot has already been removed from the live map, so the callee // walk would find nothing. Keyed by the callee token, which is what $gp_arr_valret is asked about. // Keyed by BOTH the effective argument position and the token the arm was REACHED at. For a direct // call these are the same, but `call_user_func_array("array_pop", [&$cb])` has its effective position // inside the args array while $gp_arr_valret is asked about the OUTER call token - and with only the // effective key stored, the lookup missed and the mutated (empty) live map was used instead. if ( isset( $gp_arr_danger[ $gp_mv ] ) ) { $gp_valret_pre[ $gp_mcp ] = $gp_arr_danger[ $gp_mv ]; $gp_valret_pre[ $i ] = $gp_arr_danger[ $gp_mv ]; } // ACG-149-121 (round 21, self-found FP): where the VALUE list really begins - after argument 0 ends, not // at a fixed offset from the call. `$gp_ma[1][0]` is the token that CLOSED the target argument: a comma // when values follow, or the closing paren/bracket when the target was the only argument. Stepping past // a closing paren would walk the value scan into the code AFTER the call (that mistake made a zero-value // `array_unshift($cb)` stop renumbering), so only a comma is stepped over. $gp_mv1 = $gp_mcp + 3; if ( isset( $gp_ma[1][0] ) && $gp_ma[1][0] > $gp_mtp ) { $gp_mv1 = $is_char( $tok[ $gp_ma[1][0] ], ',' ) ? ( $gp_ma[1][0] + 1 ) : $gp_ma[1][0]; } if ( 1 === $gp_mutators[ $gp_mfn ] ) { // array_push - append semantics if ( isset( $gp_arr_whole[ $gp_mv ] ) && $bd <= end( $base ) && $i - (int) $gp_arr_whole[ $gp_mv ] < 2000 ) { $gp_mbase = $gp_arr_removed( $gp_mv, (int) $gp_arr_whole[ $gp_mv ] + 2, $i ) ? null : $gp_arr_auto_next( (int) $gp_arr_whole[ $gp_mv ] + 2 ); // ACG-149-120: see above // ACG-149-118 (R17-004): with a SPLAT argument the comma count is not the value count, so resolve // the whole argument list through $gp_repl_spec (which reports count + which positions are // dangerous) instead of walking commas. $gp_msplat = false; for ( $gp_mz2 = $gp_mv1, $gp_md2 = 1; $gp_mz2 < $n && $gp_mz2 < $gp_mcp + 400; $gp_mz2++ ) { if ( $is_char( $tok[ $gp_mz2 ], '(' ) || $is_char( $tok[ $gp_mz2 ], '[' ) ) { $gp_md2++; continue; } if ( $is_char( $tok[ $gp_mz2 ], ')' ) || $is_char( $tok[ $gp_mz2 ], ']' ) ) { $gp_md2--; if ( 0 === $gp_md2 ) { break; } continue; } if ( 1 === $gp_md2 && is_int( $tok[ $gp_mz2 ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $gp_mz2 ][0] ) { $gp_msplat = true; break; } } if ( $gp_msplat && null !== $gp_mbase ) { $gp_mbase2 = $gp_arr_removed( $gp_mv, (int) $gp_arr_whole[ $gp_mv ] + 2, $i ) ? null : $gp_arr_auto_next( (int) $gp_arr_whole[ $gp_mv ] + 2 ); // ACG-149-120: see above $gp_mslot2 = 0; $gp_md3 = 1; $gp_mvs3 = $gp_mv1; $gp_mok = true; $gp_mplan = array(); for ( $gp_mq3 = $gp_mv1; $gp_mq3 < $n && $gp_mq3 < $gp_mcp + 400; $gp_mq3++ ) { $gp_mend3 = false; if ( $is_char( $tok[ $gp_mq3 ], '(' ) || $is_char( $tok[ $gp_mq3 ], '[' ) ) { $gp_md3++; continue; } if ( $is_char( $tok[ $gp_mq3 ], ')' ) || $is_char( $tok[ $gp_mq3 ], ']' ) ) { $gp_md3--; if ( 0 === $gp_md3 ) { $gp_mend3 = true; } else { continue; } } if ( $gp_mend3 || ( 1 === $gp_md3 && $is_char( $tok[ $gp_mq3 ], ',' ) ) ) { if ( $gp_mvs3 < $gp_mq3 && $gp_mvs3 >= $gp_mv1 ) { if ( is_int( $tok[ $gp_mvs3 ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $gp_mvs3 ][0] ) { $gp_msp3 = $gp_repl_spec( $gp_mvs3 + 1 ); if ( null === $gp_msp3 ) { $gp_mok = false; break; } foreach ( $gp_msp3[1] as $gp_mpp => $gp_mvv ) { $gp_mplan[ $gp_mslot2 + $gp_mpp ] = $gp_mvv; } $gp_mslot2 += (int) $gp_msp3[0]; } else { $gp_mr3 = $resolve_name( $gp_mvs3 ); if ( '' !== $gp_mr3[0] && 'str' === $gp_mr3[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_mr3[0] ) ), chr( 92 ) ) ) ) { $gp_mplan[ $gp_mslot2 ] = ltrim( strtolower( trim( (string) $gp_mr3[0] ) ), chr( 92 ) ); } $gp_mslot2++; } } $gp_mvs3 = $gp_mq3 + 1; if ( $gp_mend3 ) { break; } } } if ( $gp_mok && null !== $gp_mbase2 ) { foreach ( $gp_mplan as $gp_mpk => $gp_mpv ) { $gp_arr_danger[ $gp_mv ][ $gp_mbase2 + $gp_mpk ] = $gp_mpv; } } $gp_mbase = null; // handled here; skip the comma-walking path below } if ( null !== $gp_mbase ) { $gp_mac = $gp_append_count( $gp_mv, (int) $gp_arr_whole[ $gp_mv ] + 2, $i ); $gp_mbase = ( $gp_mac < 0 ) ? null : ( $gp_mbase + $gp_mac ); } // ACG-149-121 (round 21, self-found CRITICAL FP): RE-GATE. Setting $gp_mbase to null above and // carrying on placed every value at `null + $slot`, which PHP evaluates as `$slot` - so an // unknowable append index became "index 0" and the verdict inverted (innocent slot critical, real // slot clean). An unknowable base must place NO fact at all. if ( null !== $gp_mbase ) { $gp_md = 1; $gp_mslot = 0; $gp_mvs = $gp_mv1; // first value starts after argument 0 for ( $gp_mq = $gp_mv1; $gp_mq < $n && $gp_mq < $gp_mcp + 400; $gp_mq++ ) { if ( $is_char( $tok[ $gp_mq ], '(' ) || $is_char( $tok[ $gp_mq ], '[' ) ) { $gp_md++; continue; } if ( $is_char( $tok[ $gp_mq ], ')' ) || $is_char( $tok[ $gp_mq ], ']' ) ) { $gp_md--; if ( 0 === $gp_md ) { if ( $gp_mvs < $gp_mq ) { $gp_mr = $resolve_name( $gp_mvs ); if ( '' !== $gp_mr[0] && 'str' === $gp_mr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_mr[0] ) ), '\\' ) ) ) { $gp_arr_danger[ $gp_mv ][ $gp_mbase + $gp_mslot ] = ltrim( strtolower( trim( (string) $gp_mr[0] ) ), '\\' ); } } break; } continue; } if ( 1 === $gp_md && $is_char( $tok[ $gp_mq ], ',' ) ) { if ( $gp_mvs < $gp_mq && $gp_mvs >= $gp_mv1 ) { $gp_mr = $resolve_name( $gp_mvs ); if ( '' !== $gp_mr[0] && 'str' === $gp_mr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_mr[0] ) ), '\\' ) ) ) { $gp_arr_danger[ $gp_mv ][ $gp_mbase + $gp_mslot ] = ltrim( strtolower( trim( (string) $gp_mr[0] ) ), '\\' ); } $gp_mslot++; } $gp_mvs = $gp_mq + 1; } } } } } elseif ( 2 === $gp_mutators[ $gp_mfn ] ) { // array_unshift - insert at the FRONT, then PHP renumbers // ACG-149-119 (round 18, R18-001): expand `...$spread` here TOO. Round 18 taught the push arm to do this // but not this one, and the STATUS then claimed both were modelled - the claim was wrong, and this is // the fix. $gp_mvals maps a resulting POSITION to either a token offset (a plain argument) or a // pre-resolved dangerous name (a value that came out of a spread source). $gp_mcnt = 0; $gp_md = 1; $gp_mvs = $gp_mv1; $gp_mvals = array(); $gp_muvals = array(); $gp_muok = true; $gp_mdone = false; for ( $gp_mq = $gp_mv1; $gp_mq < $n && $gp_mq < $gp_mcp + 400; $gp_mq++ ) { $gp_mlast = false; if ( $is_char( $tok[ $gp_mq ], '(' ) || $is_char( $tok[ $gp_mq ], '[' ) ) { $gp_md++; continue; } if ( $is_char( $tok[ $gp_mq ], ')' ) || $is_char( $tok[ $gp_mq ], ']' ) ) { $gp_md--; if ( 0 === $gp_md ) { $gp_mlast = true; } else { continue; } } if ( $gp_mlast || ( 1 === $gp_md && $is_char( $tok[ $gp_mq ], ',' ) ) ) { if ( $gp_mvs < $gp_mq && $gp_mvs >= $gp_mv1 ) { if ( is_int( $tok[ $gp_mvs ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $gp_mvs ][0] ) { $gp_musp = $gp_repl_spec( $gp_mvs + 1 ); if ( null === $gp_musp ) { $gp_muok = false; break; } foreach ( $gp_musp[1] as $gp_mupp => $gp_muvv ) { $gp_muvals[ $gp_mcnt + $gp_mupp ] = $gp_muvv; } $gp_mcnt += (int) $gp_musp[0]; } else { $gp_mvals[ $gp_mcnt ] = $gp_mvs; $gp_mcnt++; } } $gp_mvs = $gp_mq + 1; if ( $gp_mlast ) { $gp_mdone = true; break; } } } // A resolvable but EMPTY value list (`array_unshift($cb)`, `array_unshift($cb, ...[])`) is legal PHP, and // it is NOT a no-op: array_unshift RENUMBERS the integer keys even when it inserts nothing (verified // against the interpreter - `[2=>"system",0=>"strlen"]` becomes `["system","strlen"]`). So it takes the // ordinary layout path with ZERO placeholders. It is still a different answer from "unresolvable", // which is the only case that retires the map. (My first cut called this a no-op and the operand // matrix immediately produced 8 false positives from it.) // ACG-149-119 (round 19, self-found FP): the argument scan is bounded at 400 tokens. When it runs OUT // before the closing paren, nothing was counted - but that is "I could not read the arguments", NOT // "there were no arguments". Treating the two alike renumbered with zero placeholders while PHP had // really inserted a value, and one big associative array as the single argument (ordinary plugin // code) was then reported as malware. A bound that runs out is never an answer. $gp_mzero = ( $gp_muok && $gp_mdone && 0 === $gp_mcnt ); // ACG-149-113 (round 15, R14-003): the old code moved every int key up by N. That is NOT what PHP does - // it RENUMBERS the integer keys sequentially from 0 in ORDER, so `[2=>"system"]` + unshift puts "system" // at 1, not at 3. Derive the real layout and remap through it. $gp_mlay = ( isset( $gp_arr_whole[ $gp_mv ] ) && $i - (int) $gp_arr_whole[ $gp_mv ] < 2000 ) ? $gp_arr_replay( $gp_mv, (int) $gp_arr_whole[ $gp_mv ] + 2, $i ) : null; // …and the same applies to a PARTIAL count: an unfinished scan makes $gp_mcnt a lower bound, not a // count, so it may not drive the transform either (this half was already true before round 19). if ( ! $gp_muok || ! $gp_mdone ) { $gp_mlay = null; } // unresolvable/unfinished -> take the retire arm if ( ( $gp_mzero || $gp_mcnt > 0 ) && $gp_mcnt < 64 && null !== $gp_mlay ) { $gp_mpre = array(); for ( $gp_mz = 0; $gp_mz < $gp_mcnt; $gp_mz++ ) { $gp_mpre[] = 0; } list( , $gp_mmap, ) = $gp_arr_reindex( array_merge( $gp_mpre, $gp_mlay[0] ) ); if ( isset( $gp_arr_danger[ $gp_mv ] ) ) { $gp_mnew = array(); foreach ( $gp_arr_danger[ $gp_mv ] as $gp_mk => $gp_mval ) { // the prepended placeholders consumed the first $gp_mcnt integer slots, so an old int key's // new index is its reindexed position AFTER them if ( is_int( $gp_mk ) ) { $gp_mpos = -1; $gp_mseen = 0; foreach ( $gp_mlay[0] as $gp_mkk ) { if ( is_int( $gp_mkk ) ) { if ( $gp_mkk === $gp_mk ) { $gp_mpos = $gp_mseen; break; } $gp_mseen++; } } if ( $gp_mpos >= 0 ) { $gp_mnew[ $gp_mcnt + $gp_mpos ] = $gp_mval; } } else { $gp_mnew[ $gp_mk ] = $gp_mval; } } $gp_arr_danger[ $gp_mv ] = $gp_mnew; } if ( $bd <= end( $base ) ) { foreach ( $gp_mvals as $gp_mslot => $gp_mvp ) { $gp_mr = $resolve_name( $gp_mvp ); if ( '' !== $gp_mr[0] && 'str' === $gp_mr[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_mr[0] ) ), '\\' ) ) ) { $gp_arr_danger[ $gp_mv ][ $gp_mslot ] = ltrim( strtolower( trim( (string) $gp_mr[0] ) ), '\\' ); } } // ACG-149-119 (R18-001): values that came from a SPREAD source are already resolved foreach ( $gp_muvals as $gp_muslot => $gp_munm ) { $gp_arr_danger[ $gp_mv ][ $gp_muslot ] = $gp_munm; } } } elseif ( isset( $gp_arr_danger[ $gp_mv ] ) ) { unset( $gp_arr_danger[ $gp_mv ] ); // layout unknown -> fail toward clean } // ACG-149-114 (round 16): the `|| 5 === kind` matters - an array_splice REPLACEMENT can CREATE the first // dangerous slot (`$cb=["strlen"]; array_splice($cb,0,1,["system"]);`), so unlike pop/shift this arm has // to run even when the variable holds no facts yet, exactly like the push/unshift arms above. } elseif ( isset( $gp_arr_danger[ $gp_mv ] ) || 5 === (int) $gp_mutators[ $gp_mfn ] ) { // ACG-149-109 (round 14, R13-001): EXACT key transforms for the removing mutators. Round 13 retired // the whole map here, which was FP-safe but left `["strlen","system"]; array_shift($cb); $cb[0](…)` // clean even though the dangerous value is provably at 0 now. // ACG-149-113 (round 15, R14-001/002/004): pop / shift / splice act on POSITION in the array's ORDER, // never on key value. Derive the real ordered layout, remove the right POSITIONS, apply PHP's // renumbering, and remap the danger map through that. When the layout is not provable -> retire. $gp_mk3 = (int) $gp_mutators[ $gp_mfn ]; $gp_noop9 = false; // ACG-149-122 (round 22, R21-003): a REORDERING op (kind 9 - sort/rsort/shuffle/…) permutes the values // among the same positions. Where the permutation is not decidable the facts must retire, as before - // but two cases ARE decidable without knowing the ordering rule at all: // * a layout with ONE element: any permutation of one element is the identity, so nothing moves. // (`$cb = ["system"]; shuffle($cb); $cb[0](…)` was clean; PHP leaves "system" exactly where it is.) // * a layout where EVERY position already holds a dangerous value: whatever the permutation, every // position still holds one. // Anything mixed - `rsort(["strlen","system"])` - needs the real ordering semantics and stays a // documented residual, retiring toward clean. if ( 9 === $gp_mk3 && isset( $gp_arr_danger[ $gp_mv ] ) && isset( $gp_arr_whole[ $gp_mv ] ) && $i - (int) $gp_arr_whole[ $gp_mv ] < 2000 ) { $gp_r9 = $gp_arr_replay( $gp_mv, (int) $gp_arr_whole[ $gp_mv ] + 2, $i ); if ( null !== $gp_r9 && ! empty( $gp_r9[0] ) ) { $gp_n9 = count( $gp_r9[0] ); $gp_d9 = 0; foreach ( $gp_r9[0] as $gp_k9 ) { if ( isset( $gp_arr_danger[ $gp_mv ][ $gp_k9 ] ) ) { $gp_d9++; } } if ( 1 === $gp_n9 || $gp_d9 === $gp_n9 ) { $gp_noop9 = true; } } } $gp_mlay = ( 9 !== $gp_mk3 && isset( $gp_arr_whole[ $gp_mv ] ) && $i - (int) $gp_arr_whole[ $gp_mv ] < 2000 ) ? $gp_arr_replay( $gp_mv, (int) $gp_arr_whole[ $gp_mv ] + 2, $i ) : null; if ( null === $gp_mlay ) { // 9 = order depends on the VALUES, or the layout is unknown -> retire, UNLESS the permutation was // shown above to be a no-op for our purposes (one element, or every position already dangerous). if ( ! $gp_noop9 ) { unset( $gp_arr_danger[ $gp_mv ] ); } } else { $gp_mkeys = $gp_mlay[0]; $gp_mdrop = array(); $gp_mre = false; $gp_msplice = false; $gp_msp_remap = array(); $gp_msp_rkeys = array(); $gp_msp_rmap = array(); if ( 3 === $gp_mk3 ) { // array_shift: the FIRST element in order if ( ! empty( $gp_mkeys ) ) { $gp_mdrop[] = $gp_mkeys[0]; array_shift( $gp_mkeys ); } $gp_mre = true; } elseif ( 4 === $gp_mk3 ) { // array_pop: the LAST element in order if ( ! empty( $gp_mkeys ) ) { $gp_mdrop[] = $gp_mkeys[ count( $gp_mkeys ) - 1 ]; array_pop( $gp_mkeys ); } $gp_mre = false; // pop does NOT renumber the survivors } else { // array_splice($cb, off, len [, replacement]) // ACG-149-114 (round 16, R15-001): the shared helper handles the REPLACEMENT argument too, which // round 15 ignored - so `array_splice($cb,0,1,[])` (a plain delete) went clean, and a replacement // that INSERTS a dangerous name was invisible. It reports the surviving-key remap AND the new // keys of the inserted slots, so both effects are applied here. $gp_msp = $gp_splice_apply( $gp_mkeys, $gp_mcp ); if ( null === $gp_msp ) { $gp_mkeys = null; } else { $gp_mdrop = array(); foreach ( $gp_mkeys as $gp_mkv ) { $gp_mid2 = ( is_int( $gp_mkv ) ? 'i' : 's' ) . $gp_mkv; if ( ! isset( $gp_msp[1][ $gp_mid2 ] ) ) { $gp_mdrop[] = $gp_mkv; } // no remap entry = removed } $gp_msp_remap = $gp_msp[1]; $gp_msp_rkeys = $gp_msp[2]; $gp_msp_rmap = $gp_msp[4]; $gp_mkeys = $gp_msp[0]; $gp_mre = true; $gp_msplice = true; } } if ( null === $gp_mkeys ) { unset( $gp_arr_danger[ $gp_mv ] ); // non-literal splice bounds } else { $gp_mmap = array(); if ( $gp_msplice ) { $gp_mmap = $gp_msp_remap; } // the splice helper already built it elseif ( $gp_mre ) { list( , $gp_mmap, ) = $gp_arr_reindex( $gp_mkeys ); } $gp_mnew = array(); $gp_mcur = isset( $gp_arr_danger[ $gp_mv ] ) ? $gp_arr_danger[ $gp_mv ] : array(); // may be empty on the splice-insert path foreach ( $gp_mcur as $gp_mk => $gp_mval ) { if ( in_array( $gp_mk, $gp_mdrop, true ) ) { continue; } // the slot itself was removed if ( ! $gp_mre ) { $gp_mnew[ $gp_mk ] = $gp_mval; continue; } // pop: survivors keep their key $gp_mid = ( is_int( $gp_mk ) ? 'i' : 's' ) . $gp_mk; if ( isset( $gp_mmap[ $gp_mid ] ) ) { $gp_mnew[ $gp_mmap[ $gp_mid ] ] = $gp_mval; } } // ACG-149-114 (round 16, R15-001): the REPLACEMENT can itself INSERT a dangerous callable // (`array_splice($cb,0,1,["system"])`). Its own keys are discarded by PHP, so take its values in // ORDER (the layout gives the order, the danger scan gives which are dangerous) and place them at // the new keys the helper reported for the inserted slots. // ACG-149-115 (round 17): the helper now returns the replacement's dangerous values BY POSITION, // resolved through the shared array resolver - so an inline literal, a bareword/class array // CONSTANT, a variable holding a literal array, a scalar, and a NESTED value all arrive here the // same way. This replaces the ad-hoc re-parse that only understood an inline literal. if ( $gp_msplice && ! empty( $gp_msp_rkeys ) && ! empty( $gp_msp_rmap ) ) { foreach ( $gp_msp_rmap as $gp_mrpos => $gp_mrval ) { if ( isset( $gp_msp_rkeys[ $gp_mrpos ] ) ) { $gp_mnew[ $gp_msp_rkeys[ $gp_mrpos ] ] = $gp_mrval; } } } if ( empty( $gp_mnew ) ) { unset( $gp_arr_danger[ $gp_mv ] ); } else { $gp_arr_danger[ $gp_mv ] = $gp_mnew; } } } } } if ( ( 'call_user_func' === $gp_fapi || 'call_user_func_array' === $gp_fapi ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $gp_fk = $i + 2; $gp_fd = 1; $gp_farg = 0; $gp_fsteps = 0; $gp_is_fc = false; $gp_fc_cls_idx = -1; $gp_fc_cls_txt = ''; $gp_fc_danger = false; $gp_fc_obj_other = false; $gp_fend = -1; while ( $gp_fk < $n && $gp_fd > 0 && $gp_fsteps++ < 5000 ) { $gp_fx = $tok[ $gp_fk ]; if ( $is_char( $gp_fx, '(' ) || $is_char( $gp_fx, '[' ) ) { $gp_fd++; $gp_fk++; continue; } if ( $is_char( $gp_fx, ')' ) || $is_char( $gp_fx, ']' ) ) { $gp_fd--; if ( 0 === $gp_fd ) { $gp_fend = $gp_fk; break; } $gp_fk++; continue; } if ( $is_char( $gp_fx, ',' ) && 1 === $gp_fd ) { $gp_farg++; $gp_fk++; continue; } if ( 0 === $gp_farg ) { // ARGUMENT 0 — does it denote Closure::fromCallable ? // ACG-147-005: each HALF is an OPERAND resolved by P1, so `["Clo"."sure",…]`, // `[$c,"fromCallable"]`, `["Closure","from"."Callable"]` and a variable holding // the whole `"Closure::fromCallable"` all resolve. Reading one token here was // the reviewer's ACG-146-001: five one-line spellings of a closed detection. // Resolve the operand, then SKIP the tokens it consumed. Without the skip the // loop re-reads each half of `"Clo" . "sure"` on its own and the fused value is // overwritten by the fragment - the concat spellings stayed invisible. $gp_fres = $resolve_name( $gp_fk ); if ( '' !== $gp_fres[0] ) { $gp_flit = trim( $gp_fres[0] ); $gp_fpos = strpos( $gp_flit, '::' ); if ( false !== $gp_fpos ) { // 'Closure::fromCallable' if ( 'fromcallable' === strtolower( substr( $gp_flit, $gp_fpos + 2 ) ) ) { $gp_is_fc = true; $gp_fc_cls_txt = substr( $gp_flit, 0, $gp_fpos ); // ACG-149-089 (reviewer round 3, MS-002 #1): a ::class-derived class half (sym) is // namespace-sensitive - signal it to the namespace-aware globality check below. if ( 'sym' === $gp_fres[1] ) { $gp_fc_cls_idx = $gp_fk; } } } elseif ( 'fromcallable' === strtolower( $gp_flit ) ) { $gp_is_fc = true; // the METHOD half of an array callable } else { $gp_fc_cls_txt = $gp_flit; // the CLASS half // a 'sym' value came from ::class / a bareword -> namespace-sensitive, // which the existing block below signals via a non-negative index. if ( 'sym' === $gp_fres[1] ) { $gp_fc_cls_idx = $gp_fk; } } // ACG-149-089 (reviewer round 3, MS-002 #1): skip the WHOLE resolved operand to the arg-0 // boundary (a depth-0 comma / the call's close). The old `.`-pair skip missed a // `Closure::class` or a concat chain's interior `::`/`.`, so the re-scan re-read a fragment // (`"::fromCallable"`) and OVERWROTE $gp_fc_cls_txt to '' - a false negative on // `call_user_func(Closure::class . "::fromCallable", "system")(..)`. $gp_fadv = $gp_fk; $gp_fdep = 0; $gp_fskip = 0; while ( $gp_fadv < $n && $gp_fskip++ < 5000 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_fadv ], '(' ) || $is_char( $tok[ $gp_fadv ], '[' ) ) { $gp_fdep++; } elseif ( $is_char( $tok[ $gp_fadv ], ')' ) || $is_char( $tok[ $gp_fadv ], ']' ) ) { if ( 0 === $gp_fdep ) { break; } $gp_fdep--; } elseif ( 0 === $gp_fdep && $is_char( $tok[ $gp_fadv ], ',' ) ) { break; } $gp_fadv++; } $gp_fk = ( $gp_fadv > $gp_fk ) ? $gp_fadv - 1 : $gp_fk; } elseif ( is_int( $gp_fx[0] ) && ( T_STRING === $gp_fx[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $gp_fx[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $gp_fx[0] ) ) ) { // `Closure::class` if ( $gp_fk + 2 < $n && is_int( $tok[ $gp_fk + 1 ][0] ) && T_DOUBLE_COLON === $tok[ $gp_fk + 1 ][0] && is_int( $tok[ $gp_fk + 2 ][0] ) && 'class' === strtolower( (string) $tok[ $gp_fk + 2 ][1] ) ) { $gp_fc_cls_idx = $gp_fk; $gp_fc_cls_txt = (string) $gp_fx[1]; } } } else { // ARGUMENT 1+ — the callable the factory is being given. // ACG-147-005: the callable being handed to the factory is an operand as well. $gp_fcb = $resolve_name( $gp_fk ); if ( '' !== $gp_fcb[0] && $danger_name( $gp_fcb[0] ) ) { $gp_fc_danger = true; } elseif ( is_int( $gp_fx[0] ) && T_VARIABLE === $gp_fx[0] && isset( $danger_cb[ $gp_fx[1] ] ) ) { $gp_fc_danger = true; } elseif ( $is_super( $gp_fx ) || $is_tainted( $gp_fx ) || $is_fn( $gp_fx, $req_read ) ) { $gp_fc_danger = true; } } $gp_fk++; } // The class must be PHP's own \Closure. `$class_is_global` resolves imports and namespace // regions, so `namespace X; class Closure {...}` is NOT reported. // ACG-146-004: a class name written as a STRING is resolved by PHP as FULLY QUALIFIED - // no namespace, no imports. Running it through the namespace-aware class resolver let a // one-line `namespace X;` prefix suppress the whole arm. Only `Closure::class` is // compile-time resolved and therefore namespace-sensitive. if ( $gp_fc_cls_idx >= 0 ) { $gp_fc_global = $class_is_global( $gp_fc_cls_txt, 'closure', $gp_fc_cls_idx ); } else { $gp_fc_global = ( 'closure' === strtolower( ltrim( trim( $gp_fc_cls_txt ), chr( 92 ) ) ) ); } if ( $gp_is_fc && $gp_fc_global && $gp_fc_danger && $gp_fend > 0 ) { // Immediately invoked? call_user_func(...)( $_POST['a'] ) $gp_finv = $invocation_args( $gp_fend, 0 ); if ( $gp_finv ) { $gp_fa = $gp_finv; $gp_fad = 1; $gp_freq = false; $gp_fs2 = 0; while ( $gp_fa < $n && $gp_fad > 0 && $gp_fs2++ < 5000 ) { $gp_fax = $tok[ $gp_fa ]; if ( $is_char( $gp_fax, '(' ) ) { $gp_fad++; } elseif ( $is_char( $gp_fax, ')' ) ) { $gp_fad--; } elseif ( $is_super( $gp_fax ) || $is_fn( $gp_fax, $req_read ) || $is_tainted( $gp_fax ) ) { $gp_freq = true; } $gp_fa++; } if ( $gp_freq ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } } else { // ASSIGNED form: `$f = call_user_func([...],'system'); $f($_POST['a']);` // Recorded in the SAME $danger_cb set, so the existing machinery reports the call. $gp_ft = $i - $wrap_before( $i ) - 1; if ( $gp_ft >= 1 && $is_char( $tok[ $gp_ft ], '=' ) && is_int( $tok[ $gp_ft - 1 ][0] ) && T_VARIABLE === $tok[ $gp_ft - 1 ][0] ) { $danger_cb[ $tok[ $gp_ft - 1 ][1] ] = 1; } } } } // ACG-145-001: the API's OWN name is normalised too, not just the callable it receives. // `\call_user_func("system", $_POST['a'])` returned NO FINDINGS - a one-character bypass. $gp_api = $called_fn( $i ); if ( '' !== $gp_api && isset( $cb_apis[ $gp_api ] ) ) { $cidx = $cb_apis[ $gp_api ]; $k = $i + 2; $d = 1; $argn = 0; $hit = false; $hit_super = false; $cb_name = ''; $cb_run = false; $cb_done = false; $any_super = false; $gp_cb_obj = false; $gp_cb_indirect = false; $gp_cb_bounded = false; $gp_cb_arrcall = false; $gp_cb_reqbase = false; $gp_cb_treq = false; $gp_cb_const_danger = false; $cb_poison = false; // ACG-149-134 (R27-004): a literal after a function name is that function's ARGUMENT // ACG-149-091 (round 4, MS-002): resolve the callable-slot OPERAND when it is arg 0 (call_user_func / // array_map / ...), so a bareword or class CONSTANT holding a dangerous name - `call_user_func(F, $_POST)`, // `call_user_func(C::F, $_POST)` - is caught. A class-constant's `::` will set $gp_cb_obj in the slot scan // below, so a proven-dangerous resolved constant carries its OWN flag that bypasses the bounded-object // gate at the emit. A genuine Foo::method / [$obj,'m'] never resolves through P1, so it stays bounded. // ACG-149-121 (round 21, self-found RCE BYPASS): resolve the ACTUAL callback argument, whichever index it // is - not a fixed `$i + 2` gated to `0 === $cidx`. `$cb_apis` splits into callback-FIRST (call_user_func, // array_map, …) and callback-SECOND (array_filter, usort, uasort, uksort, array_walk, array_reduce, …), // and the shared name resolver only ever ran on the first group. So // `array_filter($_POST["x"], base64_decode("c3lzdGVt"))` - which really executes system() on every // request element - was reported CLEAN, while the identical `array_map(base64_decode(...), $_POST["x"])` // was critical. Same disguise, same danger, different argument index. This is the recurring lesson twice // over: route every spelling through the ONE shared resolver, and never key on a FIXED TOKEN OFFSET. $gp_cbp = -1; if ( $i + 2 < $n ) { if ( 0 === $cidx ) { $gp_cbp = $i + 2; } else { $gp_ca = $gp_mut_args( $i, array() ); // positional starts; a named argument yields null -> skip $gp_cbp = ( null !== $gp_ca && isset( $gp_ca[0][ $cidx ] ) ) ? (int) $gp_ca[0][ $cidx ] : -1; } } if ( $gp_cbp >= 0 ) { $gp_cb_res = $resolve_name( $gp_cbp ); if ( '' === $gp_cb_res[0] ) { $gp_cb_ial = $gp_inline_arr_leaf( $gp_cbp ); if ( '' !== $gp_cb_ial ) { $gp_cb_res = array( $gp_cb_ial, 'str' ); } } // ACG-149-102 (R10-003): inline `(["system"])[0]` callback arg if ( '' === $gp_cb_res[0] || ! $danger_name( ltrim( strtolower( trim( (string) $gp_cb_res[0] ) ), '\\' ) ) ) { $gp_cb_vr = $gp_arr_valret( $gp_cbp ); if ( '' !== $gp_cb_vr[0] ) { $gp_cb_res = array( $gp_cb_vr[0], 'str' ); } } // ACG-149-123 (R22-001): `call_user_func(array_splice($cb,0,1)[0], …)` if ( '' !== $gp_cb_res[0] && 'str' === $gp_cb_res[1] && $danger_name( ltrim( strtolower( trim( (string) $gp_cb_res[0] ) ), '\\' ) ) ) { $cb_name = ltrim( strtolower( trim( (string) $gp_cb_res[0] ) ), '\\' ); $gp_cb_const_danger = true; } } // ACG-107 fresh-eyes (2026-07-01): a CLOSURE / arrow-fn passed as a callback is a fixed literal, NOT a // request-controlled callable — the superglobals it READS inside its own body are the normal // "array_map(function($n){ return $_COOKIE[$n]; }, …)" idiom (Elementor/WooCommerce). Skip superglobals // inside a closure body {…} or an arrow body (=> … up to the arg boundary) so they never masquerade as // "a superglobal used AS the callable". $brace = 0; $fn_pending = false; $arrow = false; $fnn_pending = false; $bracket = 0; // ACG-149-031: short-array depth while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { $x = $tok[ $k ]; // ACG-136-002 (review round 4): a CLOSURE / arrow-fn literal in the callable slot is fixed // code the developer wrote — it can never be an attacker-chosen function name, so it is not // the plain-$f webshell no matter what its use(...) clause captures. Without this, the // Contact Form 7 line // array_map( static function ( $value ) use ( $pipes ) { ... }, $value ) // tripped the rule: the use( $pipes ) tokens sit in the callable slot BEFORE the body brace, // so a tainted $pipes read as "tainted callable". Found by the clean-corpus run. if ( is_int( $x[0] ) && T_FUNCTION === $x[0] ) { if ( $argn === $cidx ) { $gp_cb_obj = true; } $fn_pending = true; $k++; continue; } if ( is_int( $x[0] ) && defined( 'T_FN' ) && T_FN === $x[0] ) { if ( $argn === $cidx ) { $gp_cb_obj = true; } $fnn_pending = true; $k++; continue; } if ( $fnn_pending && is_int( $x[0] ) && defined( 'T_DOUBLE_ARROW' ) && T_DOUBLE_ARROW === $x[0] ) { $arrow = true; $fnn_pending = false; $k++; continue; } if ( $is_char( $x, '{' ) || ( is_int( $x[0] ) && ( T_CURLY_OPEN === $x[0] || ( defined( 'T_DOLLAR_OPEN_CURLY_BRACES' ) && T_DOLLAR_OPEN_CURLY_BRACES === $x[0] ) ) ) ) { if ( $fn_pending || $brace > 0 ) { $brace++; $fn_pending = false; } $k++; continue; } // ACG-149-031: "${x}" interpolation braces if ( $is_char( $x, '}' ) ) { if ( $brace > 0 ) { $brace--; } $k++; continue; } if ( $is_char( $x, '(' ) ) { $d++; } elseif ( $is_char( $x, ')' ) ) { $d--; } // ACG-149-031: a '[' array literal - its inner comma is NOT an argument separator. A // top-level '[' in the callable slot is an array-callable ([$obj,'m']) -> bounded set. elseif ( $is_char( $x, '[' ) ) { if ( $argn === $cidx && 0 === $bracket && 0 === $brace && ! $cb_done ) { // ACG-149-092: once the slot NAME is resolved (nested chain), a later '[' of the SAME chain must not reclassify it as a bounded object $gp_cb_base = ( $k - 1 >= 0 ) ? $tok[ $k - 1 ] : null; // ACG-149-090 (MS-004): `call_user_func($cb[], $_POST[..])` where $cb holds a literal // array with a DANGEROUS function name at that constant index is a hidden webshell - resolve the // slot to the callable exactly like the $danger_cb VAR case below (sets $cb_name, NOT $gp_cb_obj, // so the 8010 emit fires with the request argument). A safe slot records nothing -> stays bounded. $gp_slot_leaf = null; $gp_slot_end = -1; if ( null !== $gp_cb_base && is_int( $gp_cb_base[0] ) && T_VARIABLE === $gp_cb_base[0] && isset( $gp_arr_danger[ $gp_cb_base[1] ] ) ) { list( $gp_slot_leaf, $gp_slot_end ) = $gp_arr_descend( $gp_arr_danger[ $gp_cb_base[1] ], $k ); // ACG-149-092: descend the FULL subscript chain ($cb["a"]["b"], $cb[K::X]) } if ( null !== $gp_slot_leaf && $gp_slot_end < $n && ( $is_char( $tok[ $gp_slot_end ], ',' ) || $is_char( $tok[ $gp_slot_end ], ')' ) ) ) { $cb_name = 'system'; $cb_done = true; } elseif ( null !== $gp_cb_base && ( $is_char( $gp_cb_base, '(' ) || $is_char( $gp_cb_base, ',' ) ) ) { $gp_cb_obj = true; $gp_cb_arrcall = true; if ( $gp_ac_reqbase( $k ) ) { $gp_cb_reqbase = true; } // '[' at SLOT START ([$obj,'m']) is a genuine array-callable (ACG-149-082 #7: reqbase if the object element is request-derived) } elseif ( null !== $gp_cb_base && is_int( $gp_cb_base[0] ) && T_VARIABLE === $gp_cb_base[0] && isset( $tainted[ $gp_cb_base[1] ] ) && ! ( isset( $gp_arr_whole[ $gp_cb_base[1] ] ) && isset( $gp_taint_pos[ $gp_cb_base[1] ] ) && $gp_arr_whole[ $gp_cb_base[1] ] > $gp_taint_pos[ $gp_cb_base[1] ] ) ) { // ACG-149-086 (siege 19 #1): a subscript on a REQUEST-TAINTED base - `call_user_func($a['f'],..)` // where an earlier `parse_str($_SERVER['QUERY_STRING'], $a)` filled $a from the request - is a // request-CHOSEN callee, not a fixed handler registry. The direct-call sibling `$a['f'](..)` already // fires here via base-provenance; this callback-API arm was treating ANY `$var[...]` as a bounded // object ($gp_cb_obj) and silently dropping it. Mirror the direct-call arm: level-2 (laundered) // taint reviews, level-1 (direct request) is the request-callee malware. The $gp_arr_whole guard // reproduces $gp_super_is_fixedkey (5704-5711): a tainted base that is REASSIGNED a whole // `= array(..)` more recently than the taint (S14d) currently holds a fixed table -> bounded. if ( 2 === (int) $tainted[ $gp_cb_base[1] ] ) { $gp_cb_indirect = true; } else { $gp_cb_treq = true; } } else { $gp_cb_obj = true; // ACG-149-081 #6: a '[' after a NON-tainted variable ($handlers[$_POST['op']]) is a subscript into a FIXED registry -> bounded object } } $bracket++; } elseif ( $is_char( $x, ']' ) ) { if ( $bracket > 0 ) { $bracket--; } } elseif ( $is_char( $x, ',' ) && 1 === $d && 0 === $brace && 0 === $bracket ) { if ( $arrow ) { $arrow = false; } $argn++; } elseif ( 0 === $brace && ! $arrow ) { // ACG-149-031: the slot scanner still SEES tokens inside a [ ] args array (a request value there is what makes a dangerous callee critical); only the arg-COMMA counter and the callable-name slot are bracket-aware if ( $argn === $cidx ) { // ACG-136-002 (review round 4): is the callable an OBJECT/TABLE reference rather than a // plain scalar variable? array($this,'m') / [$app,$method] / $this->actions[$k]['callback'] // can only reach a METHOD ON AN OBJECT (or an entry in a table the developer registered) — // a bounded set. Only a plain $f can become `system`. This is the same distinction already // applied to $this->$m() in the direct-call block, and it is required: without it the // broadened rule flagged Contact Form 7's array_map(array($this,'sanitize_posted_data'), // $value) and Elementor's registered-ajax-action dispatcher as CRITICAL MALWARE — caught // by the clean-corpus run, not by reasoning. // ACG-141-005 (adversarial review): `Closure::fromCallable(...)` is a FACTORY CALL, // not a `Foo::method` array-callable, so its `::` must not trip the bounded-callable // guard. It did — which meant wrapping the literal in the factory laundered it past // the very detector that catches the bare literal: // array_map( 'system', $_POST['items'] ); // malware // array_map( Closure::fromCallable('system'), $_POST['items'] ); // was CLEAN // The literal inside the factory is collected by the fusion below, so once the guard // stops firing the existing $danger_name check reports it. // ACG-141-006 (adversarial review): the CLASS matters. Testing only the METHOD // name dropped the bounded-callable guard for ANY class exposing a static // fromCallable() - `Foo::fromCallable('extract')`, // `MyClosure::fromCallable('parse_str')` - so legitimate vendor code became // CRITICAL malware. That is precisely the false-positive class this guard exists // to prevent. Only PHP's own Closure yields a genuine global callable. $gp_is_factory = ( is_int( $x[0] ) && T_DOUBLE_COLON === $x[0] && $k + 1 < $n && is_int( $tok[ $k + 1 ][0] ) && T_STRING === $tok[ $k + 1 ][0] && 'fromcallable' === strtolower( $tok[ $k + 1 ][1] ) && $k - 1 >= 0 && is_int( $tok[ $k - 1 ][0] ) // ACG-143-001: resolve, do not string-compare (see the arm above). && $class_is_global( (string) $tok[ $k - 1 ][1], 'closure', $k - 1 ) ); if ( ! $cb_done && ! $gp_is_factory && is_int( $x[0] ) && ( T_OBJECT_OPERATOR === $x[0] || T_DOUBLE_COLON === $x[0] || T_ARRAY === $x[0] ) ) { $gp_cb_obj = true; if ( T_ARRAY === $x[0] ) { $gp_cb_arrcall = true; if ( $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && $gp_ac_reqbase( $k + 1 ) ) { $gp_cb_reqbase = true; } } } // ACG-149-081 #6: array(...) callable (ACG-149-092: a resolved nested slot NAME already set $cb_done - a class-const KEY's `::` must not reclassify) // A PHP 8.1 first-class callable in the callable slot — `call_user_func(system(...), …)` // — carries its name as a T_STRING, which the literal fusion never collects. if ( '' === $cb_name && is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) ) && $danger_name( $x[1] ) && $k + 2 < $n && $is_char( $tok[ $k + 1 ], '(' ) && defined( 'T_ELLIPSIS' ) && is_int( $tok[ $k + 2 ][0] ) && T_ELLIPSIS === $tok[ $k + 2 ][0] && ! ( is_int( $tok[ $k - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $k - 1 ][0] || T_DOUBLE_COLON === $tok[ $k - 1 ][0] ) ) ) { $cb_name = strtolower( trim( $x[1] ) ); $cb_done = true; } // ACG-149-031: '[' is handled at the top level now (bracket depth). // ACG-105 fresh-eyes: a DIRECT superglobal as the callable (a request value passed as // the callback to call_user_func/array_map/…) is a confirmed request-controlled call; a // tainted variable, or the RETURN of a request reader (filter_input()/getallheaders()) used // as the callable, is the ambiguous/framework form → review. // ACG-143-003: a VARIABLE proven to hold a dangerous callable // (`$f = "system"; call_user_func($f, $_POST['a'])`) is exactly as dangerous as // the literal spelled in place, and was returning NO FINDINGS. if ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $danger_cb[ $x[1] ] ) ) { $cb_name = 'system'; $cb_done = true; } // ACG-149-130b (self-found, and it is the "one spelling fixed, the rest ship" trap): // the callable slot holding a NAME-BOUNDED variable is bounded for exactly the reason // $gp_cb_bounded already exists - it cannot reach a global function. // $fn = "su_ajax_" . sanitize_key( $_POST['act'] ); call_user_func( $fn, $_POST ); // is the same WordPress dispatcher as the direct `$fn( $_POST )` one line of code away, // and `call_user_func($fn, …)` is if anything the MORE common spelling in real plugins. // Setting the flag here covers call_user_func, call_user_func_array, array_map, // array_filter, usort/uasort/uksort, array_reduce, array_walk, register_shutdown_function, // register_tick_function, set_error_handler, spl_autoload_register, forward_static_call and // preg_replace_callback in ONE place, because they all reach this same slot examination. if ( is_int( $x[0] ) && T_VARIABLE === $x[0] && $argn === $cidx && $gp_name_bound( $x[1] ) ) { $gp_cb_bounded = true; } // ACG-149-075 (siege 12 #5): a super used as the KEY into a fixed-array registry - // `call_user_func($h[$_POST['op']], ...)` where $h is an array literal - is a BOUNDED table // (the request picks a KEY, not the function). Consistent with the direct-call demotion // (ACG-149-048), route it to review ($hit + $gp_cb_bounded), never the request-CHOSEN-callee // malware. A real China-Chopper `call_user_func($_POST['fn'], ...)` puts the super itself in // the slot (preceded by '(' not '['), so $hit_super still fires. if ( $is_super( $x ) ) { // ACG-149-077 (siege 13 #1/#5/#6/#7): mirror the direct-call sibling's guards (ACG-149-048) - // a base that is a SUPERGLOBAL or is TAINTED (a request value written into one of its // elements, `$h['y']=$_POST['fn']`) is NOT a bounded fixed registry; it stays malware. // ACG-149-081 (siege 14 #6): a super INSIDE an array/object callable slot // (`array($this, sanitize_key($_POST['a']))`, `[$obj, $_GET['m']]`) picks a METHOD NAME on a // bounded object/class - it can never reach a global function, the identical reason every // malware emit here already requires `! $gp_cb_obj`. So it is bounded, never the China-Chopper // $hit_super (which fires regardless of $gp_cb_obj at the emit). A real `call_user_func($_POST['fn'])` // puts the super directly in the slot with NO array wrapper, so $gp_cb_obj stays false and it fires. // ACG-149-082 (siege 15 #7): only bounded when the object/class element is FIXED - a fully // request-controlled `array($_POST['cls'], $_POST['m'])` is an arbitrary static call and fires. if ( ( $gp_cb_arrcall && ! $gp_cb_reqbase ) || $gp_super_is_fixedkey( $k ) ) { $hit = true; $gp_cb_bounded = true; } // ACG-149-081 #6: array-callable METHOD slot; ACG-149-078 (#3/#4): plain-var arr_lit OR property/static bounded table // ACG-149-086-fix (siege 19 adversarial review, FP #6): a super in the callable slot that is // only a ternary CONDITION selecting between FIXED callables - `array_map($_GET['mode']==='raw' // ? 'trim' : 'sanitize_text_field', $rows)` - does not name the callee; the fixed literal branch // does, and the literal-run logic below resolves it. The direct/shell arms already consult // $gp_super_is_cond; the callback-API slot never did, branding this idiom critical malware. A real // China-Chopper `call_user_func($_POST['fn'], ..)` is NOT condition-only ($gp_super_is_cond sees the // sink call_user_func enclosing the super and returns false), so it still fires. elseif ( ! $gp_super_is_cond( $k ) ) { $hit_super = true; } } // ACG-149-027 (siege 2 #13): a socket-derived callee - `call_user_func($c)` / // `array_map($c, ...)` where $c is bytes read off a socket - is an attacker-chosen // callable, wired here exactly like a request-tainted one (fix 6 covered the direct // $c() / eval / shell arms but not this callback-API arm). elseif ( $is_tainted( $x ) || $is_fn( $x, $req_read ) || ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $gp_sock_data[ $x[1] ] ) ) ) { $hit = true; if ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $tainted[ $x[1] ] ) && 2 === (int) $tainted[ $x[1] ] ) { $gp_cb_indirect = true; } } // ACG-138-R2-02b: indirect callable taint → review // ACG-141-001: fuse a callable name SPLIT ACROSS ADJACENT LITERALS, exactly as the // Closure::fromCallable arm already did — `call_user_func("sys" . "tem", $_POST[..])` // was a one-token bypass of this whole rule. Only a literal '.' continues the run, // so unrelated literals elsewhere in the slot cannot fuse (the same discipline the // include-path accumulator needed after it produced false positives). // ACG-149-134 (round 28, R27-004): POISON the run once a FUNCTION NAME has been seen // while no callable name is established. From that point every literal in the slot is // that function's ARGUMENT, not the callee - `md5("system")`, `strlen("system")`, // `crc32("system")` were all reported as a request-controlled system() call. A literal // inside an unresolved name expression is not the effective callable name. The proper // resolver above still proves trim("system") / "sys"."tem" / ("sys").("tem") / // system(...), which is everything this crude run was ever for. if ( '' === $cb_name && ! $cb_poison && is_int( $x[0] ) && ( T_STRING === $x[0] || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $x[0] ) || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $x[0] ) ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) // ...EXCEPT a NAME-PRESERVING callable factory. `Closure::fromCallable("system")`, // `(new ReflectionFunction("system"))->invoke(...)` and `getClosure()` all hand back a // callable that denotes the literal inside them, so that literal IS the name - and the // crude run is what the factory arms lean on for it. Poisoning those took five existing // fixtures with it, which is precisely the false-negative-from-a-false-positive-fix trap // this review keeps producing. An OPAQUE call (md5/strlen/crc32) still poisons. && ! in_array( strtolower( (string) $x[1] ), array( 'fromcallable', 'invoke', 'invokeargs', 'getclosure', 'reflectionfunction', 'reflectionmethod', 'closure' ), true ) ) { $cb_poison = true; } if ( is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] && ! $cb_poison ) { if ( ! $cb_done ) { $cb_seg = strtolower( trim( $decode( $x[1] ) ) ); $cb_name = $cb_run ? ( $cb_name . $cb_seg ) : ( '' === $cb_name ? $cb_seg : $cb_name ); $cb_run = false; } } elseif ( $is_char( $x, '.' ) ) { if ( ! $cb_done ) { $cb_run = true; } } else { // ACG-141-004 (adversarial review): anything that is NOT a literal and NOT the // concatenation operator ENDS the run. Without this a VARIABLE between literals // kept it alive — `'a' . $sep . 'ssert'` fused to "assert" and was reported as // CRITICAL malware, which also falsified the comment above claiming only // adjacent literals fuse. (Parens never reach here: they are consumed by the // depth bookkeeping above, so ('sys').('tem') still fuses correctly.) // The first maximal literal run is FINAL. Clearing only the run flag was not // enough: a later '.' re-opened it and appended to the STALE prefix, so // 'a' . $sep . 'ssert' still fused to "assert". if ( '' !== $cb_name ) { $cb_done = true; } $cb_run = false; } } // ACG-105 fresh-eyes: "request data present anywhere in the call" — count a literal superglobal // OR a request-reader (filter_input/getallheaders/…), so a dangerous callable fed request input // via filter_input is caught too. Only ever consulted alongside a $danger callable, so benign // callables are unaffected. // ACG-136-002 (review round 4): count a TAINTED VARIABLE as request data too. // This only recognised a literal superglobal or a request-reader CALL, so one // variable hop hid the request entirely from this block: // $a = $_POST['a']; call_user_func('system', $a); -> reported CLEAN // $a = $_POST['a']; array_map('system', $a); -> reported CLEAN // $f = $_POST['f']; $a = $_POST['a']; call_user_func($f, $a); -> review only // while the direct `$a = $_POST['a']; system($a);` was correctly malware — the // wrapper was the whole difference. call_user_func('system', $tainted) has exactly // the capability of system($tainted); the wrapper is not a mitigation. $is_tainted // is the same taint set tk_shell_request already follows into a sink. // The callable POSITION is excluded ($argn !== $cidx): this loop visits every token // in the call, so without that guard a tainted callable would count as its own // data argument and `call_user_func($f, 'literal')` — attacker picks the function // but supplies no data — would be promoted to malware. "Request data present" // must mean present in an ARGUMENT, never in the callee slot. if ( $argn !== $cidx && ( $is_super( $x ) || $is_fn( $x, $req_read ) || $is_tainted( $x ) ) ) { $any_super = true; } } $k++; } // A literal dangerous callable name (assert/system/…) fed request data (China-Chopper) is confirmed malware. // // ACG-138-R2-01 (reviewer 2, 2026-07-17): ...but ONLY when the name denotes the GLOBAL function. // This arm harvested $cb_name from the callable slot and looked it up in $danger[] without // consulting $gp_cb_obj — the very flag the NEXT arm uses for exactly this distinction. So an // object/array callable whose METHOD happens to share a dangerous name was CRITICAL MALWARE: // array_map( array( $this, 'extract' ), $_POST['items'] ); // -> CRITICAL (false) // array_filter( $_POST, array( $this, 'assert' ) ); // -> CRITICAL (false) // usort( $_POST['rows'], array( $obj, 'exec' ) ); // -> CRITICAL (false) // `[$obj,'extract']` can only reach a METHOD NAMED extract on that object — never PHP's global // extract(). assert/exec/extract are ordinary method names (PHPUnit, Webmozart Assert, Symfony // Validator, PDO, ZIP/archive handlers, DTOs, parsers). The bounded-set reasoning was already // written and applied one line below; it simply was not applied here. // // I originally left this alone because the clean corpus contains no instance and therefore // could not gate a fix. Reviewer 2 rejected that reasoning and is right: "no corpus instance" // is a reason to EXTEND the corpus, not to ship a known CRITICAL false positive. The synthetic // fixtures are in the callable harness (R8/R9/R10/R11) and a clean-vendor fixture file now // carries the shape, so the gate exists. // NOT an FN: a real China-Chopper is a LITERAL name in the callable slot (`'assert'`, // 'system'), which sets no $gp_cb_obj — those still fire. Only the array/object form is spared, // and it is the form that cannot reach a global function at all. // ACG-149-091 (round 4, MS-002): a proven-dangerous RESOLVED constant in the callable slot // ($gp_cb_const_danger) is a hidden name, not a bounded object, so it fires WITH a request argument // regardless of the $gp_cb_obj its `::` set. call_user_func(C::F, $_POST) / call_user_func(F, $_POST). if ( $hit_super || ( $danger_name( $cb_name ) && $any_super && ! $gp_cb_obj ) || ( $gp_cb_const_danger && $any_super ) ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } // ACG-149-086 (siege 19 #1): a subscript on a request-tainted base ($a['f'] where an earlier // parse_str filled $a from the request) has NO literal super in the slot, so the $any_super // malware emit below never fired - the call fell through to review, or before this fix was // dropped entirely as a bounded $gp_cb_obj. It is the exact callback-API analogue of the direct // call `$a['f'](..)` (which fires tk_dyn_request_callee_var via base-provenance) and must carry // the identical critical severity. $gp_cb_treq is only set for LEVEL-1 (direct) taint; level-2 // laundering sets $gp_cb_indirect instead and degrades to the review emit below. // ACG-149-086-fix (siege 19 adversarial review, FP #1): REQUIRE a request-derived DATA argument // ($any_super, which the 7675 scan sets for a super/tainted/req_read arg) exactly as the direct-call // sibling requires $gp_arg_req. Without it, `$fmt=array_fill_keys($_GET['cols'],'esc_html'); // call_user_func($fmt[$c], $row)` - a uniform key->FIXED-literal map with a NON-request argument - // was branded critical malware, the owner's #1-fear FP on idiomatic sanitizer/formatter maps. A // tainted base with a plain argument now degrades to the review emit below, matching the direct-call // arm ($a=$_POST; $a['f']($x) is a review item there). The real webshell keeps a request arg // ($a['f']($a['x']) / call_user_func($a['f'],$_POST['x'])) and still fires critical. elseif ( $hit && $gp_cb_treq && $any_super ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee_var', 'name' => 'Request-Controlled Dynamic Call (via variable)', 'severity' => 'critical' ); } // ACG-135-002 (review round 3): the SAME one-hop webshell laundered through a callback API. // $f = $_POST['f']; call_user_func( $f, $_POST['a'] ); // $f = $_POST['f']; call_user_func_array( $f, [ $_POST['a'] ] ); // $f = $_POST['f']; array_map( $f, $_POST['a'] ); // ACG-122 promoted the plain `$f($_POST['a'])` form to malware but left these as review, so the // identical attack — attacker picks the function AND its input; $f=system is a webshell — was // still reported under "no malware found". call_user_func($f, …) has exactly the capability of // $f(…); the wrapper is not a mitigation. // Same narrowness as the plain-call rule: the callable must be a tainted VARIABLE (a literal // callable name is handled by $danger above; a closure/arrow body is already skipped) AND the // call must carry request data. The Elementor-style validated dispatcher is $this->$m(), which // never reaches this block. Gated on the clean corpus, not on reasoning. elseif ( $hit && $any_super && ! $gp_cb_obj && ! $gp_cb_indirect && ! $gp_cb_bounded ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee_var', 'name' => 'Request-Controlled Dynamic Call (via variable)', 'severity' => 'critical' ); } // ACG-149-075 // ACG-143-009 (clean-corpus gate, 2026-07-19): the BOUNDED-CALLABLE exemption argued at // length above was applied to both malware emits and forgotten here, on the review emit. // `array( $this, 'order_callback' )` names a fixed method on a known class -- it cannot // reach a global function, which is the entire reason the malware arms exempt it -- so it // must not produce a dynamic-call finding of ANY class. Surfaced by stock WordPress core: // $this->items = $api->plugins; // taints $this via a property write // uasort( $this->items, array( $this, 'order_callback' ) ); // wp-admin/includes/class-wp-plugin-install-list-table.php:252 became a new review item the // moment ACG-143-006 stopped popping the scope early and $this stayed tainted to that line. // The bug had been masking the over-broad rule, not preventing it. elseif ( $hit && ! $gp_cb_obj ) { $found['dyn'] = array( 'id' => 'tk_dyn_superglobal_call', 'name' => 'Dynamic Call From Request', 'severity' => 'critical' ); } } // (6) PARAM-FORWARDING call site: forwardingFunc( ..., , ... ) where the request lands in a // parameter the callee uses as a dynamic callable. if ( ! $prev_op && is_int( $e[0] ) && T_STRING === $e[0] && isset( $fwd[ strtolower( $e[1] ) ] ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) && ! ( $i - 1 >= 0 && is_int( $tok[ $i - 1 ][0] ) && T_FUNCTION === $tok[ $i - 1 ][0] ) ) { $idxs = $fwd[ strtolower( $e[1] ) ]; $k = $i + 2; $d = 1; $argn = 0; $hit = false; $hit_super = false; while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { $x = $tok[ $k ]; if ( $is_char( $x, '(' ) ) { $d++; } elseif ( $is_char( $x, ')' ) ) { $d--; } elseif ( $is_char( $x, ',' ) && 1 === $d ) { $argn++; } elseif ( isset( $idxs[ $argn ] ) && $is_super( $x ) ) { $hit_super = true; } elseif ( isset( $idxs[ $argn ] ) && $is_tainted( $x ) ) { $hit = true; } $k++; } // ACG-105 fresh-eyes: forwarding a DIRECT superglobal into a dynamic-callable parameter is confirmed malware. if ( $hit_super ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } elseif ( $hit ) { $found['dyn'] = array( 'id' => 'tk_dyn_superglobal_call', 'name' => 'Dynamic Call From Request', 'severity' => 'critical' ); } } // (6b) ACG-149-085 (siege 18 #2): by-reference output taint - `preg_match($re,$_SERVER['q'],$m)`, // `parse_str($_SERVER['QUERY_STRING'],$m)` fill $m with request data. Taint the output var so a later // `call_user_func($m[$_GET['k']])` / `system($m[$_GET['k']])` / `include $m[$_GET['k']]` is not judged // a bounded (untainted-base) table by ACG-149-084. $gp_br = $called_fn( $i ); if ( '' !== $gp_br && isset( $gp_byref_fns[ $gp_br ] ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $gp_bin = $gp_byref_fns[ $gp_br ][0]; $gp_bout = $gp_byref_fns[ $gp_br ][1]; $gp_bk = $i + 2; $gp_bd = 1; $gp_bargn = 0; $gp_binreq = false; $gp_boutvar = ''; $gp_bs2 = 0; while ( $gp_bk < $n && $gp_bd > 0 && $gp_bs2++ < 4000 && self::scan_budget_ok() ) { $x = $tok[ $gp_bk ]; if ( $is_char( $x, '(' ) || $is_char( $x, '[' ) ) { $gp_bd++; } elseif ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { $gp_bd--; if ( 0 === $gp_bd ) { break; } } elseif ( 1 === $gp_bd && $is_char( $x, ',' ) ) { $gp_bargn++; } else { if ( $gp_bargn === $gp_bin && ( $is_super( $x ) || $is_fn( $x, $req_read ) || ( is_int( $x[0] ) && T_VARIABLE === $x[0] && isset( $tainted[ $x[1] ] ) ) ) ) { $gp_binreq = true; } // ACG-149-085 (siege 18, self-review): the by-ref target must be a BARE LOCAL variable // ($m, immediately closed by ',' or ')'), NEVER $this or the base of a property/subscript // write ($this->query_vars) - tainting $this cascades to every property and branded WP core's // `parse_str($this->query_string, $this->query_vars)` a CRITICAL tk_extract_superglobal (FP). if ( $gp_bargn === $gp_bout && 1 === $gp_bd && '' === $gp_boutvar && is_int( $x[0] ) && T_VARIABLE === $x[0] && '$this' !== (string) $x[1] && $gp_bk + 1 < $n && ( $is_char( $tok[ $gp_bk + 1 ], ',' ) || $is_char( $tok[ $gp_bk + 1 ], ')' ) ) ) { $gp_boutvar = $x[1]; } } $gp_bk++; } if ( $gp_binreq && '' !== $gp_boutvar ) { $tainted[ $gp_boutvar ] = 1; $gp_taint_pos[ $gp_boutvar ] = $i; } } // (7) ACG-106 fresh-eyes: DIRECT command-execution call whose FIRST (command) argument holds request // data — variable-hop, ANY request superglobal, concatenation, filter_input, or a request stream. // This is the common one-line shell that one variable hop hides from the flat bd_* regexes. Only the // command argument is inspected (a request value in popen()'s 2nd "mode" arg is not a command), so it // stays false-positive-free: no legitimate plugin builds a shell command out of request input. // ACG-145-001: `\system($_POST['c'])` was invisible here and was only caught by the flat // bd_*/ws_* regexes - the very regexes being retired, because they cannot tell a method // call from a global one. This arm is now the single owner of the command-execution axis. $gp_sh = $called_fn( $i ); if ( '' !== $gp_sh && isset( $shell_fns[ $gp_sh ] ) ) { $maxarg = $shell_fns[ $gp_sh ]; // ACG-149-056 (siege 7 finder-J): a FIRST-CLASS CALLABLE of a shell fn - `system(...)($_GET['c'])` // (PHP 8.1) - hands request data to the command through the trailing invocation. The normal arg // scan below sees only `...` inside the fn's OWN parens, so inspect the `(...)( )` that // immediately follows and fire if it carries request data. // ACG-149-064 (siege 8 #6): the invocation '(' need not be at a FIXED offset after the FCC's ')' // ("never match at fixed token offsets"). A trivial wrapper - `[system(...)][0]($_GET)` or // `($o->r=system(...))($_GET)` - inserts a `]`/`)`/subscript between the callable and its call. Skip // a bounded run of grouping/subscript tokens to find the real invocation '('. $gp_iv = -1; if ( $i + 4 < $n && $is_char( $tok[ $i + 1 ], '(' ) && is_int( $tok[ $i + 2 ][0] ) && defined( 'T_ELLIPSIS' ) && T_ELLIPSIS === $tok[ $i + 2 ][0] && $is_char( $tok[ $i + 3 ], ')' ) ) { $gp_iw = $i + 4; $gp_iws = 0; while ( $gp_iw < $n && $gp_iws++ < 12 && ( $is_char( $tok[ $gp_iw ], ']' ) || $is_char( $tok[ $gp_iw ], ')' ) || $is_char( $tok[ $gp_iw ], '[' ) || ( is_int( $tok[ $gp_iw ][0] ) && in_array( $tok[ $gp_iw ][0], array( T_LNUMBER, T_CONSTANT_ENCAPSED_STRING, T_STRING, T_OBJECT_OPERATOR, T_DOUBLE_COLON ), true ) ) ) ) { $gp_iw++; } if ( $gp_iw < $n && $is_char( $tok[ $gp_iw ], '(' ) ) { $gp_iv = $gp_iw; } } if ( $gp_iv >= 0 ) { $gp_fk = $gp_iv + 1; $gp_fd = 1; $gp_fcc_req = false; $gp_fcs = 0; while ( $gp_fk < $n && $gp_fd > 0 && $gp_fcs++ < 4000 && self::scan_budget_ok() ) { $gp_fx = $tok[ $gp_fk ]; if ( $is_char( $gp_fx, '(' ) || $is_char( $gp_fx, '[' ) ) { $gp_fd++; } elseif ( $is_char( $gp_fx, ')' ) || $is_char( $gp_fx, ']' ) ) { $gp_fd--; if ( 0 === $gp_fd ) { break; } } elseif ( ( ( $is_super( $gp_fx ) && ! $gp_srv_path( $gp_fk ) ) || $is_tainted( $gp_fx ) || $is_fn( $gp_fx, $req_read ) || $gp_remote_in( $gp_fk ) ) && ! $gp_super_is_cond( $gp_fk ) ) { $gp_fcc_req = true; } $gp_fk++; } if ( $gp_fcc_req ) { $found['shellexec'] = array( 'id' => 'tk_shell_request', 'name' => 'Shell Command From Request', 'severity' => 'critical' ); } } // ACG-148 (self-review): a command argument is request-controlled if it is a superglobal / // tainted var / request-reader, OR it READS php://input. The read must be a real stream read, // not the literal text "php://input" sitting in a fixed command: an earlier concat scan fired // tk_shell_request on `system("echo php://input")` and `exec("grep php://input /var/www")` — // diagnostic/dev commands with NO request data (second-siege FP). So php://input counts only // INSIDE a $stream_read call's parens, tracked by depth exactly like the upload-sanitizer arm. $k = $i + 2; $d = 1; $argn = 0; $hit = false; $gp_read_depths = array(); while ( $k < $n && $d > 0 && self::scan_budget_ok() ) { $x = $tok[ $k ]; if ( $is_fn( $x, $stream_read ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) ) { $gp_read_depths[] = $d + 1; // depth INSIDE this stream read's parens } // ACG-149-086-fix (siege-22 final review): a numeric CAST/narrower ((int)/(float)/(bool), or // intval/absint/floatval/doubleval/boolval) REPLACES the request bytes with a canonical number - // no shell metacharacter (; | ` $ space newline) can survive - so `exec("tail -n ".(int)$_GET['n'])` // is injection-free. The taint tracker $rhs_src (5819/5830) and the upload arm already neutralise // exactly this set; the shell arm did not, so the INLINE form fired CRITICAL while the temp-var form // ($n=(int)$_GET['n']; exec("...".$n)) was clean - a pure oversight/asymmetry. Skip ONLY the narrowed // operand (bracket-balanced, so $d is unaffected); every OTHER raw request token in the command still // fires (FN-safe: system((int)$_GET['a']." ".$_GET['b']) still hits on $_GET['b']). Reject a // ->/::/\ method shadowing a cast name, exactly as $rhs_src does. if ( ( is_int( $x[0] ) && in_array( $x[0], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) || ( $is_fn( $x, $num_cast_fns ) && $k + 1 < $n && $is_char( $tok[ $k + 1 ], '(' ) && ! ( $k - 1 >= 0 && is_int( $tok[ $k - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $k - 1 ][0] || T_DOUBLE_COLON === $tok[ $k - 1 ][0] || T_NS_SEPARATOR === $tok[ $k - 1 ][0] ) ) ) ) { $k = $skip_numeric( $k ) + 1; continue; } if ( $is_char( $x, '(' ) || $is_char( $x, '[' ) ) { $d++; } elseif ( $is_char( $x, ')' ) || $is_char( $x, ']' ) ) { $d--; while ( ! empty( $gp_read_depths ) && $d < end( $gp_read_depths ) ) { array_pop( $gp_read_depths ); } } elseif ( $is_char( $x, ',' ) && 1 === $d ) { $argn++; if ( $argn > $maxarg ) { break; } } // stop after the command-bearing args elseif ( ( ( $is_super( $x ) && ! $gp_srv_path( $k ) && ! $gp_super_is_fixedkey( $k ) ) || $is_tainted( $x ) || $is_fn( $x, $req_read ) || $gp_remote_in( $k ) ) && ! $gp_super_is_cond( $k ) ) { $hit = true; } // ACG-149-054 + ACG-149-078 (#9) elseif ( ! empty( $gp_read_depths ) && $d >= end( $gp_read_depths ) && is_int( $x[0] ) && T_CONSTANT_ENCAPSED_STRING === $x[0] && false !== strpos( strtolower( $decode( $x[1] ) ), 'php://input' ) ) { $hit = true; } $k++; } if ( $hit ) { $found['shellexec'] = array( 'id' => 'tk_shell_request', 'name' => 'Shell Command From Request', 'severity' => 'critical' ); } } // (7c) ACG-148-004: move_uploaded_file() to an ATTACKER-CONTROLLED DESTINATION. This is the // upload-shell primitive: a visitor posts a .php file and chooses where it lands. A fixed // destination (the normal case - a plugin decides its own upload folder) is NOT reported. // ACG-148-004 (self-review, agent 3): a RAW request value in the destination is the drop; a // SANITISED one is the mainstream import/media idiom and must NOT be called malware. Building // `$dir . sanitize_file_name($_POST['name'])` or `basename($_POST['file'])` cannot escape the // fixed folder, so a request token wrapped in a path-sanitizer no longer counts — only a raw // request value concatenated straight into the path (traversal-capable) does. $gp_mu = $called_fn( $i ); if ( 'move_uploaded_file' === $gp_mu && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $gp_mk = $i + 2; $gp_md = 1; $gp_marg = 0; $gp_mhit = false; $gp_ms = 0; $gp_san_depths = array(); // paren-depths at which a path-sanitizer call is currently open while ( $gp_mk < $n && $gp_md > 0 && $gp_ms++ < 3000 ) { $gp_mx = $tok[ $gp_mk ]; // a sanitizer call is opening: ( — everything inside its parens is neutralised. if ( is_int( $gp_mx[0] ) && ( T_STRING === $gp_mx[0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $gp_mx[0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $gp_mx[0] ) ) // ACG-149-037: \basename is a T_NAME_FULLY_QUALIFIED token && isset( $upload_sanitizers[ ltrim( strtolower( (string) $gp_mx[1] ), '\\' ) ] ) && $gp_mk + 1 < $n && $is_char( $tok[ $gp_mk + 1 ], '(' ) // ACG-149-055 (siege 7 #7): a sanitizer NAME reached through `->`/`::` is a METHOD whose body // the attacker defines - a 1-line no-op `basename()` silences this critical detector while the // destination stays traversal-capable. Only a GLOBAL sanitizer function is positive evidence; // a method-name collision is not. (The safe refactor `$d=$this->clean($_POST); move(...,$d)` // stays exempt because the raw super leaves move()'s own parens.) && ! ( $gp_mk - 1 >= 0 && is_int( $tok[ $gp_mk - 1 ][0] ) && ( T_OBJECT_OPERATOR === $tok[ $gp_mk - 1 ][0] || T_DOUBLE_COLON === $tok[ $gp_mk - 1 ][0] ) ) ) { // ACG-149-023: an OOP sanitiser method is legit $gp_san_depths[] = $gp_md + 1; // the depth INSIDE this sanitizer's parens } if ( $is_char( $gp_mx, '(' ) || $is_char( $gp_mx, '[' ) ) { $gp_md++; } elseif ( $is_char( $gp_mx, ')' ) || $is_char( $gp_mx, ']' ) ) { $gp_md--; while ( ! empty( $gp_san_depths ) && $gp_md < end( $gp_san_depths ) ) { array_pop( $gp_san_depths ); } if ( 0 === $gp_md ) { break; } } elseif ( $is_char( $gp_mx, ',' ) && 1 === $gp_md ) { $gp_marg++; } // argument 1 is the DESTINATION. Fire ONLY on a RAW SUPERGLOBAL placed directly in the // destination (`move_uploaded_file($f, ABSPATH.$_POST['p'])`) — an unsanitisable, // traversal-capable path that is either an upload shell or a real path-traversal bug. // ACG-148-004 (SECOND siege): a TAINTED VARIABLE was DROPPED here. The taint engine does // not model sanitize_file_name()/basename() as clearing, so the ubiquitous, correct idiom // $name = sanitize_file_name($_FILES['f']['name']); $dest = $dir.'/'.$name; // move_uploaded_file($_FILES['f']['tmp_name'], $dest); // left $dest tainted and was branded CRITICAL malware — a business-ending false positive on // ordinary, even correctly-sanitised, upload handlers (two independent reviewers hit it). // "Destination holds a value derived from the request" is undecidable for sanitisation by // tokens, so it is NOT proven malware; the raw-superglobal form above is. A genuinely raw // request path stored in a variable ($d=$_GET['p']; move(...,$d)) is no longer flagged here, // but the .php SHELL it drops is still caught CRITICAL by the uploads-location + content scan. // The inline-sanitiser suppression is retained for the direct super-inside-sanitizer form. elseif ( $gp_marg >= 1 && $is_super( $gp_mx ) && ! $gp_super_is_cond( $gp_mk ) ) { // ACG-149-054: not a mere ternary/comparison condition // ACG-148-004 (THIRD siege): $_SERVER and $_ENV are exempt HERE. They are in $supers // because HTTP_* / QUERY_STRING really are attacker-controlled, but as an upload // DESTINATION the dominant use is the server-set path root — // move_uploaded_file($tmp, $_SERVER['DOCUMENT_ROOT'].'/uploads/'.basename($name)) // is ordinary media/import code, not traversal-capable, and was branded CRITICAL // malware. The rare request-controlled $_SERVER key used AS an upload path is caught // by the content scan of the .php file it drops. $_GET/$_POST/$_REQUEST/$_COOKIE — // the real request channels — still fire. (Exempt only in THIS arm: a $_SERVER value // reaching a COMMAND or an eval remains a genuine backdoor and is unaffected.) $gp_sv = ( is_int( $gp_mx[0] ) && T_VARIABLE === $gp_mx[0] ) ? $gp_mx[1] : ''; $gp_is_exempt = ( '$_FILES' === $gp_sv ); // $_FILES is the upload SOURCE, always exempt // ACG-149-009 / -032 (siege 3 #15): a numeric CAST narrows the value to digits exactly // as intval() does, but has no parens for the sanitiser-depth tracker to see, so it // needs its own check. `(int)$_POST['id']` AND `(int)($_POST['id'])` (a cast over a // GROUP) both apply, so walk back over any grouping '(' before testing for the cast. if ( ! $gp_is_exempt ) { $gp_cst = $gp_mk - 1; $gp_csts = 0; while ( $gp_cst >= 0 && $gp_csts++ < 6 && $is_char( $tok[ $gp_cst ], '(' ) ) { $gp_cst--; } if ( $gp_cst >= 0 && is_int( $tok[ $gp_cst ][0] ) && in_array( $tok[ $gp_cst ][0], array( T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST ), true ) ) { $gp_is_exempt = true; } } // ACG-148-004 (FOURTH siege): $_SERVER / $_ENV carry BOTH server-set filesystem roots // (DOCUMENT_ROOT, ...) AND attacker-controlled values (HTTP_* headers, PATH_INFO, // QUERY_STRING, REQUEST_URI). The third-siege blanket exemption was over-broad — it made // move_uploaded_file($f, $_SERVER['HTTP_X_DEST']) — a real arbitrary-write shell keyed on // a request header — scan clean while the byte-identical $_POST form fired CRITICAL. // Exempt ONLY a LITERAL server-set filesystem key (the legit upload-path idiom); fire on // every request-controlled or non-literal key. if ( ! $gp_is_exempt && ( '$_SERVER' === $gp_sv || '$_ENV' === $gp_sv ) ) { $gp_key = ''; if ( $gp_mk + 2 < $n && $is_char( $tok[ $gp_mk + 1 ], '[' ) && is_int( $tok[ $gp_mk + 2 ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $gp_mk + 2 ][0] ) { $gp_key = strtolower( trim( $tok[ $gp_mk + 2 ][1], "\"'" ) ); } $gp_is_exempt = in_array( $gp_key, array( 'document_root', 'context_document_root', 'script_filename', 'server_root' ), true ); } $gp_is_sanitised = ( ! empty( $gp_san_depths ) && $gp_md >= end( $gp_san_depths ) ); if ( ! $gp_is_exempt && ! $gp_is_sanitised ) { $gp_mhit = true; } } $gp_mk++; } if ( $gp_mhit ) { $found['upload'] = array( 'id' => 'tk_upload_request_dest', 'name' => 'Upload To Request-Controlled Path', 'severity' => 'critical' ); } } // (7d) ACG-148-005: REVERSE SHELL. Three links must all be present in one file: // $s = fsockopen(...) -> $s is a socket handle // $c = fgets($s) -> $c carries REMOTE data // system($c) -> a command run on remote data // Each link alone is ordinary code, which is why this fires only on the conjunction. A // socket read that is merely echoed, or a command with a fixed argument, is not reported. // ACG-148-005 (self-review, adversarial agent 3): socket_accept is included so a BIND shell // (socket_create -> socket_bind -> socket_listen -> $conn = socket_accept($listen) -> read -> // command) is covered: socket_accept always returns a connection SOCKET, so its assignment // target is a handle too. (socket_create is already a gate marker, so a bind shell reaches here.) $gp_rsx = $called_fn( $i ); // ACG-149-039: fopen("tcp://...") / ssl:// / tls:// / udp:// opens a SOCKET, not a file. Treat // it as a handle producer only when a network-transport wrapper literal is in its arguments. $gp_fopen_sock = false; if ( ( 'fopen' === $gp_rsx || 'fsockopen' === $gp_rsx ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { // ACG-149-070 (siege 11 #1/#8/#11): resolve the FIRST argument's full string VALUE with resolve_name, // which folds inline concatenation (`"tc".$x`, `"tc"."p://"`), a nowdoc/heredoc body, a const_str // variable, AND decoder transforms (base64_decode/str_rot13/strrev/gz*/...). The token-by-token walk // below only sees a single contiguous literal or a single const_str var, so any wrapper obfuscated // INSIDE fopen's own argument evaded it even after ACG-149-069 opened the gate. $gp_fres = $resolve_name( $i + 2 ); if ( is_array( $gp_fres ) && isset( $gp_fres[0] ) && preg_match( '#^\s*(?:tcp|ssl|tls|udp)://#i', (string) $gp_fres[0] ) ) { $gp_fopen_sock = true; } // ACG-149-076 (siege 12 #2): resolve_name is all-or-nothing - a split scheme followed by an // UNRESOLVABLE host (`fopen("tc"."p://".$h)`, and C2 hosts are variables/config, not IP literals) // zeroes the whole result even though the tcp:// PREFIX is fully determined by the leading literals. // Fold ONLY the leading literal/const_str concat prefix and test it. if ( ! $gp_fopen_sock ) { $gp_pref = ''; $gp_pj = $i + 2; $gp_pfs = 0; while ( $gp_pj < $n && $gp_pfs++ < 40 && strlen( $gp_pref ) < 12 ) { $gp_px = $tok[ $gp_pj ]; if ( is_int( $gp_px[0] ) && T_CONSTANT_ENCAPSED_STRING === $gp_px[0] ) { $gp_pref .= (string) $decode( $gp_px[1] ); } elseif ( is_int( $gp_px[0] ) && T_VARIABLE === $gp_px[0] && isset( $const_str[ $gp_px[1] ] ) ) { $gp_pref .= (string) $const_str[ $gp_px[1] ][0]; } else { break; } if ( $gp_pj + 1 < $n && $is_char( $tok[ $gp_pj + 1 ], '.' ) ) { $gp_pj += 2; } else { break; } } if ( '' !== $gp_pref && preg_match( '#^\s*(?:tcp|ssl|tls|udp)://#i', $gp_pref ) ) { $gp_fopen_sock = true; } } // ACG-149-079 (siege 13 #2): the IDIOMATIC way to build a socket address is string interpolation - // `fopen("tcp://$ip:$port")`. PHP tokenizes the leading scheme as T_ENCAPSED_AND_WHITESPACE (right // after the opening quote), not T_CONSTANT_ENCAPSED_STRING, so all the literal/const_str layers above // miss it. Honour a scheme that begins the interpolated string. if ( ! $gp_fopen_sock && $i + 3 < $n && $is_char( $tok[ $i + 2 ], '"' ) && is_int( $tok[ $i + 3 ][0] ) && T_ENCAPSED_AND_WHITESPACE === $tok[ $i + 3 ][0] && preg_match( '#^\s*(?:tcp|ssl|tls|udp)://#i', (string) $tok[ $i + 3 ][1] ) ) { $gp_fopen_sock = true; } $gp_fw = $i + 2; $gp_fwd = 1; $gp_fws = 0; if ( $gp_fopen_sock ) { $gp_fwd = 0; } while ( $gp_fw < $n && $gp_fwd > 0 && self::scan_budget_ok() && $gp_fws++ < 40 ) { if ( $is_char( $tok[ $gp_fw ], '(' ) ) { $gp_fwd++; } elseif ( $is_char( $tok[ $gp_fw ], ')' ) ) { $gp_fwd--; if ( 0 === $gp_fwd ) { break; } } elseif ( is_int( $tok[ $gp_fw ][0] ) && T_CONSTANT_ENCAPSED_STRING === $tok[ $gp_fw ][0] && preg_match( '#^[\"\']\\s*(?:tcp|ssl|tls|udp)://#i', (string) $tok[ $gp_fw ][1] ) ) { $gp_fopen_sock = true; break; } // ACG-149-046 (siege 6 #8): the transport wrapper is often held in a string variable - // `$u = "tcp://host:port"; fopen( $u, ... )`. $const_str (built in this same source-order // walk) already carries $u's literal value, so honour it as a socket opener too. elseif ( is_int( $tok[ $gp_fw ][0] ) && T_VARIABLE === $tok[ $gp_fw ][0] && isset( $const_str[ $tok[ $gp_fw ][1] ] ) && preg_match( '#^\s*(?:tcp|ssl|tls|udp)://#i', (string) $const_str[ $tok[ $gp_fw ][1] ][0] ) ) { $gp_fopen_sock = true; break; } // ACG-149-081 (siege 14 #3): the same wrapper var built by INTERPOLATION - its leading literal is in $gp_str_prefix. elseif ( is_int( $tok[ $gp_fw ][0] ) && T_VARIABLE === $tok[ $gp_fw ][0] && isset( $gp_str_prefix[ $tok[ $gp_fw ][1] ] ) && preg_match( '#^\s*(?:tcp|ssl|tls|udp)://#i', (string) $gp_str_prefix[ $tok[ $gp_fw ][1] ] ) ) { $gp_fopen_sock = true; break; } $gp_fw++; } } if ( ( in_array( $gp_rsx, self::socket_ingress_fns(), true ) || $gp_fopen_sock ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { // ACG-149-004: walk back over the TRANSPARENT tokens rather than matching a fixed // offset. PHP's error-suppression '@' survives normalisation as a char token, so // `$s = @fsockopen(...)` - what real droppers write, to keep the warning out of the // response - left `=` at $i-2 and silenced this whole arm. A leading namespace // separator does the same on PHP 7.4, where `\fsockopen` is T_NS_SEPARATOR+T_STRING. $gp_r1 = $i - 1; $gp_r1s = 0; while ( $gp_r1 >= 0 && $gp_r1s++ < 4 && ( $is_char( $tok[ $gp_r1 ], '@' ) || ( is_int( $tok[ $gp_r1 ][0] ) && T_NS_SEPARATOR === $tok[ $gp_r1 ][0] ) ) ) { $gp_r1--; } if ( $gp_r1 >= 1 && $is_char( $tok[ $gp_r1 ], '=' ) && is_int( $tok[ $gp_r1 - 1 ][0] ) && T_VARIABLE === $tok[ $gp_r1 - 1 ][0] ) { $gp_sock_var[ $tok[ $gp_r1 - 1 ][1] ] = 1; } } // link 2: a variable assigned from a read ON A KNOWN SOCKET HANDLE now carries remote bytes. // Keyed on the READ FUNCTION (not on the assigned variable): a plain T_VARIABLE token never // reaches this arm, because an earlier arm in this same loop consumes it and continues. if ( ! empty( $gp_sock_var ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) && in_array( $called_fn( $i ), array( 'fgets', 'fgetss', 'fread', 'stream_get_contents', 'socket_read', 'fgetc', 'stream_get_line', 'socket_recv', 'stream_socket_recvfrom', 'fscanf', 'socket_recvfrom', 'fgetcsv' ), true ) ) { // ACG-149-039 // walk back over any wrapping calls (`$c = trim(fgets($s))`) to the assignment target $gp_rb = $i - 1; $gp_rsteps = 0; $gp_rdst = ''; while ( $gp_rb >= 1 && $gp_rsteps++ < 80 ) { // ACG-149-052: was 14 - deep wrapper nesting hit the cap // ACG-149-004: '@' and a namespace-qualified wrapper name are transparent here. // `$c = @fgets($s)` and `$c = \trim(\fgets($s))` both used to break the walk-back // and leave the socket data unbound, silencing link 3. if ( $is_char( $tok[ $gp_rb ], '(' ) || $is_char( $tok[ $gp_rb ], '@' ) ) { $gp_rb--; continue; } // ACG-149-052 (siege 7 finder-E): a LEADING concat prefix - `$c = "" . fgets($s)` or // `$c = $log . trim(fgets($s))` - must not break the walk. Skip the '.' and any string/number // literal operand before the read; the assignment target is still bound. if ( $is_char( $tok[ $gp_rb ], '.' ) || ( is_int( $tok[ $gp_rb ][0] ) && in_array( $tok[ $gp_rb ][0], array( T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER ), true ) ) ) { $gp_rb--; continue; } // a T_VARIABLE that is the LEFT operand of a concat (`$log . fgets(..)`) is followed by '.', // so it is not the assignment target - skip it too. The real target is followed by '='/'.='. if ( is_int( $tok[ $gp_rb ][0] ) && T_VARIABLE === $tok[ $gp_rb ][0] && $gp_rb + 1 < $n && $is_char( $tok[ $gp_rb + 1 ], '.' ) ) { $gp_rb--; continue; } if ( is_int( $tok[ $gp_rb ][0] ) && ( T_STRING === $tok[ $gp_rb ][0] || T_NS_SEPARATOR === $tok[ $gp_rb ][0] || ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $tok[ $gp_rb ][0] ) || ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $tok[ $gp_rb ][0] ) ) ) { $gp_rb--; continue; } // ACG-149-050 (siege 7 gap #10): a read ACCUMULATED with `.=` (T_CONCAT_EQUAL) or appended // with `$a[] =` also binds the remote bytes. `$buf.=fread($s,1024); system($buf);` and // `$a[]=fgets($s); passthru(implode('',$a));` are textbook read-until-EOF reverse shells that // previously scanned clean because the walk-back accepted only a plain `=`. if ( ( $is_char( $tok[ $gp_rb ], '=' ) || ( is_int( $tok[ $gp_rb ][0] ) && T_CONCAT_EQUAL === $tok[ $gp_rb ][0] ) ) && is_int( $tok[ $gp_rb - 1 ][0] ) && T_VARIABLE === $tok[ $gp_rb - 1 ][0] ) { $gp_rdst = $tok[ $gp_rb - 1 ][1]; } elseif ( $is_char( $tok[ $gp_rb ], '=' ) && $gp_rb - 3 >= 0 && $is_char( $tok[ $gp_rb - 1 ], ']' ) && $is_char( $tok[ $gp_rb - 2 ], '[' ) && is_int( $tok[ $gp_rb - 3 ][0] ) && T_VARIABLE === $tok[ $gp_rb - 3 ][0] ) { $gp_rdst = $tok[ $gp_rb - 3 ][1]; } break; } if ( '' !== $gp_rdst ) { $gp_rk2 = $i + 2; $gp_rd3 = 1; $gp_rs3 = 0; $gp_from_sock = false; while ( $gp_rk2 < $n && $gp_rd3 > 0 && self::scan_budget_ok() ) { if ( $is_char( $tok[ $gp_rk2 ], '(' ) ) { $gp_rd3++; } elseif ( $is_char( $tok[ $gp_rk2 ], ')' ) ) { $gp_rd3--; if ( 0 === $gp_rd3 ) { break; } } elseif ( is_int( $tok[ $gp_rk2 ][0] ) && T_VARIABLE === $tok[ $gp_rk2 ][0] && isset( $gp_sock_var[ $tok[ $gp_rk2 ][1] ] ) ) { $gp_from_sock = true; } $gp_rk2++; } if ( $gp_from_sock ) { $gp_sock_data[ $gp_rdst ] = 1; } } } // ACG-149-035 (siege 4 #5): socket_recv()/fscanf() write attacker bytes into a BY-REFERENCE // out-parameter, not the return value. When a known socket handle is the first argument, mark // the out-param variable(s) as socket data. socket_recv($c, $buf, ...) -> $buf; fscanf($c, // $fmt, $a, $b) -> $a, $b (every variable after the format). if ( ! empty( $gp_sock_var ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $gp_brf = $called_fn( $i ); if ( 'socket_recv' === $gp_brf || 'stream_socket_recvfrom' === $gp_brf || 'socket_recvfrom' === $gp_brf || 'fscanf' === $gp_brf || 'sscanf' === $gp_brf ) { // ACG-149-039: socket_recvfrom $gp_bk = $i + 2; $gp_bd = 1; $gp_barg = 0; $gp_bhandle = false; $gp_bs = 0; $gp_bout_from = ( 'fscanf' === $gp_brf || 'sscanf' === $gp_brf ) ? 2 : 1; // fscanf: vars after the format while ( $gp_bk < $n && $gp_bd > 0 && self::scan_budget_ok() ) { $gp_bx = $tok[ $gp_bk ]; if ( $is_char( $gp_bx, '(' ) || $is_char( $gp_bx, '[' ) ) { $gp_bd++; } elseif ( $is_char( $gp_bx, ')' ) || $is_char( $gp_bx, ']' ) ) { $gp_bd--; if ( 0 === $gp_bd ) { break; } } elseif ( $is_char( $gp_bx, ',' ) && 1 === $gp_bd ) { $gp_barg++; } elseif ( 1 === $gp_bd && is_int( $gp_bx[0] ) && T_VARIABLE === $gp_bx[0] ) { if ( 0 === $gp_barg && isset( $gp_sock_var[ $gp_bx[1] ] ) ) { $gp_bhandle = true; } elseif ( $gp_barg >= $gp_bout_from && $gp_bhandle ) { $gp_sock_data[ $gp_bx[1] ] = 1; } } $gp_bk++; } } } if ( ! empty( $gp_sock_data ) || ! empty( $gp_sock_var ) ) { $gp_rc = $called_fn( $i ); if ( '' !== $gp_rc && isset( $shell_fns[ $gp_rc ] ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { // ACG-149-023: socket data reaching a shell function's args is a reverse shell, // whether or not it is escaped (see the removal of escapeshellarg suppression above). // ACG-149-044 (siege 6 #2): the CANONICAL php-reverse-shell (pentestmonkey) hands the // socket HANDLE itself to proc_open/popen as I/O plumbing (`proc_open("/bin/sh -i", // array(0=>$sock,1=>$sock,2=>$sock), ...)`) - nothing is read in PHP, so $gp_sock_data is // empty. A socket HANDLE reaching proc_open/popen is a reverse shell just the same. $gp_rc_plumb = ( 'proc_open' === $gp_rc || 'popen' === $gp_rc ); $gp_rk3 = $i + 2; $gp_rd4 = 1; $gp_rs4 = 0; while ( $gp_rk3 < $n && $gp_rd4 > 0 && self::scan_budget_ok() ) { $gp_rx2 = $tok[ $gp_rk3 ]; if ( $is_char( $gp_rx2, '(' ) ) { $gp_rd4++; } elseif ( $is_char( $gp_rx2, ')' ) ) { $gp_rd4--; if ( 0 === $gp_rd4 ) { break; } } elseif ( is_int( $gp_rx2[0] ) && T_VARIABLE === $gp_rx2[0] && ( isset( $gp_sock_data[ $gp_rx2[1] ] ) || ( $gp_rc_plumb && isset( $gp_sock_var[ $gp_rx2[1] ] ) ) ) && ! $gp_super_is_cond( $gp_rk3 ) ) { // ACG-149-066 (siege 9 #4): socket byte used ONLY as a condition is not a shell $found['revshell'] = array( 'id' => 'tk_reverse_shell', 'name' => 'Reverse Shell', 'severity' => 'critical' ); } $gp_rk3++; } } } // (7e) ACG-148-006: a ReflectionFunction built from a REQUEST-CONTROLLED NAME. The visitor // picks which PHP function runs; the argument does not have to be request data for that to be // a backdoor (`$_POST['fn']` = 'phpinfo' / 'passthru' / anything). The existing arm required // request data in the INVOCATION too, so `new ReflectionFunction($_POST['fn'])` with a fixed // argument was silent. // ACG-149-012 (review finding #43): the $gp_rfn assignment here was DEAD - never read anywhere, // while calling the name resolver on every single token. The arm below resolves from $e[1]. // ACG-148-006 (self-review, adversarial agent 3): strip a leading namespace backslash before the // name compare. `new \ReflectionFunction($_POST['fn'])` — the IDIOMATIC way to reach the global // class from inside a namespace — tokenizes the name as T_NAME_FULLY_QUALIFIED "\ReflectionFunction", // so strtolower() left "\reflectionfunction" and this whole arm short-circuited before // $class_operand_is_global was ever consulted. One backslash fully evaded a headline rule. // $class_operand_is_global() (below) still owns the real namespace decision. // ACG-149-021 (siege finding #20): mirror the ACG-149-011 fix from arm 4f here. On PHP 7.4 // `new \ReflectionFunction(...)` tokenises as T_NEW + T_NS_SEPARATOR + T_STRING, so the token // before the NAME is the separator, not T_NEW, and an explicit leading '\' means the GLOBAL // class. On PHP 8 the name is one T_NAME_FULLY_QUALIFIED token and $i-1 is already T_NEW, so // the separator branch never fires and $class_operand_is_global still owns the decision. $gp_7e_new = ( $i > 0 && is_int( $tok[ $i - 1 ][0] ) && T_NEW === $tok[ $i - 1 ][0] ); $gp_7e_abs = false; if ( ! $gp_7e_new && $i > 1 && is_int( $tok[ $i - 1 ][0] ) && T_NS_SEPARATOR === $tok[ $i - 1 ][0] && is_int( $tok[ $i - 2 ][0] ) && T_NEW === $tok[ $i - 2 ][0] ) { $gp_7e_new = true; $gp_7e_abs = true; } if ( ( 'reflectionfunction' === ltrim( strtolower( (string) ( is_int( $e[0] ) ? $e[1] : '' ) ), '\\' ) ) && $gp_7e_new && ( $gp_7e_abs || $class_operand_is_global( $i, 'reflectionfunction' ) ) && $i + 1 < $n && $is_char( $tok[ $i + 1 ], '(' ) ) { $gp_qk = $i + 2; $gp_qd = 1; $gp_qreq = false; while ( $gp_qk < $n && $gp_qd > 0 && self::scan_budget_ok() ) { // ACG-149-033: shared budget $gp_qx = $tok[ $gp_qk ]; if ( $is_char( $gp_qx, '(' ) ) { $gp_qd++; } elseif ( $is_char( $gp_qx, ')' ) ) { $gp_qd--; if ( 0 === $gp_qd ) { break; } } elseif ( $is_super( $gp_qx ) || $is_fn( $gp_qx, $req_read ) || $gp_remote_in( $gp_qk ) ) { $gp_qreq = true; } // ACG-149-033: socket bytes too elseif ( is_int( $gp_qx[0] ) && T_VARIABLE === $gp_qx[0] && isset( $tainted[ $gp_qx[1] ] ) && 1 === (int) $tainted[ $gp_qx[1] ] ) { $gp_qreq = true; } $gp_qk++; } if ( $gp_qreq ) { $found['dyn_req'] = array( 'id' => 'tk_dyn_request_callee', 'name' => 'Request-Controlled Dynamic Call', 'severity' => 'critical' ); } } // (8) ACG-106 fresh-eyes: the backtick operator `...` (a shell_exec equivalent with no callable name) // interpolating request data — a complete blind spot before. Flag only when request data is inside // the backticks (a fixed literal backtick command is not flagged here), so it is false-positive-free. if ( $is_char( $e, '`' ) ) { $k = $i + 1; $hit = false; while ( $k < $n && ! $is_char( $tok[ $k ], '`' ) && self::scan_budget_ok() ) { if ( $is_super( $tok[ $k ] ) || $is_tainted( $tok[ $k ] ) || $is_fn( $tok[ $k ], $req_read ) || $gp_remote_in( $k ) ) { $hit = true; } // ACG-149-033: socket bytes too $k++; } if ( $hit ) { $found['btick'] = array( 'id' => 'tk_shell_request', 'name' => 'Shell Command From Request', 'severity' => 'critical' ); } } } return array_values( $found ); } private static function scan_content( $filepath, $signatures, &$result, $content = null ) { // RC-118-04 (audit round 2): when the caller already read the file's bytes (scan_file's // single TOCTOU-safe read), scan THOSE exact bytes instead of re-opening the file — so // the hash, the verdict and the scanned content are provably the same bytes. Callers // that pass no buffer (e.g. the manual single-file viewer) still read here as before. if ( null === $content ) { // ACG-086 sweep (audit 2026-06-28): the no-buffer fallback must never re-read THROUGH a symlink component // or from a non-regular file (FIFO would HANG file_get_contents). Unsafe path → nothing to scan here (it is // a coverage gap already counted upstream). if ( ! self::is_safe_regular_file( $filepath ) ) { return; } $content = @file_get_contents( $filepath ); } if ( $content === false || '' === $content ) return; // ACG-138-R2-02a: the subject for filename-target signatures. Normalised first so a // Windows path yields the basename too (basename() alone does not split on a backslash // under a non-Windows PHP, and the scanner's paths are wp_normalize_path'd elsewhere). $gp_scan_basename = ( '' !== (string) $filepath ) ? basename( wp_normalize_path( (string) $filepath ) ) : ''; // RC-112-01 (audit 2026-06-18): a recognised signature-database / detection-rules // file is NO LONGER fully exempted (that let an attacker pick a /rules/ path + // content to hide a live webshell). It now only DOWNGRADES non-dangerous matches // (see the $is_sig_db rule below, gated on ! $never_downgrade). Dangerous // code-execution signatures always report, wherever they live. $is_sig_db = self::is_signature_database_file( $filepath, $content ); // ═══════════════════════════════════════════════════════════════════ // TWO-PASS SCAN (v8.2 PERF): Quick pre-screen before 11K+ regex // ═══════════════════════════════════════════════════════════════════ // // Pass 1: Check if the file contains ANY suspicious indicator strings // using fast strpos() (~0.1ms per file). If zero indicators are found, // the file CANNOT match any malware signature → skip all regex. // // Pass 2: Full regex matching (only for the ~4% of files with indicators). // // SAFETY: The indicator list is intentionally BROAD. It covers every // category of malware (shells, backdoors, obfuscation, miners, spam, // phishing, etc.). Being too broad just means a clean file gets the // full scan unnecessarily. Being too narrow could miss malware. // // SCALING: With 11K sigs this saves ~25x regex ops. // With 30K sigs the savings grow proportionally. // ═══════════════════════════════════════════════════════════════════ // RC-111-01 (audit 2026-06-18): the indicator pre-screen is a PERF optimisation, // NOT a correctness gate — its hand-maintained list does not cover every active // signature, so it must never short-circuit High/Critical signatures (a backdoor // such as wp_insert_user(...'administrator') carries none of the generic indicator // strings yet MUST still match). Compute it once and, in the signature loop below, // ALWAYS run critical/high signatures while pre-screening only the lower heuristic // tiers, where the optimisation is safe. $has_indicators = self::content_has_indicators( $content ); // ACG-043-001/002 (audit 2026-06-22): request-driven EXECUTION SINKS (dynamic call from a // superglobal, eval/assert of a superglobal or php://input, extract/parse_str of a superglobal) // are now detected with a TOKEN-aware pass (see detect_execution_sinks_tokenized()) rather than a // raw-byte regex/canonicalization. Tokenising binds the match to CODE structure, so (a) the same // text inside a documentation STRING or a comment is NOT flagged (the v1.0.43 canonicalization // produced critical false positives on such strings), and (b) comments, extra parentheses, mixed // quotes and split/joined string literals between code tokens can no longer evade it. if ( ! isset( $result['risk_score'] ) ) { $result['risk_score'] = 0; } $score_map = array( 'critical' => 100, 'high' => 50, 'medium' => 20, 'low' => 5, 'info' => 0, ); // Context checks (v8.0) $security_check = self::is_security_plugin_file( $filepath ); $is_minified_js = self::is_legitimate_base64_file( $filepath ); $has_data_uri = preg_match( '/data:(image|font|audio)[^;]*;base64/i', $content ); // Context check (v8.1) — known legitimate libraries $library_check = self::is_known_library_file( $filepath ); // HARDENING (2026-06-15): bound the per-file signature-scan time so a crafted // file paired with a very large (opt-in threat-feed) signature set cannot stall // the scan. The guard is cheap — a microtime() check only every 1000 signatures. // 10s is far above any legitimate file (oversized files are skipped earlier by // MAX_FILE_SIZE, and most files skip this loop entirely via the two-pass // pre-screen above). On the pathological overrun we record scan_truncated so it // is never silently ignored. $sig_loop_start = microtime( true ); $sig_seen = 0; // PERF-116-02: per-request memo of "does this pattern match the empty string?" // so the validity probe is not re-run for every file in the batch. static $empty_re_cache = array(); // PERF (audit 2026-06-19, SOUND negative prefilter): on a large literal Threat Feed the cost // is the 5000+ PER-SIGNATURE PHP loop iterations, not any single preg_match. So we first ask // ONE cheap question in C: does the file contain ANY of the pure-literal signatures at all? // We build a chunked combined regex of every pure literal (≈20 preg_match calls total) and // run preg_match (presence-only) per chunk. If NOTHING matches, then NO pure literal is // present, so every pure-literal signature can be skipped — turning 5000 iterations into ~20. // • SOUND: we only use the binary "did this chunk match at all?" — never the match LIST — // so the old combined-regex prefix/substring counting bug cannot apply (preg_match // returning 0 is a definitive "no literal here"). // • FAIL OPEN: if a chunk fails to compile/run (e.g. "regex too large"), or any chunk // matches, we set skip=false and run the full per-signature loop — never a false negative. // Disabled → $skip_pure_literals = false → nothing is skipped (the differential oracle). $lit_index = self::scan_multipattern_enabled() ? self::scan_literal_index( $signatures ) : null; $skip_pure_literals = ( $lit_index && ! empty( $lit_index['chunks'] ) ) ? self::scan_no_literals_present( strtolower( $content ), $lit_index['chunks'] ) : false; // When it is PROVEN no pure literal is present, iterate ONLY the (few) non-literal // signatures — this is the real speed-up: it removes the per-signature PHP loop overhead // for the thousands of literal Threat-Feed signatures, not just their preg_match. The // skipped signatures are exactly the pure literals proven absent, so nothing that could // match is dropped (verified by the gate-ON==gate-OFF differential). $loop_sigs = ( $skip_pure_literals && $lit_index ) ? $lit_index['non_literal_sigs'] : $signatures; $gp_pcre_aborted = 0; // ACG-148-008: signatures whose match ABORTED on this file foreach ( $loop_sigs as $sig ) { if ( ( ++$sig_seen % 1000 === 0 ) && ( microtime( true ) - $sig_loop_start > 10.0 ) ) { // RC-112-07 (audit 2026-06-18): a time-truncated scan must NOT be reported // or cached as clean. Surface a coverage finding, veto the verdict cache, // and bump the risk so the file is recorded for manual review. self::add_coverage_notice( $result, __( 'This file was too large or complex to finish scanning within the time budget, so it was only partially checked for malware.', 'ai-cyberguard' ) ); break; } $pattern = $sig['pattern'] ?? ''; if ( '' === $pattern ) continue; // ACG-138-R2-02a: pick the subject this signature is actually about. $sig_on_filename = self::sig_matches_filename( $sig ); if ( $sig_on_filename && '' === $gp_scan_basename ) { // The name is not known (content-only invocation), so a rule about the name // cannot be evaluated. Skipping is "inapplicable", NOT "clean": every content // signature still runs, and every caller of scan_content() in this plugin passes // a real path, so this is unreachable in the shipped scan paths. continue; } // PERF-116-02 (perf audit 2026-06-18): apply the cheap severity/indicator // gate BEFORE touching the regex. On an indicator-free file the lower-tier // heuristics are skipped without paying any preg_match compile/match cost // (the audit measured ~40x on such files). This changes NOTHING about which // signatures can produce a finding — a signature skipped here was already // skipped (just one step later) before. // RC-111-01: always run critical/high signatures; pre-screen the rest. // RC-118-03 (audit 2026-06-18): only a built-in PREFILTER-SAFE signature may be // skipped on an indicator-free file. Bundled-DB and remote-Feed signatures lack // the 'prefilter' flag and therefore ALWAYS run — a precise Medium/Low feed sig // can match content that holds none of the manual indicator tokens, so gating it // would be a false negative. // ACG-138-R2-02a: $has_indicators is a property of the CONTENT, so it may not gate a // signature whose subject is the NAME (same false-negative shape as the literal index). $sev_pre = strtolower( $sig['severity'] ?? 'high' ); if ( ! $sig_on_filename && ! $has_indicators && 'critical' !== $sev_pre && 'high' !== $sev_pre && ! empty( $sig['prefilter'] ) ) { continue; // built-in prefilter-safe lower-tier heuristic on an indicator-free file — safe to skip (perf) } // PERF-119-01 REMOVED (RC-120-01 / PERF-120-01, audit 2026-06-19): the pure-literal // anchor prefilter was UNSOUND for Unicode patterns — strtolower() folds ASCII only, // but PCRE in /iu mode uses Unicode case-folding, so the anchor could be absent while // preg_match() still matched (false negatives on /ÄBCD/iu, /KILO/iu, /ΣΙΓΜΑ/iu …). It // was also a net performance LOSS: 0 of 132 local signatures qualified, and on the // large opt-in Threat Feed it added a full strpos() pass per literal signature // (measured 1.6×–5.1× slower). Removed entirely — correctness over a non-benefit. // A future multi-pattern engine (Aho-Corasick/trie) can reintroduce this safely under // a feature flag with a differential oracle. // Validity guard: a pattern that matches the empty string would match EVERY // file (usually a malformed remote-feed signature) — skip it. PERF-116-02: // the match-empty test is memoised per distinct pattern for this request, so // it is computed once instead of once per file. if ( ! isset( $empty_re_cache[ $pattern ] ) ) { $empty_re_cache[ $pattern ] = ( @preg_match( $pattern, '' ) === 1 ); } if ( $empty_re_cache[ $pattern ] ) continue; // ACG-138-R2-02a: match the subject the signature is about — the file's name for a // filename-target rule, its bytes for everything else (the default, so unchanged). // ACG-148-008: FALSE is not 0. FALSE means the match ABORTED (backtrack / JIT stack / // recursion limit) - the signature never got to decide - and folding it into "no match" // reports the file clean for a rule that never ran. The limits depend on the SUBJECT, so a // crafted file can silence a chosen signature on every future scan. Record it instead. $gp_re_r = @preg_match( $pattern, $sig_on_filename ? $gp_scan_basename : $content, $matches ); if ( false === $gp_re_r ) { // ACG-148-008 (self-review, adversarial agent 4): only a genuine RUNTIME-LIMIT abort — the // engine ran out of backtrack / recursion / JIT stack budget on THIS subject and gave up — // means "the signature never got to decide", which is the attacker-reachable false negative // we must surface. The earlier check ("anything except PREG_NO_ERROR") was wrong on two // counts: a pattern that FAILS TO COMPILE sets PREG_INTERNAL_ERROR (not PREG_NO_ERROR, as a // stale comment claimed), and a valid /u pattern hitting invalid UTF-8 bytes sets // PREG_BAD_UTF8_ERROR — both are properties of the RULE or the ENCODING, not an incomplete // scan, and would stamp a bogus "partially scanned" notice on ordinary files. Enumerate the // runtime-limit codes explicitly (guarded by defined() for old PHP without the JIT constant). $gp_re_err = function_exists( 'preg_last_error' ) ? preg_last_error() : 0; $gp_limit_hit = ( PREG_BACKTRACK_LIMIT_ERROR === $gp_re_err ) || ( PREG_RECURSION_LIMIT_ERROR === $gp_re_err ) || ( defined( 'PREG_JIT_STACKLIMIT_ERROR' ) && PREG_JIT_STACKLIMIT_ERROR === $gp_re_err ); if ( $gp_limit_hit ) { $gp_pcre_aborted++; } } $sig_hit = ( 1 === $gp_re_r ); if ( $sig_hit ) { $original_sev = strtolower( $sig['severity'] ?? 'high' ); $adjusted_sev = $original_sev; $context_note = ''; $sig_id = $sig['id'] ?? ''; // FIX (audit 2026-06-10): SECURITY — some signatures must NEVER be // downgraded to a harmless severity by attacker-controllable // context (folder name, file content). This flag gates the // library-context rules below for genuine code-execution / // webshell / backdoor signatures. $never_downgrade = self::is_dangerous_signature( $sig_id, $sig ); // Context-aware severity adjustment (v8.0) $is_base64_sig = ( strpos( $sig_id, 'b64' ) !== false || strpos( $sig_id, 'base64' ) !== false || strpos( $sig_id, 'long_b64' ) !== false ); // Detect malware-NAME patterns. RC-116-01: an EXPLICIT per-signature // is_malware_name is authoritative — an id prefix like "wpvcd" must NOT // override a signature that declares is_malware_name=false (e.g. wpvcd_2, // an ACTIVE @include sink that merely shares the wpvcd prefix). The id-prefix // heuristic applies ONLY to signatures that don't declare the field. if ( array_key_exists( 'is_malware_name', $sig ) ) { $is_malware_name = (bool) $sig['is_malware_name']; } else { $is_malware_name = false; foreach ( array( 'ws_', 'wpvcd', 'miner_', 'mailer_' ) as $prefix ) { if ( strpos( $sig_id, $prefix ) === 0 ) { $is_malware_name = true; break; } } } // RC-112-02 (audit 2026-06-18): Rules 1-3 must NEVER downgrade a dangerous // (never_downgrade) code-execution signature. Attacker-controllable context // — folder name, file name like rules.php/patterns.php, or signature-DB // recognition — must not be able to silence a live webshell. Rule 4/5 already // honour this; Rules 1-3 and the new sig-DB rule now do too. // Rule 1: Base64 in minified JS or with data URI = likely fonts/images if ( ! $never_downgrade && $is_base64_sig && ( $is_minified_js || $has_data_uri ) ) { $adjusted_sev = 'info'; $context_note = 'Base64 in minified JS or data URI - likely embedded fonts/images (safe)'; } // Rule 2: Malware name in security plugin folder = detection signature if ( ! $never_downgrade && $is_malware_name && $security_check['is_security'] ) { $adjusted_sev = 'info'; $context_note = 'Malware name found in security plugin "' . $security_check['plugin_name'] . '" - this is a DETECTION RULE, not actual malware'; } // Rule 3: Any pattern in security plugin rules file if ( ! $never_downgrade && $security_check['is_security'] && preg_match( '/(rules|signatures|patterns|config-transient)\.php$/i', $filepath ) ) { $adjusted_sev = 'info'; $context_note = 'Pattern found in security plugin configuration/rules file - this is normal'; } // RC-112-01: signature-database / detection-rules file — downgrade detection // DATA only, never a dangerous live signature. if ( ! $never_downgrade && $is_sig_db ) { $adjusted_sev = 'info'; $context_note = 'Pattern appears inside a recognised signature-database / detection-rules file — treated as detection data, not live malware'; } // Rule 4 (v8.1): Known legitimate library — signature is safe in this context // Covers: TCPDF/FPDF chr(), PHPExcel format strings, CA bundle base64, // ad-inserter eval(), VC Addons presets, mailer libraries if ( ! $never_downgrade && $library_check['is_library'] && in_array( $sig_id, $library_check['safe_sigs'], true ) ) { $adjusted_sev = 'info'; $context_note = sprintf( 'Pattern "%s" found in known library "%s" (%s) — this is normal behavior for this library', $sig['name'] ?? $sig_id, $library_check['name'], $library_check['category'] ); } // Rule 5 (v8.1): "Hacked By" text in non-PHP-output context // PHPExcel format parsers, translation files, and documentation contain this string if ( $sig_id === 'deface_hacked' && $library_check['is_library'] ) { $adjusted_sev = 'info'; $context_note = sprintf( '"Hacked By" text found in library "%s" — this is a format string or documentation, not a defacement', $library_check['name'] ); } // Rule 6 (v8.1): chr() concatenation in files that legitimately generate binary output // PDF libraries MUST use chr() to construct PDF binary streams if ( $sig_id === 'obf_chr_concat' && $library_check['is_library'] && $library_check['category'] === 'pdf' ) { $adjusted_sev = 'info'; $context_note = 'chr() concatenation in PDF library — required for PDF binary stream generation (safe)'; } // Rule 7 (v8.1): chr() in PDF export wrapper files (outside library folder) // Covers files like class-wpcc-entries-export.php that USE PDF libraries // SECURITY: Requires 3+ strong indicators to prevent bypass via simple comment injection if ( $sig_id === 'obf_chr_concat' && $adjusted_sev !== 'info' ) { $pdf_strong_indicators = 0; // Class inheritance — very hard to fake without actual PDF code if ( preg_match( '/\b(extends|new)\s+(T?FPDF|TCPDF|MPDF|Dompdf)\b/i', $content ) ) $pdf_strong_indicators += 2; // PDF method calls — require actual method chaining if ( preg_match( '/\->\s*(AddPage|SetFont|Cell|MultiCell|Output|SetAutoPageBreak)\s*\(/i', $content ) ) $pdf_strong_indicators++; // PDF header signature in output if ( strpos( $content, '%PDF-' ) !== false ) $pdf_strong_indicators++; // Require/include of a known PDF library file if ( preg_match( '/(?:require|include)(?:_once)?\s*\(.*(?:fpdf|tfpdf|tcpdf)(?:\.php|\/)/', $content ) ) $pdf_strong_indicators++; // Need 3+ points to be confident this is a real PDF file, not spoofed if ( $pdf_strong_indicators >= 3 ) { $adjusted_sev = 'info'; $context_note = 'chr() concatenation in file that extends/uses a PDF library — normal for PDF generation'; } } // Rule 8 (v8.1): UTF-8 BOM — chr(239).chr(187).chr(191) // Extremely common in CSV/Excel export files to ensure correct encoding. // SECURITY: Only downgrade if the BOM pattern is the ONLY chr() chain in the file. // If there are additional chr() concatenations beyond the BOM, keep severity // (attacker could hide obfuscated code alongside a legitimate BOM). if ( $sig_id === 'obf_chr_concat' && $adjusted_sev !== 'info' ) { $has_bom = preg_match( '/chr\s*\(\s*239\s*\)\s*\.\s*chr\s*\(\s*187\s*\)\s*\.\s*chr\s*\(\s*191\s*\)/i', $content ); if ( $has_bom ) { // Count ALL chr().chr() chains in the file $all_chr_chains = preg_match_all( '/chr\s*\(\s*\d+\s*\)\s*\.\s*chr\s*\(\s*\d+\s*\)\s*\.\s*chr\s*\(\s*\d+\s*\)/i', $content ); // If the BOM is the only chr() chain → safe (CSV/Excel export) // If there are more chains → keep severity (could be obfuscation + BOM cover) if ( $all_chr_chains <= 1 ) { $adjusted_sev = 'info'; $context_note = 'chr(239).chr(187).chr(191) is a standard UTF-8 BOM (Byte Order Mark) used in CSV/Excel exports — safe'; } } } // Rule 9 (v8.2): URLhaus / malicious URL signatures in known library files // Domains like archive.org, gitlab.com etc. are legitimate but sometimes // abused by attackers. When a URL with such a domain appears inside a // recognized library (phpseclib, ad-inserter-pro, etc.) within plugins/ // or themes/, it is overwhelmingly a false positive — the library simply // references that domain for its normal functionality (e.g. CRL/OCSP // endpoints in X509.php, update-checker URLs pointing to GitLab). // SECURITY: The is_known_library_file() gate already limits this to // plugins/ and themes/ directories. Files in uploads/ or site root // are NOT affected and will still trigger normally. // // Detection: Threat Feed API returns signatures with name like // "URLhaus: archive.org" — these may have empty id or non-standard // category, so we match on THREE conditions: // 1. sig_id starts with 'uh_' (hardcoded URLhaus patterns) // 2. category is 'malicious_url' (any URL-check signature) // 3. name contains 'URLhaus' (Threat Feed API signatures) $sig_name_lower = strtolower( $sig['name'] ?? '' ); $is_urlhaus_sig = ( strpos( $sig_id, 'uh_' ) === 0 ); $is_malicious_url_cat = ( ( $sig['category'] ?? '' ) === 'malicious_url' ); $is_urlhaus_name = ( strpos( $sig_name_lower, 'urlhaus' ) !== false ); if ( ! $never_downgrade && ( $is_urlhaus_sig || $is_malicious_url_cat || $is_urlhaus_name ) && $library_check['is_library'] && $adjusted_sev !== 'info' ) { // FIX (audit 2026-06-10): downgrade to 'low', NOT 'info'. The // previous 'info' fully hid EVERY malicious_url match inside any // plugins/themes folder (a folder name the attacker controls), // so a real C2 URL dropped into plugins/x/vendor/ vanished from // results. 'low' keeps it de-prioritised but still visible in // the per-file detail for review. $adjusted_sev = 'low'; $context_note = sprintf( 'URL pattern "%s" found in known library "%s" (%s) inside plugins/themes — likely a legitimate library reference; de-prioritised but kept visible for review', $sig['name'] ?? $sig_id, $library_check['name'], $library_check['category'] ); } // Rule 9b (FP-TUNING 2026-06-30): suppress URLhaus / malicious_url matches on // GLOBALLY-REPUTABLE reference domains (gitlab.com, archive.org, bitbucket.org, // github.com, package registries, php.net, …). The remote Threat-Feed ships some // "URLhaus: " signatures that are effectively a BARE-DOMAIN regex; URLhaus // actually lists malicious URLs, not these domains, so a library merely referencing // the domain (phpseclib X509, the Elsts update-checker's BitBucketApi/GitLabApi) is a // false positive that Rule 9 only softened to 'low' inside recognised library paths. // We parse the matched text's HOST (true-host check, not a substring) and suppress // to 'info' when it is one of these reputable domains — regardless of folder, so // vendored copies under unrecognised paths and mu-plugins are covered too. A // PATH-BEARING malicious URL on one of these domains has a different matched host and // is not suppressed; an execution-sink/webshell is never_downgrade and unaffected. if ( ! $never_downgrade && ( $is_urlhaus_sig || $is_malicious_url_cat || $is_urlhaus_name ) && 'info' !== $adjusted_sev && isset( $matches[0] ) && self::is_reputable_reference_host( $matches[0] ) ) { $adjusted_sev = 'info'; $context_note = 'Reference to a globally-reputable domain (e.g. github.com / gitlab.com / archive.org) — URLhaus lists specific malicious URLs, not these domains; treated as a legitimate library reference, not a threat'; } // Rule 10 (FP-TUNING 2026-06-30): low-confidence INFORMATIONAL smells that are not // malware on their own. phpinfo() disclosure (info_phpinfo) is a hardening note, not // a threat — cap to 'info' so it leaves the threat count. The generic request-mailer // heuristic (mailer_generic) fires on legitimate contact-form / mailer code — cap to // 'low'. The DANGEROUS corroborated forms are SEPARATE never_downgrade signatures and // are untouched: the named spam-mailer FAMILIES (leafmailer / kingmailer / alfa // mailer) keep their 'critical', and request->exec/include sinks keep theirs. Gated by // never_downgrade so it can never soften an active sink, and never raises a severity. if ( ! $never_downgrade && 'info' !== $adjusted_sev ) { $smell_caps = array( 'info_phpinfo' => 'info', 'mailer_generic' => 'low' ); if ( isset( $smell_caps[ $sig_id ] ) ) { $cap = $smell_caps[ $sig_id ]; if ( ( $score_map[ $cap ] ?? 0 ) < ( $score_map[ $adjusted_sev ] ?? 0 ) ) { $adjusted_sev = $cap; if ( '' === $context_note ) { $context_note = ( 'info' === $cap ) ? 'Informational disclosure pattern (e.g. phpinfo()) — not malware on its own; shown for awareness only' : 'Low-confidence generic pattern — commonly legitimate (e.g. a contact/mailer form); de-prioritised but kept visible for review'; } } } } $finding = array( 'type' => 'signature', 'severity' => $adjusted_sev, 'original_severity' => $original_sev, 'name' => $sig['name'] ?? 'Suspicious', 'description' => 'Matches pattern: ' . $sig_id ); self::add_finding_explanation( $finding, $filepath, $context_note ); $result['findings'][] = $finding; $result['risk_score'] += $score_map[ $adjusted_sev ] ?? 10; } } // ACG-148-008: at least one signature's match ABORTED on this file, so the file was NOT // fully checked. Same disposition as a time-truncated scan: say so, do not cache the verdict, // and floor the risk so a file whose only finding is this notice is still surfaced. // ($gp_pcre_aborted is a LOCAL set by the signature loop above, so it is correct here.) if ( $gp_pcre_aborted > 0 ) { self::add_coverage_notice( $result, __( 'Some malware checks could not finish on this file, so it was only partially checked. A file can be built deliberately to cause this.', 'ai-cyberguard' ) ); } // ACG-043-001/002 (audit 2026-06-22): token-aware execution-sink detection. Bound to CODE // structure (not string-literal or comment text), so it catches comment/whitespace/parenthesis/ // concat/mixed-quote/join evasions of request-driven backdoors WITHOUT the false positives a flat // regex produces on documentation strings. These are high-confidence sinks recorded directly. // // ACG-148-009 (self-review, adversarial agents 2 & 4): this ONE call is the sole place that sets // self::$tokenizer_skipped for THIS file (it resets the flag at its top, then sets it true iff the // content exceeds the memory budget). The coverage check MUST therefore read the flag AFTER this // call — an earlier version emitted it BEFORE, so every file saw the PREVIOUS file's value: a // padded webshell scanned clean + cacheable while the next innocent file was falsely flagged // "partially scanned". A scan_content-only test (no pre-call) is the one that exposes this; // probe-mem masked it by echoing the tokenizer result first. $gp_sinks = self::detect_execution_sinks_tokenized( $content ); // ACG-148-009 (SIXTH siege): the coverage notice now reuses the GATE's decision precisely instead of a // divergent copy of it. self::$tokenizer_skipped is set ONLY when the tokenizer GATE had already opened // (an ingress marker is present) AND the file exceeded the memory budget — so a skipped file always // DID contain a channel the tokenizer would have analysed. The one thing to filter out is the gate's // substring FALSE MATCHES on ordinary English ('require' in "required", 'include' in "includes", // 'eval' in "evaluate"): those must stay silent. Every earlier attempt kept a SEPARATE marker LIST // (content_has_indicators + extras) which repeatedly DIVERGED from the gate — the 4th siege lost // filter_input/getallheaders, the 6th lost bare include/require (a padded `include("wp-"."feed.php")` // WP-VCD loader went completely silent, a regression from v147). One anchored regex, derived from the // gate's own channel list, ends the divergence. SEVENTH siege: two refinements. // (i) Only channels that can produce a tokenizer finding with NO request-superglobal / no signature // companion need to be here. eval/assert/extract/parse_str/call_user_func were REMOVED: their // real request forms always carry a $_ / php://input marker (caught by the $_ branch), and a // self-contained obfuscated eval(gzinflate(base64_decode(..))) is caught by a never_downgrade // SIGNATURE, which runs on the full bytes and is never budget-skipped. Removing them also kills // a real usability FP — the ubiquitous `extract($args)` theme idiom no longer false-nags. // What remains has NO such companion: include/require (the WP-VCD `'wp-'.'feed.php'` loader is a // fixed literal name), the socket family (reverse/bind shells — the ingress is the socket), and // the request-reader functions (filter_input/getallheaders — the ingress is the call itself). // (ii) Each keyword is matched with a NEGATIVE-LOOKAHEAD on a word char, not an adjacent delimiter, // so a COMMENT between the keyword and its target — `include/*x*/("wp-"."feed.php")`, // `fsockopen/*x*/(..)` — which the tokenizer normalises away and catches, no longer slips past // as if it were the word "included". It still rejects "included"/"includes"/"required" (a word // char follows). (include/require can still nag on the rare large file that uses the ENGLISH // verb "include"/"require" in prose — accepted fail-visible, same class as the $_SERVER note.) // A PCRE abort (backtrack) counts as "matched" so a pathological file still fails visible. static $gp_ingress_re = null; if ( null === $gp_ingress_re ) { $gp_ingress_re = '/\$_(?:GET|POST|REQUEST|COOKIE|SERVER|FILES|ENV)\b' // request superglobals in $supers ($_SESSION is NOT a taint source) . '|\$GLOBALS|\$\{' // $GLOBALS + ${"_POST"} / ${$x} variable-variable / alias form . '|php:\/\/input' // request body stream . '|\b(?:filter_input|filter_input_array|getallheaders|apache_request_headers)(?![a-z0-9_])' // request readers (own ingress, no $_ companion) . '|\b(?:' . implode( '|', self::socket_ingress_fns() ) . ')(?![a-z0-9_])' // sockets (reverse/bind shells) - ACG-149-001: same source as the gate, cannot drift . '|(?:tcp|ssl|tls|udp):\/\/' // ACG-149-042 (siege 6 #1/#4/#5): the raw-socket stream wrappers MUST mirror the gate markers added in ACG-149-039, or a memory-skipped fopen("tcp://...") reverse shell goes silent // ACG-148-009 (EIGHTH siege): eval/assert are BACK (the 7th-siege removal was wrong for them). // The eval arm REASSEMBLES a split literal, so `eval(file_get_contents("php:"."//input"))` — a // working POST-body eval with NO $_ marker and NO CONTIGUOUS 'php://input' for the regex — is // caught SMALL but is tokenizer-ONLY (no signature backs it), so a budget-skipped padded copy // went silent. Word-bounded, so "evaluate"/"assertion" are still ignored. (extract/parse_str/ // call_user_func stay OUT: their split forms are NOT detected even small, so they add no // coverage — only the `extract($args)` theme-idiom nag, which staying out avoids.) . '|\b(?:eval|assert)(?![a-z0-9_])' . '|\b(?:include|require)(?:_once)?(?![a-z0-9_])' // real include/require STATEMENT — not "included"/"required"/"includes" . '/i'; } // ACG-149-017: a file whose per-file analysis budget was exhausted (padded to resist the // tokenizer) must fail VISIBLE, exactly like a memory-skipped file. Without this a backdoor // placed after cheap decoy work scanned as a confident clean verdict. if ( self::$analysis_truncated ) { self::add_coverage_notice( $result, __( 'This file could not be fully analysed - it was large or complex enough to exhaust the scan budget, so it was only partially checked. This can happen with large legitimate files; it is also a technique used to hide malicious code.', 'ai-cyberguard' ) ); } if ( self::$tokenizer_skipped && 0 !== @preg_match( $gp_ingress_re, $content ) ) { // 1 (match) or false (abort) both fire; only a clean 0 stays silent self::add_coverage_notice( $result, __( 'This file was too large to run the deep code analysis on with the memory available, so it was only partially checked. This can happen with large legitimate files; it is also a technique used to hide malicious code.', 'ai-cyberguard' ) ); } foreach ( $gp_sinks as $sink ) { $sid = $sink['id']; $sev = $sink['severity']; $note = ''; // FP-TUNING (2026-06-30): the tokenized heuristic request-data sinks are STRUCTURAL // smells, not confirmed backdoors. Reserve CRITICAL for confirmed execution sinks: // a heuristic "dynamic call touching request data" with no proven dangerous callable // does NOT warrant the "Immediate action" CRITICAL badge — record it HIGH. A genuine // request-driven shell (an exec/eval/system/include of request input, or a // request-named dynamic call) is caught INDEPENDENTLY by the never_downgrade // get_signatures() patterns at CRITICAL, so no real-backdoor severity is lost. // (Proven by the gate-ON==gate-OFF differential.) Without this, a ubiquitous reputable // library (guzzlehttp/psr7 ServerRequest, which legitimately threads server/cookie // superglobals through a constructor) tripped a site-wide "Critical: N — Immediate // action required" badge on a clean site. if ( 'tk_dyn_superglobal_call' === $sid && 'critical' === $sev ) { $sev = 'high'; } // Inside a recognised legitimate library (composer vendor//

, guzzle, symfony, // paragonie, phpseclib, freemius, …) these heuristics fire on normal request-handling // plumbing. Downgrade to 'low' — kept VISIBLE for review, never hidden — mirroring // Rule 4/9 above. The real execution-sink signatures (recorded by the loop above) are // gated by never_downgrade, so a backdoor pasted into a vendor folder still reports. if ( $library_check['is_library'] && in_array( $sid, $library_check['safe_sigs'], true ) ) { $sev = 'low'; $note = sprintf( 'Pattern "%s" found in known library "%s" (%s) — normal request handling for this library; de-prioritised but kept visible for review', $sink['name'], $library_check['name'], $library_check['category'] ); } $finding = array( 'type' => 'signature', 'severity' => $sev, 'original_severity' => $sink['severity'], 'name' => $sink['name'], 'description' => 'Matches pattern: ' . $sid, ); self::add_finding_explanation( $finding, $filepath, $note ); $result['findings'][] = $finding; $result['risk_score'] += $score_map[ $sev ] ?? 10; } } private static function is_signature_database_file( $filepath, $content ) { // FIX H-5 (audit 2026-05-25): PHP string '\\\\' is the literal '\\' (two // backslashes), but Windows paths use SINGLE backslashes. The bug caused // legitimate signature-DB files under wp-content\plugins\wordfence\... to // be misclassified as suspicious on Windows hosts, generating // false-positive scan results. Every other site in this class uses '\\' // (single literal backslash) — see lines 96, 109, 363. $path = strtolower( str_replace( '\\', '/', $filepath ) ); $sig_patterns = array( '/wordfence/', '/sucuri/', '/ithemes-security/', '/malcare/', '/signatures/', '/rules/', '/patterns/', '/ai-cyberguard', '/guardpress', ); $in_sig_path = false; foreach ( $sig_patterns as $pattern ) { if ( strpos( $path, $pattern ) !== false ) { $in_sig_path = true; break; } } if ( ! $in_sig_path ) { return false; } $sig_indicators = 0; if ( strpos( $content, 'signature' ) !== false ) $sig_indicators++; if ( strpos( $content, 'pattern' ) !== false ) $sig_indicators++; if ( strpos( $content, 'rule ' ) !== false ) $sig_indicators++; if ( strpos( $content, 'yara' ) !== false ) $sig_indicators++; if ( preg_match( '/\$signatures\s*=\s*array/', $content ) ) $sig_indicators++; return $sig_indicators >= 2; } /** * FIX (audit 2026-06-10): privacy consent gate for third-party threat- * intelligence lookups (MalwareBazaar / URLhaus at abuse.ch). These send file * hashes / URLs off-site, so they only run when the user has opted into * external threat intelligence via the Threat Feed toggle. * Honours the readme promise that external connections are off by default. * * FIX (audit follow-up Finding A): gated ONLY by the Threat Feed opt-in, NOT by * AI. The AI consent text promises file content is sent only on a manual * "Analyze" click, so enabling AI must not silently turn on abuse.ch reputation * checks during scans. abuse.ch reputation belongs to the Threat Feed consent, * whose UI now discloses it. * * @return bool */ public static function external_intel_allowed() { return (bool) get_option( 'guardpress_threat_feed_enabled', false ); } private static function confirm_with_malwarebazaar( $filepath, &$result ) { if ( empty( $result['findings'] ) ) { return; } // FIX (audit 2026-06-10): do not POST file hashes to abuse.ch unless the // user opted into external threat intelligence. if ( ! self::external_intel_allowed() ) { return; } $has_high_critical = false; foreach ( $result['findings'] as $f ) { $sev = strtolower( $f['severity'] ?? '' ); if ( $sev === 'critical' || $sev === 'high' ) { $has_high_critical = true; break; } } if ( ! $has_high_critical ) { return; } if ( ! class_exists( 'GuardPress_MalwareBazaar' ) ) { return; } if ( GuardPress_MalwareBazaar::is_budget_exhausted() ) { return; } $bazaar_result = GuardPress_MalwareBazaar::check_file( $filepath ); if ( $bazaar_result && ! empty( $bazaar_result['is_known'] ) ) { array_unshift( $result['findings'], array( 'type' => 'malwarebazaar', 'severity' => 'critical', 'name' => '🔴 Confirmed Malware: ' . ( $bazaar_result['malware_name'] ?? 'Unknown' ), 'description' => sprintf( 'This file is confirmed malware in the MalwareBazaar database. Detected by %d antivirus engines.', $bazaar_result['av_detections'] ?? 0 ), 'confirmed' => true, 'source' => 'MalwareBazaar', )); $result['risk_score'] = 100; $result['malwarebazaar_confirmed'] = true; } } private static function is_legitimate_upload_php( $filepath ) { $filename = basename( $filepath ); if ( strtolower( $filename ) !== 'index.php' ) { return array( 'is_legitimate' => false, 'reason' => '' ); } // ACG-086 sweep (audit 2026-06-28): never read THROUGH a symlink component or from a non-regular file (FIFO // would HANG) to WHITELIST an uploads index.php. An unsafe path is NOT legitimate (never suppress the finding). if ( ! self::is_safe_regular_file( $filepath ) ) { return array( 'is_legitimate' => false, 'reason' => '' ); } $content = @file_get_contents( $filepath ); if ( $content === false ) { return array( 'is_legitimate' => false, 'reason' => '' ); } // RC-112-03 (audit 2026-06-18): EXACT-canonical trust only. The previous logic // trusted index.php whenever the phrase "silence is golden" appeared ANYWHERE // (strpos) or whenever the file merely STARTED with "', '', '', ); if ( in_array( $normalized, $canonical, true ) ) { return array( 'is_legitimate' => true, 'reason' => 'Standard WordPress directory-protection index.php (canonical stub) - prevents directory listing' ); } return array( 'is_legitimate' => false, 'reason' => '' ); } // ==================== SUMMARY ==================== private static function generate_summary( $findings, $verified, $core_integrity = array(), $discovery_skipped = 0, $scan_skipped = 0 ) { $s = array( 'total_threats' => 0, 'critical' => 0, 'high' => 0, 'medium' => 0, 'low' => 0, 'info' => 0, 'files_infected' => 0, 'verified_clean' => $verified, 'core_verified' => $core_integrity['verified'] ?? 0, 'core_modified' => count( $core_integrity['modified'] ?? array() ), // RC-112-04 review: count only real threats (critical/high/medium); low-severity // coverage notices (oversize-config / chain-scan-limit) must not inflate the // "unknown files" tally shown to the user. 'core_unknown' => count( array_filter( (array) ( $core_integrity['unknown'] ?? array() ), static function ( $u ) { $sev = is_array( $u ) ? strtolower( (string) ( $u['severity'] ?? 'high' ) ) : 'high'; return ( 'critical' === $sev || 'high' === $sev || 'medium' === $sev ); } ) ), // RC-114-05 (audit 2026-06-18): coverage verdict is SEPARATE from the threat // verdict. "No signature matched" is NOT the same as "the scan was complete". // coverage_warnings counts every place the scan could not fully inspect // something (oversized/skipped files, truncated content, a bounded chain scan, // an over-1MB config, or core checksums that could not be fetched). is_clean // requires BOTH zero threats AND coverage_complete. 'is_clean' => true, 'coverage_complete' => true, 'coverage_warnings' => 0, // ACG-103 (2026-06-30): findings bucketed by verdict class. total_threats counts ONLY // confirmed malware; these three hold the rest so they are shown SEPARATELY (review / // changed-files / incomplete-coverage), never as malware "threats". 'suspicious_items' => 0, 'integrity_items' => 0, 'coverage_items' => 0, 'potential_items' => 0, 'recommendation' => '' ); // ACG-103 (2026-06-30): count by VERDICT CLASS, not by "any non-info severity". Only // malware-class findings increment total_threats (the red count) and the critical/high/ // medium/low chips. Suspicious (smell/location), integrity (checksum change) and coverage // (could-not-scan) are tallied SEPARATELY so they are shown in their own sections instead of // masquerading as malware. No detection is lost — every finding is still recorded here. foreach ( $findings as $f ) { $file_has_malware = false; foreach ( $f['findings'] as $finding ) { $sev = strtolower( (string) ( $finding['severity'] ?? 'medium' ) ); $cls = self::finding_verdict_class( $finding ); switch ( $cls ) { case 'malware': $s['total_threats']++; if ( isset( $s[ $sev ] ) ) { $s[ $sev ]++; // severity chips reflect confirmed malware only } $file_has_malware = true; break; case 'suspicious': $s['suspicious_items']++; // ACG-116-T1 (2026-07-05, OWNER DECISION — final): a suspicious finding of // HIGH/CRITICAL severity (a premium plugin's eval-style pattern, a PHP file // in /uploads) is a "potential threat": shown UNCOLLAPSED in the main results // area, honestly labelled as not confirmed. It does NOT touch total_threats // or the severity chips — those stay confirmed-only, which is what keeps the // red list meaningful. suspicious_items remains the TOTAL; potential_items is // the serious subset. Supersedes the v112 attention tier (can_quarantine-keyed). if ( in_array( $sev, array( 'high', 'critical' ), true ) ) { $s['potential_items']++; } break; case 'integrity': $s['integrity_items']++; break; case 'coverage': $s['coverage_items']++; $s['coverage_warnings']++; break; // 'info' → not counted in any bucket. } } if ( $file_has_malware ) { $s['files_infected']++; } } // ACG-103 (2026-06-30): a core file that differs from the official WordPress.org checksum is // an INTEGRITY change, not confirmed malware — it carries no signature match here. It is // surfaced prominently in the Core-Integrity section and drives the "reinstall core" // recommendation below, but it must NOT inflate the malware threat count. (Malware actually // injected into a core file matches a signature and is counted as malware on its own.) if ( $s['core_modified'] > 0 ) { $s['integrity_items'] += $s['core_modified']; } $core_critical = 0; if ( ! empty( $core_integrity['unknown'] ) ) { foreach ( $core_integrity['unknown'] as $unknown ) { if ( is_array( $unknown ) && isset( $unknown['severity'] ) ) { $sev = strtolower( (string) $unknown['severity'] ); if ( 'critical' === $sev ) { // ACG-111 (2026-07-03, from Yossi's real scan): a CRITICAL core-integrity item // (e.g. a root wp-config copy that can expose database credentials — the entry // whose own description says "DELETE IMMEDIATELY") was counted as an optional // review item, so the headline stayed a green "✅ your site looks clean!" right // above it. A credential-exposure file is a confirmed, immediately-actionable // threat: count it as one, so has_threats flips the RED headline and the // Critical chip. Non-technical users must never see "clean" next to "DELETE // IMMEDIATELY". $s['total_threats']++; $s['critical']++; $core_critical++; } elseif ( in_array( $sev, array( 'high', 'medium' ), true ) ) { // ACG-103: an unrecognised file inside a core dir is SUSPICIOUS/review — a // strong hint, but not confirmed malware without a signature match. Shown in // the Core-Integrity section, not counted as a malware threat. $s['suspicious_items']++; } elseif ( 'low' === $sev ) { // RC-114-05: low-severity entries here are coverage notices // (bounded execution-chain scan, over-1MB config) — not threats, // but they DO mean the scan was not exhaustive. $s['coverage_warnings']++; } } } } // RC-114-05: core checksums could not be fetched → core was NOT verified. if ( isset( $core_integrity['status'] ) && 'error' === $core_integrity['status'] ) { $s['coverage_warnings']++; } // RC-121-02 (audit 2026-06-19): symlinked/unreadable directories the walker could not // descend are a coverage gap — each one means files that were never scanned. Count them so // the scan reports INCOMPLETE instead of a false "clean". if ( $discovery_skipped > 0 ) { $s['coverage_warnings'] += (int) $discovery_skipped; $s['skipped_dirs'] = (int) $discovery_skipped; } // ACG-121 B4 (audit 2026-07-16): SCAN-TIME skips are a coverage gap too. A path enqueued as a normal // file at discovery but refused at scan time (swapped to a symlink/FIFO — TOCTOU — or scan_file() // returning the 'skipped' sentinel) was NEVER INSPECTED. The batch loop already increments // $state['skipped'] "so the scan reads incomplete", but the value was never passed here, so // coverage_complete stayed true and is_clean could report a green all-clear over an unscanned file. // Kept in its own key: skipped_dirs means DIRECTORIES the walker could not descend; conflating the two // would mislabel a skipped FILE as a skipped directory in the UI. if ( $scan_skipped > 0 ) { $s['coverage_warnings'] += (int) $scan_skipped; $s['skipped_files'] = (int) $scan_skipped; } $s['coverage_complete'] = ( 0 === (int) $s['coverage_warnings'] ); // ACG-103 (2026-06-30): THREE distinct verdict states for the UI, so a benign review item // never lights up the red malware alarm: // has_threats (total_threats > 0) → CONFIRMED MALWARE (red) // no malware, but review/integrity/incomplete present → ISSUES TO REVIEW (amber) // no malware, nothing to review, coverage complete → CLEAN (green) $s['review_total'] = (int) $s['suspicious_items'] + (int) $s['integrity_items']; $s['has_threats'] = ( (int) $s['total_threats'] > 0 ); // ACG-103b (2026-06-30): "is_clean" (green panel + the post-scan confirmation) means NO // CONFIRMED MALWARE and complete coverage. Review/changed-files items are SHOWN (calmly, // collapsed) but do NOT withhold the green "scan complete — no malware" state. The previous // rule also required review_total===0, so a site full of legitimate premium plugins (40+ // review items, zero malware) showed NO green at all — the user couldn't tell a scan had // even run. That was a regression; green now reflects the thing that matters: no malware. // ACG-122 (review round 2 — both reviewers called the previous behaviour a release blocker): // a HIGH/CRITICAL suspicious finding (potential_items) must NOT sit under a green "no malware // found" headline. The canonical fixture `$f = $_POST['f']; $f($_POST['a']);` — a textbook // webshell, both the callee AND its argument straight from the request — classes as suspicious, // because ACG-110 moved obf_var_func to the smell list on the claim that the malicious form // "stays malware as tk_dyn_request_callee / obf_varvar_func_input". That claim does NOT hold for // the one-variable-hop form: neither of those catches it, so the file's only findings are // suspicious and total_threats stays 0 → green. A buyer (or a competitor) opening a site with a // live webshell and reading "✅ No malware found" is exactly the false-negative this product // cannot afford. // This is the FLOOR both reviewers required: green now also requires zero HIGH/CRITICAL // suspicious items, so such a file forces the amber "issues to review" verdict instead. // ACG-103b is deliberately preserved: potential_items is only the high/critical SUBSET of // suspicious_items, so a site full of legitimate premium plugins (dozens of benign review items, // potential_items = 0) still gets its green — that regression is not re-introduced. // NOT a substitute for classifying the one-hop dynamic callee as malware; that fix needs the // tokenizer plus a full clean-corpus FP run, and is tracked separately. // ACG-135-003 (review round 3): a MODIFIED CORE FILE must withhold green. The previous cut only // EXPOSED has_core_integrity_issue and never wired it into is_clean — so a site with a modified // wp-admin/wp-includes file still got "✅ No malware found. We also noted 1 item to optionally // review below — these are common in legitimate plugins and are not malware." A core file that // differs from the official WordPress.org checksum is not "common in legitimate plugins": it is a // hacked core or a broken update, and it drives the "reinstall core" recommendation. Exposing a // flag that nothing consults is not a fix — this is the same half-fix the reviewer caught in A4. $s['has_core_integrity_issue'] = ( (int) $s['core_modified'] > 0 || (int) $s['core_unknown'] > 0 ); $s['is_clean'] = ( 0 === (int) $s['total_threats'] && $s['coverage_complete'] && 0 === (int) $s['potential_items'] && ! $s['has_core_integrity_issue'] ); // (has_core_integrity_issue is set above, where is_clean consults it.) // Distinct flag for "green but with optional review items" so the UI can add a calm note. $s['clean_with_review'] = ( $s['is_clean'] && (int) $s['review_total'] > 0 ); // ───────────────────────────────────────────────────────────────────────────────────────────── // ACG-137-B6 (self-review of the v1.0.137 diff, 2026-07-17): ONE BRANCH PER STATE. // // This ladder used to be ordered by an ad-hoc mix of is_clean and raw counters, so THREE distinct // states with nothing in common fell through to a generic "⚡ Some issues detected": // - potential_items > 0 — the flagship webshell case ACG-116-T1/ACG-122 were written FOR; // - core_unknown-only — the branch below tested core_modified, not has_core_integrity_issue, // so the half of the core-issue state that withholds green had no text; // - total_threats > 0 with only medium/low malware. // And two further defects came from the same shape: // - The ACG-116-T1 potential_items pointer was UNREACHABLE DEAD CODE: it sat inside // `if ( is_clean && clean_with_review )`, and ACG-122 later made is_clean require // potential_items === 0. The condition could never be true. A later fix silently killed an // earlier fix because both keyed off is_clean instead of the state itself. // - total_threats > 0 AND incomplete coverage ERASED the coverage gap entirely: the coverage // branch was guarded by total_threats === 0, so finding malware hid the fact that part of the // site was never checked — precisely when it matters most. // // The fix is to stop deriving the headline from is_clean (a SUMMARY of the state) and enumerate // the state itself, most severe first. is_clean/clean_with_review are still computed above and // still consumed by the UI; they are just no longer the axis this ladder pivots on. Each arm below // corresponds to exactly one reachable state, and the coverage caveat is appended to whichever arm // wins, so it can never be swallowed again. // ───────────────────────────────────────────────────────────────────────────────────────────── if ( (int) $s['total_threats'] > 0 ) { // ── CONFIRMED MALWARE (red) ──────────────────────────────────────────────────────────────── if ( (int) $s['core_modified'] > 0 ) { $s['recommendation'] = '🚨 CRITICAL: WordPress core files modified! Reinstall WordPress immediately.'; } elseif ( (int) $s['critical'] > 0 ) { $s['recommendation'] = '🚨 CRITICAL threats! Immediate action required.'; } elseif ( (int) $s['high'] > 0 ) { $s['recommendation'] = '⚠️ High-risk issues found.'; } else { // Malware confirmed, but only medium/low severity. This used to share the generic // "⚡ Some issues detected" with two unrelated no-malware states, which understated it: // these ARE confirmed detections, not review items. $s['recommendation'] = sprintf( /* translators: %d: number of confirmed malware findings */ _n( '⚠️ %d confirmed malware finding — review it below.', '⚠️ %d confirmed malware findings — review them below.', (int) $s['total_threats'], 'ai-cyberguard' ), (int) $s['total_threats'] ); } } elseif ( (int) $s['core_modified'] > 0 ) { // ── NO MALWARE, BUT CORE IS MODIFIED (amber) ────────────────────────────────────────────── $s['recommendation'] = '🚨 CRITICAL: WordPress core files modified! Reinstall WordPress immediately.'; } elseif ( (int) $s['potential_items'] > 0 ) { // ── NO MALWARE, BUT SERIOUS REVIEW ITEMS (amber) — S4, previously the generic "⚡" ──────── // This is the state ACG-116-T1 and ACG-122 exist for, and it finally has its own headline. // It says the true thing twice, because both halves matter to a non-technical reader: nothing // was CONFIRMED as malware, and something here is serious enough to look at now. $s['recommendation'] = sprintf( /* translators: %d: number of serious (high/critical) review items shown as potential threats */ _n( '⚠️ No confirmed malware — but %d item looks serious enough to check now. It is shown with the main results as a potential threat.', '⚠️ No confirmed malware — but %d items look serious enough to check now. They are shown with the main results as potential threats.', (int) $s['potential_items'], 'ai-cyberguard' ), (int) $s['potential_items'] ); } elseif ( (int) $s['core_unknown'] > 0 ) { // ── NO MALWARE, UNRECOGNISED FILES IN CORE DIRECTORIES (amber) — S6, previously "⚡" ────── // The old ladder tested core_modified here, so this half of has_core_integrity_issue — the // half that is_clean DOES withhold green for — had no recommendation of its own. $s['recommendation'] = sprintf( /* translators: %d: number of unrecognised files found in WordPress core directories */ _n( '⚠️ No confirmed malware — but %d file in your WordPress core folders is not part of the official WordPress release.', '⚠️ No confirmed malware — but %d files in your WordPress core folders are not part of the official WordPress release.', (int) $s['core_unknown'], 'ai-cyberguard' ), (int) $s['core_unknown'] ); } elseif ( ! $s['coverage_complete'] ) { // ── NO MALWARE, SCAN INCOMPLETE (amber) — S3 ────────────────────────────────────────────── // RC-114-05: no threats found, but the scan was incomplete — must NOT claim "Site clean". $s['recommendation'] = sprintf( /* translators: %d: number of coverage warnings */ _n( '⚠️ No threats detected, but the scan was incomplete (%d part of your site was not fully checked). Review the coverage notice below.', '⚠️ No threats detected, but the scan was incomplete (%d parts of your site were not fully checked). Review the coverage notices below.', (int) $s['coverage_warnings'], 'ai-cyberguard' ), (int) $s['coverage_warnings'] ); } elseif ( (int) $s['review_total'] > 0 ) { // ── GREEN WITH OPTIONAL REVIEW ITEMS — S2 (this arm IS clean_with_review) ───────────────── // ACG-103b: no confirmed malware (GREEN), but there are review/changed items to surface // honestly — typically legitimate plugin code (extract()/mailer/dynamic-call patterns), // a plugin file that differs from the WordPress.org copy, or a PHP file in /uploads. $s['recommendation'] = sprintf( /* translators: %d: number of non-malware review items */ _n( '✅ No malware found. We also noted %d item to optionally review below — these are common in legitimate plugins and are not malware.', '✅ No malware found. We also noted %d items to optionally review below — these are common in legitimate plugins and are not malware.', (int) $s['review_total'], 'ai-cyberguard' ), (int) $s['review_total'] ); } else { // ── FULLY CLEAN — S1 (this arm IS is_clean with nothing to review) ─────────────────────── $total_verified = $verified + ( $core_integrity['verified'] ?? 0 ); $s['recommendation'] = sprintf( '✅ Site clean! %s files verified against WordPress.org', number_format_i18n( $total_verified ) ); } // ACG-137-B6: the coverage caveat belongs to EVERY verdict, not just the no-malware one. The old // ladder guarded its coverage arm with total_threats === 0, so a site with malware AND an // incomplete scan was told about the malware and never told that part of the site was not looked // at — the moment that fact matters most. Appended here so no future arm can swallow it. // Skipped for the coverage arm itself, which already leads with it. if ( ! $s['coverage_complete'] && ( (int) $s['total_threats'] > 0 || (int) $s['potential_items'] > 0 || $s['has_core_integrity_issue'] ) ) { $s['recommendation'] .= ' ' . sprintf( /* translators: %d: number of coverage warnings */ _n( 'Note: the scan was also incomplete — %d part of your site was not fully checked, so there may be more.', 'Note: the scan was also incomplete — %d parts of your site were not fully checked, so there may be more.', (int) $s['coverage_warnings'], 'ai-cyberguard' ), (int) $s['coverage_warnings'] ); } // ACG-138-R2-05: the ACG-111 core-integrity pointer here was a next_action append, removed with // the rest of that dead field. The user is still pointed at the core-integrity section by // generate_summary()'s core arms (recommendation) and by the Last-Scan card's core arm (R2-03). return $s; } // ───────────────────────────────────────────────────────────────────────────────────────────────────── // ACG-149-138 — MALWARE-SCAN A BOUNDED, ALREADY-IDENTIFIED SET OF FILES. // // WHY THIS EXISTS. Until now malware detection was reachable ONLY through the three AJAX handlers // (ajax_init_scan / ajax_scan_batch / ajax_finalize_scan), each of which interleaves // check_ajax_referer(), $_POST reads and wp_send_json_*() EXITS with the actual work. Nothing outside a // logged-in admin's browser could invoke the engine — so the scheduled scan // (GuardPress_Scan_Runner::run(), integrity only) could never look for malware, and a malware finding // could never reach the email notifier. A user who enabled "Scheduled Scans" and "Email Alerts" — // both of which this product recommends — still got no automatic malware detection at all. // // WHY NOT A FULL SCHEDULED SCAN. Measured on the 12,705-file reference corpus: ~4.6 ms/file, i.e. ~59 s // for a full pass on developer hardware and several minutes on shared hosting, against a typical // max_execution_time of 30 s. A cron tick cannot complete a full scan, which is exactly why the manual // scan is batched over many requests. Making cron drive that batching would mean refactoring ~1,100 // lines of the most defensively-audited code in the plugin (ownership guards, lock CAS, the finalize // commit-gate read-back, coverage accounting, ack hashing) — a large regression risk in the core // feature, for a scan that mostly re-inspects files that have not changed since the last one. // // WHAT THIS DOES INSTEAD, and why it is the right axis. The integrity scan ALREADY runs on schedule and // ALREADY knows exactly which files are new or changed. Malware arriving on a site IS a new or changed // file, so that set is precisely where an automatic scan should look — and it is normally a handful of // files, so it costs ~nothing. This automates the instruction the product already gives the user by // hand in three places (partials/tables.php: "New file detected … Run a Malware Scan to verify"). // // THE HONEST BOUNDARY, stated because a coverage claim must not be vague: this finds malware that // ARRIVES after a baseline exists. It does NOT find malware that was already present when the baseline // was taken, nor malware sitting in a file that never changes — that is the full manual scan's job, and // the scanner page now raises "Run Your First Malware Scan" / "Last Malware Scan Was N Ago" so the user // is actually asked to run one. The two together are what make the promise true. // // Signature loading, the high-confidence pre-filter, the MAX_FILE_SIZE oversize branch and the result // contract ('skipped' = coverage gap, 'clean' = verified, else should_record_finding()) all mirror // ajax_scan_batch(); this method adds no detection logic of its own, so it cannot disagree with a manual // scan about a given file. (The oversize branch was MISSING until round 32 — R31-001 — which made this // parity claim false for exactly the files where being wrong is worst. It is asserted by a fixture now, // not just stated here.) // // @param array $abs_paths Absolute paths to inspect. // @param int $max_files Hard cap. Excess is REPORTED in 'over_limit', never silently dropped. // @return array{scanned:int,over_limit:int,over_size:int,coverage_gaps:int,clean:int,findings:array,threats:int} public static function scan_paths_for_malware( $abs_paths, $max_files = 200 ) { $out = array( 'scanned' => 0, 'over_limit' => 0, // files we declined to inspect because of the per-run CAP — surfaced, not hidden 'over_size' => 0, // files larger than MAX_FILE_SIZE — inspected only in part (R31-001) 'coverage_gaps' => 0, // scan_file() refused to read it (symlink swap / unreadable) — NOT clean // ACG-149-156 (adversarial audit): a file the engine INSPECTED but could not analyse fully — // add_coverage_notice() fires when the tokenizer's memory budget is exceeded. It emits a // type='coverage' finding, which landed in 'findings' and incremented NOTHING, so the notifier's // has_cov_gap test was false and the email claimed full coverage. Measured: the same // eval($_POST) payload padded to 411 KB (under the 2 MB cap, so no over_size) came back // threats=0, coverage_gaps=0, "File only partially scanned" — and the email said // "Likely a legitimate update" with no coverage section. Same defect class as R31-001, in the // branch that fix did not reach; the engine's own comment says this must "fail VISIBLE". 'partial' => 0, 'clean' => 0, 'findings' => array(), 'threats' => 0, // malware-CLASS only, matching total_threats semantics everywhere else // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R37-A (adversarial review of round 36) — WHICH FILES DID WE ACTUALLY LOOK AT. // // Every counter above answers "how many"; none answers "which", and that turned out to be // the load-bearing question. A caller that wants to RETIRE a previous verdict ("this file // is no longer infected") must distinguish "we inspected it and it is clean" from "we never // opened it" — and an empty findings list means BOTH. Three independent reviewers found the // same defect through that gap: a confirmed webshell's record was erased by a tick that had // not read the file (chmod 000, a symlink swap, growth past the 2 MB cap, or simply the // 300-file rotation window landing elsewhere). One chmod removed the alarm. // // So the set is now explicit. A path lands here ONLY after scan_file() returned a verdict // on its contents. Absence from this list is positive evidence of "not inspected", which is // exactly what a retirement decision needs and what a counter can never provide. 'inspected' => array(), ); if ( ! is_array( $abs_paths ) || empty( $abs_paths ) ) { return $out; } // De-duplicate on the normalized path so the same file arriving twice (two covering roots) is not // scanned or reported twice — the ACG-121 duplicate-row defect, avoided here by construction. $paths = array(); foreach ( $abs_paths as $p ) { $p = (string) $p; if ( '' === $p ) { continue; } $paths[ wp_normalize_path( $p ) ] = $p; } $paths = array_values( $paths ); $max_files = max( 0, (int) $max_files ); if ( count( $paths ) > $max_files ) { // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-156 (adversarial audit) — DETERMINISTIC STARVATION. This used to be a plain // array_slice(0, $max_files). The path list comes from a filesystem walk, so its order is // stable: the SAME first 300 files were re-scanned on every tick and the tail was NEVER // scanned. Measured: 350 changed files under wp-admin plus a backdoor in wp-content/uploads // put the backdoor at position 350 — over_limit=51, threats=0 — and tick 2's first-300 slice // was byte-identical, so it would never be reached. One "incomplete coverage" email, then // permanent silence with a trivially detectable shell on disk. // // Two changes make the tail reachable: // 1. PRIORITISE by risk before cutting — a php-family file in a writable content directory // is where a backdoor lands; a changed .js in wp-admin is almost always an update. // 2. ROTATE the remainder across runs with a persisted cursor, so a file that misses one // tick is scanned on a later one. Coverage becomes eventual instead of never. // over_limit still reports exactly how many were deferred, so nothing is hidden either way. $gp_pri = array(); foreach ( $paths as $gp_p ) { $gp_lp = strtolower( $gp_p ); $gp_isphp = (bool) preg_match( '/\.(php[0-9]?|phtml|phar|inc)$/', $gp_lp ); $gp_hot = ( false !== strpos( $gp_lp, '/wp-content/uploads/' ) ) || ( false !== strpos( $gp_lp, '/wp-content/' ) && false === strpos( $gp_lp, '/wp-content/plugins/' ) && false === strpos( $gp_lp, '/wp-content/themes/' ) ); // 0 = most suspicious (executable in a writable/upload area), 3 = least $gp_pri[] = $gp_isphp ? ( $gp_hot ? 0 : 1 ) : ( $gp_hot ? 2 : 3 ); } array_multisort( $gp_pri, SORT_ASC, SORT_NUMERIC, $paths ); $out['over_limit'] = count( $paths ) - $max_files; if ( $max_files > 0 ) { $gp_cursor = (int) get_option( 'guardpress_malware_scan_cursor_v1', 0 ); $gp_total = count( $paths ); $gp_cursor = ( $gp_cursor % $gp_total + $gp_total ) % $gp_total; // normalise, never negative // Rotate so a different window is examined each run, then take the window. $paths = array_merge( array_slice( $paths, $gp_cursor ), array_slice( $paths, 0, $gp_cursor ) ); $paths = array_slice( $paths, 0, $max_files ); update_option( 'guardpress_malware_scan_cursor_v1', ( $gp_cursor + $max_files ) % $gp_total, false ); } else { $paths = array(); } } else { // The whole set fits — coverage is complete, so the next run starts from the top again. delete_option( 'guardpress_malware_scan_cursor_v1' ); } if ( empty( $paths ) ) { return $out; } // === SIGNATURE LOADING — same set and same order as ajax_scan_batch()'s fallback path. === $signatures = self::get_signatures(); if ( class_exists( 'GuardPress_Signatures_Database' ) ) { $db_sigs = GuardPress_Signatures_Database::get_all_signatures(); if ( ! empty( $db_sigs ) ) { $signatures = array_merge( $signatures, $db_sigs ); } } if ( class_exists( 'GuardPress_Threat_Feed' ) ) { // PERF-116-05: cached feed only — never a synchronous network call during a scan, and this // path runs inside a cron tick where a hanging request would stall the whole scheduled run. $feed_sigs = GuardPress_Threat_Feed::get_signatures( false, false ); if ( ! empty( $feed_sigs ) ) { $signatures = array_merge( $signatures, $feed_sigs ); } } $signatures = array_merge( $signatures, self::collect_extra_signature_sets() ); // ACG-045-008: deduplicate by stable ID *and* by effective pattern. $unique = array(); $seen = array(); $seen_pat = array(); foreach ( $signatures as $sig ) { $id = $sig['id'] ?? ''; $pat = isset( $sig['pattern'] ) ? (string) $sig['pattern'] : ''; if ( ( '' !== $id && isset( $seen[ $id ] ) ) || ( '' !== $pat && isset( $seen_pat[ $pat ] ) ) ) { continue; } if ( '' !== $id ) { $seen[ $id ] = true; } if ( '' !== $pat ) { $seen_pat[ $pat ] = true; } $unique[] = $sig; } $signatures = $unique; $core_checksums = self::get_core_checksums(); $malware_hashes = class_exists( 'GuardPress_Threat_Feed' ) ? GuardPress_Threat_Feed::get_malware_hashes() : array(); // PERF (v8.2): pre-compute the high-confidence subset once, not per file. $hc_sigs = array(); foreach ( $signatures as $s ) { $sev = strtolower( $s['severity'] ?? 'high' ); if ( 'critical' === $sev || 'high' === $sev ) { $hc_sigs[] = $s; } } $plugin_cache = array(); foreach ( $paths as $abs ) { // ACG-121: the shared no-follow contract. A path handed to us was identified by a DIFFERENT // pass (the integrity walk), so it may have been swapped to a symlink since — refuse to follow, // and count it as a coverage gap rather than silently treating it as clean. if ( ! self::is_safe_regular_file( $abs ) ) { $out['coverage_gaps']++; continue; } // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-155 (adversarial review) — THE TWO OWN-FILE GATES ajax_scan_batch() APPLIES AND I // DID NOT. Their absence made this method's "mirrors ajax_scan_batch" claim FALSE in the one // way that hurts most. // // THE FAILURE: when the plugin updates itself, every one of ITS OWN files shows up in the // integrity report as `changed`, and class-cron.php feeds exactly those paths to this method. // This plugin's detection code deliberately contains live malware patterns — that is what a // scanner IS — so scanning ourselves produces self-false-positives, and the scheduled scan // would email the site owner "MALWARE FOUND: N confirmed threats" listing OUR OWN FILES. // Nothing could destroy trust faster, and it would fire on a routine plugin update. // // is_unmodified_own_file() trusts a shipped file only when its sha256 matches the signed // manifest, so a TAMPERED copy of our own file is still scanned — the gate cannot be used as // a hiding place. is_internal_data_path() is the ACG-112/ACG-103 exclusion for our own data // store, which carries strings that trip generic signatures (it was once reported as a // CRITICAL "Adminer Shell" against itself). if ( self::is_unmodified_own_file( $abs ) ) { continue; // our own shipped file, hash-verified against the manifest } if ( class_exists( 'GuardPress_FS_Helpers' ) && GuardPress_FS_Helpers::is_internal_data_path( $abs ) ) { continue; // our own data store } // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-142 (round 32, R31-001) — THE SIZE CAP, which this method was missing. // // scan_file() reads at most MAX_FILE_SIZE bytes (one bounded read, deliberately, for the // TOCTOU reason documented at its top). So a file LARGER than the cap is inspected only in // part — and without this branch it was counted in 'scanned' with no finding and no gap, // i.e. reported as fully checked. A 2.2 MB PHP file with the payload after the first 2 MB // therefore passed a scheduled scan silently: no malware, no warning, nothing. // // That is the worst shape of defect this product can have — not a miss the user is told // about, but a miss dressed as coverage. Reproduced on real WordPress before fixing: // scanned=1 over_limit=0 coverage_gaps=0 threats=0, only a 'location' row. // // The fix is PARITY, not a new invention: ajax_scan_batch() already emits exactly this // finding and `continue`s (see its oversize branch), so the identical finding is emitted // here — same type, severity rule, name, description and recommendation — which is what // makes this method's "mirrors ajax_scan_batch" claim true instead of aspirational. // ACG-087-H1: gate the size read through the no-follow contract, or a symlinked parent // would report the EXTERNAL target's size. // // Counted in its own key, NOT in coverage_gaps: ACG-137-B2 established that folding an // over-cap file into "failure to inspect" made one ordinary large backup mark every scan // permanently amber — false and unactionable. An over-cap file is a BOUNDARY; an unreadable // one is a FAILURE. Both are reported, neither is silent, and they stay distinguishable. $gp_fsize = @filesize( $abs ); if ( false !== $gp_fsize && $gp_fsize > self::MAX_FILE_SIZE ) { $gp_bn = basename( $abs ); $gp_exec = self::has_php_family_suffix( $gp_bn ) || in_array( strtolower( pathinfo( $gp_bn, PATHINFO_EXTENSION ) ), self::php_family_exts(), true ); $gp_rel = ltrim( str_replace( wp_normalize_path( rtrim( ABSPATH, '/\\' ) ), '', wp_normalize_path( $abs ) ), '/' ); $out['over_size']++; $out['findings'][] = array( 'filepath' => $gp_rel, 'risk_score' => $gp_exec ? 60 : 5, 'findings' => array( array( 'type' => 'oversize', 'severity' => $gp_exec ? 'high' : 'low', 'name' => __( 'File too large to fully scan', 'ai-cyberguard' ), 'description' => __( 'This file exceeds the scanner size limit (2 MB) and was not fully scanned for malware. Large executable/script files are unusual.', 'ai-cyberguard' ), 'recommendation' => __( 'Open and review this file; remove it if you do not recognise it.', 'ai-cyberguard' ), // Stamped here for the same reason every other row is: the notifier reads the // verdict and must never have to re-derive it. 'oversize' classes as 'coverage', // so this row can never be mistaken for a confirmed threat. 'verdict' => 'coverage', ) ), ); continue; // NOT scanned, NOT clean } // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-R37-Y — AN UNREADABLE FILE IS A COVERAGE GAP, NOT A VERDICT. // // Found by running the attack instead of trusting the fix. scan_file() returns its distinct // 'skipped' sentinel only for the no-follow gate; when the bounded read itself FAILS it // carries on into scan_file_uncached() with no content and produces a STRUCTURAL result — // filename, extension, location. So `chmod 000` on a confirmed webshell yielded an ARRAY // with no malware finding: the engine reported it as looked-at-and-not-malicious, having // read none of it. Measured on real MariaDB as the web user (uid 33): // is_readable=false -> threats=0 coverage_gaps=0 inspected=1 // which then retired the confirmed verdict and emptied the watch list — the very attack the // rest of this round exists to stop, surviving one layer deeper than the reviewers found it. // // Checked here rather than in scan_file() because this is the SCHEDULED path's coverage // accounting: "we could not open it" must land in coverage_gaps and must never enter // 'inspected', which is the set a retirement decision trusts. (TOCTOU-wise this is a hint, // not a gate — the real gate is scan_file()'s own bounded read; a file that becomes readable // between the two is simply inspected on the next run.) if ( ! @is_readable( $abs ) ) { $out['coverage_gaps']++; continue; } $result = self::scan_file( $abs, $signatures, $core_checksums, $plugin_cache, $malware_hashes, $hc_sigs ); // ACG-149-R36-F (pre-release audit 2026-07-27): 'scanned' used to be incremented HERE, // before the arms below — so a file scan_file() REFUSED (symlink swap, unreadable) was // counted in 'scanned' AND in 'coverage_gaps' at the same time. One file, reported both // as inspected and as not inspected: "scanned 300, of which 12 could not be read" is a // contradiction, and any consumer computing "inspected minus gaps" gets an over-count. // Now it counts a file only on an arm that actually looked at its contents. if ( 'skipped' === $result ) { $out['coverage_gaps']++; } elseif ( 'clean' === $result ) { $out['scanned']++; $out['clean']++; $out['inspected'][] = wp_normalize_path( $abs ); // ACG-149-R37-A: read, and verified clean } elseif ( ! is_array( $result ) ) { // SELF-REVIEW (adversarial pass on this diff): scan_file()'s contract today is // 'skipped' | 'clean' | array, but if it ever gains a fourth string return this branch // would previously have fallen through every arm — leaving the file counted in 'scanned' // and in NOTHING else, which reads downstream as "inspected, nothing found". An // unrecognised verdict is a file we did not actually clear, so it counts as a COVERAGE GAP. // Fail-visible rather than fail-clean; this is the false all-clear RC-116 exists to prevent. $out['coverage_gaps']++; } elseif ( self::should_record_finding( $result ) ) { $out['scanned']++; // ACG-149-R36-F: inspected — the contents were read and analysed $out['inspected'][] = wp_normalize_path( $abs ); // ACG-149-R37-A // ACG-149-R37-B: carry the ABSOLUTE path beside the display path. 'filepath' is built // with str_replace( ABSPATH, '', … ), which strips EVERY occurrence — so a file under // wp-content/uploads/home/site/public_html/ comes back as "wp-content/uploadsshell.php" // and can never be resolved again. That was a display wart before this round; the // scheduled record then made the same string load-bearing for the alarm AND the // re-inspection, so a confirmed backdoor at such a path silently fell out of both. $result['gp_abs'] = wp_normalize_path( $abs ); // Stamp the verdict class exactly as ajax_finalize_scan() does, so a consumer (the email // notifier) never has to re-derive it and can never disagree with the results table. if ( ! empty( $result['findings'] ) && is_array( $result['findings'] ) ) { $gp_saw_partial = false; foreach ( $result['findings'] as $j => $fnd ) { $vc = self::finding_verdict_class( $fnd ); $result['findings'][ $j ]['verdict'] = $vc; if ( 'malware' === $vc ) { $out['threats']++; } // ACG-149-156: a 'coverage' row means the engine could not finish analysing this // file. Count it ONCE per file so the notifier can say so — silently carrying it // in findings and reporting full coverage is the exact failure this round exists // to remove. Counted separately from coverage_gaps: this file WAS opened and // partly analysed, the other was never read at all, and the user action differs. if ( 'coverage' === $vc && 'oversize' !== ( $fnd['type'] ?? '' ) ) { $gp_saw_partial = true; } } if ( $gp_saw_partial ) { $out['partial']++; } } $out['findings'][] = $result; } else { // ACG-149-R36-F: an array result the recorder discarded (nothing worth reporting). // The file WAS read and analysed, so it belongs in 'scanned'. Made explicit — before // this change the shared increment above covered it, and moving the increment into the // arms would otherwise have dropped this case silently. $out['scanned']++; $out['inspected'][] = wp_normalize_path( $abs ); // ACG-149-R37-A: read, nothing to report } } // Persist the incremental verdict cache, exactly as the batch path does, so the next scan can skip // files proven clean here. Without this the work is thrown away every tick. self::verdict_cache_flush(); return $out; } // ───────────────────────────────────────────────────────────────────────────────────────────────────── // ACG-149-156 (adversarial audit) — A SCHEDULED DETECTION MUST SURVIVE EVEN IF NO EMAIL IS SENT. // // THE HOLE, measured on a real install: plant a webshell, let the scheduled scan run. It DETECTS it // (critical / "Shell Command From Request") — and then the finding exists nowhere but the email body. // `email_enabled` ships as 0 (class-settings.php), so on a default install: no email, nothing stored, // and the dashboard says "Review Needed — 1 file change detected". The product positively identified a // backdoor and threw the identification away. The same loss happened when wp_mail failed or no // recipient was configured. // // That was my design error: I deliberately did not persist, to avoid overwriting the MANUAL scan's // report (whose coverage numbers describe a whole-site scan and must not be replaced by a // changed-files-only run). The fix keeps that separation instead of abandoning the data — its own // record, its own key, read by the dashboard alongside the manual one. const OPTION_SCHEDULED_MALWARE = 'guardpress_scheduled_malware_v1'; /** * Strip the install root from an absolute path — LEADING occurrence only. * * ACG-149-R37-B: `str_replace( ABSPATH, '', $p )` removes EVERY occurrence, so a path that legitimately * contains the install root twice (backup plugins mirror absolute paths under uploads/, and an attacker * can simply mkdir one) came back mangled — "wp-content/uploadsshell.php" — and could never be resolved * back to a real file. Harmless while it was only a display string; not harmless once the same string * decides whether a confirmed backdoor keeps its alarm and its re-inspection. */ private static function rel_to_abspath( $abs ) { $abs = wp_normalize_path( (string) $abs ); $root = rtrim( wp_normalize_path( ABSPATH ), '/' ) . '/'; return ( 0 === strpos( $abs, $root ) ) ? substr( $abs, strlen( $root ) ) : $abs; } /** * Persist the scheduled scan's malware result. Never touches 'malware-last-scan'. * * ───────────────────────────────────────────────────────────────────────────────────────────────── * ACG-149-R37-A (adversarial review of round 36) — THIS MERGES; IT DOES NOT OVERWRITE. * * The first version rebuilt the record from the current tick's findings alone. That silently deleted * any previously-confirmed file the tick had not actually inspected — and there are four ordinary ways * for that to happen, one of which an attacker triggers on demand: * · chmod 000 on the shell -> scan_file() refuses -> coverage_gaps, no finding * · a symlink swapped in -> the no-follow gate refuses -> coverage_gaps, no finding * · the file grows past 2 MB -> the oversize branch -> over_size, no finding * · >300 changed files -> the rotation window lands elsewhere -> over_limit, no finding * In every one the record was rewritten to files=[], so the red dashboard notice went dark, the * re-inspect watch list emptied, and nothing ever revisited the file again. A single chmod removed * the alarm. That is the worst shape this product can have, and it was introduced by the fix meant * to prevent exactly it. * * The rule now: a recorded file is retired ONLY by positive evidence — this run READ it and reached a * verdict (it appears in $inspected) and did not re-confirm malware. No evidence means no change. * * @param array $result scan_paths_for_malware() output. * @param array|null $inspected Absolute paths this run actually read. NULL = "unknown", which is * treated as "inspected nothing", so nothing is retired. Fail-safe by * construction: an older or third-party caller cannot erase a verdict. */ public static function save_scheduled_findings( $result, $inspected = null ) { if ( ! is_array( $result ) ) { return false; } // What this run proved it looked at, keyed on the stored (relative) form. $seen = array(); foreach ( (array) ( is_array( $inspected ) ? $inspected : array() ) as $abs ) { if ( is_string( $abs ) && '' !== $abs ) { $seen[ self::rel_to_abspath( $abs ) ] = true; } } // Carry forward every previously-recorded file this run did NOT inspect. get_scheduled_findings() // has already dropped rows whose file no longer exists, so a deleted threat still retires at once. $files = array(); $prev = self::get_scheduled_findings(); foreach ( (array) ( isset( $prev['files'] ) && is_array( $prev['files'] ) ? $prev['files'] : array() ) as $row ) { if ( ! is_array( $row ) ) { continue; } $p = isset( $row['path'] ) && is_string( $row['path'] ) ? $row['path'] : ''; if ( '' === $p || isset( $seen[ $p ] ) ) { continue; // inspected this run -> this run's verdict decides below } $files[ $p ] = array( 'path' => $p, 'name' => isset( $row['name'] ) && is_string( $row['name'] ) ? $row['name'] : '', // ACG-149-R37-T: WHEN WE FIRST SAW IT, carried forward untouched. The record's 'time' is // rewritten on every re-check, so the notice's "detected N ago" always read "1 second // ago" — a week-old infection presented as breaking news, which is both wrong and the // wrong urgency signal. 'first' => isset( $row['first'] ) && is_numeric( $row['first'] ) ? (int) $row['first'] : 0, ); } // This run's confirmed malware. ONE ROW PER FILE, not per signature: a webshell that matches three // signatures used to produce three identical rows, which inflated the headline count, printed the // same filename three times, and let one file consume the entire 50-row budget — hiding 49 other // infected files from both the notice and the watch list. foreach ( (array) ( $result['findings'] ?? array() ) as $ff ) { if ( ! is_array( $ff ) ) { continue; } $abs = isset( $ff['gp_abs'] ) && is_string( $ff['gp_abs'] ) ? $ff['gp_abs'] : ''; $p = ( '' !== $abs ) ? self::rel_to_abspath( $abs ) : ( isset( $ff['filepath'] ) && is_string( $ff['filepath'] ) ? $ff['filepath'] : '' ); if ( '' === $p ) { continue; } foreach ( (array) ( $ff['findings'] ?? array() ) as $fnd ) { if ( ! is_array( $fnd ) || 'malware' !== ( $fnd['verdict'] ?? '' ) ) { continue; } $files[ $p ] = array( 'path' => $p, 'name' => ( isset( $fnd['name'] ) && is_scalar( $fnd['name'] ) ) ? (string) $fnd['name'] : '', // ACG-149-R37-T: keep the ORIGINAL sighting when this file was already on the record. 'first' => isset( $files[ $p ]['first'] ) && $files[ $p ]['first'] > 0 ? (int) $files[ $p ]['first'] : time(), ); break; // one row per file } } // Bounded: this record is read on every scanner-page render. Report what the cap hid rather than // dropping it silently — the bound the user cannot see is the defect this whole round is about. $files = array_values( $files ); $dropped = 0; if ( count( $files ) > 50 ) { $dropped = count( $files ) - 50; $files = array_slice( $files, 0, 50 ); } $rec = array( 'time' => time(), 'threats' => count( $files ), // the NAMEABLE rows are the authority (ACG-149-138) 'over_limit' => isset( $result['over_limit'] ) ? (int) $result['over_limit'] : 0, 'over_size' => isset( $result['over_size'] ) ? (int) $result['over_size'] : 0, 'coverage_gaps' => isset( $result['coverage_gaps'] ) ? (int) $result['coverage_gaps'] : 0, 'partial' => isset( $result['partial'] ) ? (int) $result['partial'] : 0, 'files_dropped' => $dropped, 'files' => $files, ); if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::save( 'scheduled-malware', $rec, 'cache' ); } update_option( self::OPTION_SCHEDULED_MALWARE, $rec, false ); return true; } /** * ACG-149-R37-U — MAKE THE PRUNE DURABLE. * * get_scheduled_findings() drops rows whose file is gone, but only in the value it RETURNS; the * stored record keeps them. Measured consequence: the user deletes an infected plugin (the correct * action), the notice clears — and then they reinstall a CLEAN copy from the developer at the same * path, and the stale row matches a file that exists again. The red "confirmed threat" banner comes * back naming a file that is now clean, and stays until the next scheduled tick, which on the weekly * schedule is up to seven days. * * Called from the cron tick, never from a page render: this plugin treats a state write on a plain * admin GET as a defect. It writes ONLY when the prune actually changed something, so a quiet tick * on a healthy site still performs no write at all. * * @return bool True when the record was rewritten. */ public static function reconcile_scheduled_findings() { $raw = get_option( self::OPTION_SCHEDULED_MALWARE, array() ); if ( ! is_array( $raw ) || empty( $raw['files'] ) || ! is_array( $raw['files'] ) ) { return false; } $view = self::get_scheduled_findings(); // the pruned view $kept = ( isset( $view['files'] ) && is_array( $view['files'] ) ) ? $view['files'] : array(); if ( count( $kept ) === count( $raw['files'] ) ) { return false; // nothing vanished — no write } $raw['files'] = $kept; $raw['threats'] = count( $kept ); if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::save( 'scheduled-malware', $raw, 'cache' ); } update_option( self::OPTION_SCHEDULED_MALWARE, $raw, false ); return true; } /** The scheduled scan's last malware result, or array() if there is none. */ public static function get_scheduled_findings() { $r = null; if ( class_exists( 'GuardPress_File_Storage' ) ) { $r = GuardPress_File_Storage::load( 'scheduled-malware', null, 'cache' ); } if ( ! is_array( $r ) ) { $r = get_option( self::OPTION_SCHEDULED_MALWARE, array() ); } if ( ! is_array( $r ) ) { return array(); } // ACG-149-R36-E: drop rows for files that no longer exist — the same rule get_last_scan() // applies via prune_vanished_findings() (ACG-120-002, Yossi's own report: a results list that // keeps naming a file the user has already deleted is confusing and reads as an unresolved // threat). It matters more here: this record drives a red dashboard notice AND the re-inspect // watch list, and DELETING the file is one of the two correct responses to the notice. Without // this, deleting the malware would leave the alarm on screen permanently — the watch list // cannot re-scan a file that is gone, so nothing would ever rewrite the record. if ( ! empty( $r['files'] ) && is_array( $r['files'] ) ) { $root = rtrim( str_replace( '\\', '/', ABSPATH ), '/' ); $kept = array(); foreach ( $r['files'] as $row ) { // ACG-149-R37-C: every field is validated as a STRING before use. The record lives in the // options table and in File_Storage; a corrupt or hostile value (an object, an array) used // to reach a `(string)` cast and throw an uncaught Error — fatal not only on the admin page // but inside CRON, because malware_watch_paths() reads through here too. A malformed row is // dropped, never dereferenced. if ( ! is_array( $row ) || ! isset( $row['path'] ) || ! is_string( $row['path'] ) ) { continue; } if ( isset( $row['name'] ) && ! is_string( $row['name'] ) ) { $row['name'] = ''; } $p = str_replace( '\\', '/', $row['path'] ); // ACG-149-R37-D: refuse traversal. Nothing we write produces it, but the record is // persisted state and a path that escapes the install must never be offered for // inspection or printed as one of "your" infected files. if ( '' === $p || false !== strpos( $p, '../' ) || false !== strpos( $p, '..\\' ) ) { continue; } $abs = ( 0 === strpos( $p, $root . '/' ) ) ? $p : $root . '/' . ltrim( $p, '/' ); if ( @is_file( $abs ) ) { $kept[] = $row; } } $r['files'] = $kept; // ACG-149-R37-C: the count must follow the prune. prune_vanished_findings() recomputes its // headline counts for exactly this reason; leaving 'threats' at the stored value would let a // consumer say "2 confirmed threats" over an empty list. $r['threats'] = count( $kept ); } return $r; } /** * Clear it. Called when a MANUAL scan finishes: that scan is broader (whole site, not just changed * files) and its verdict supersedes, so leaving the old scheduled record would double-report. */ public static function clear_scheduled_findings() { if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::delete( 'scheduled-malware', 'cache' ); } delete_option( self::OPTION_SCHEDULED_MALWARE ); } public static function get_last_scan() { // BINLOG FIX (v8.2): Read from file instead of DB $loaded = null; if ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'malware-last-scan', null, 'cache' ); } if ( ! is_array( $loaded ) ) { $loaded = get_option( self::OPTION_LAST_SCAN ); // Fallback to DB (legacy) } if ( is_array( $loaded ) ) { $loaded = self::prune_vanished_findings( $loaded ); // ACG-120-002 (Yossi): drop rows for files deleted since the scan } return $loaded; } /** * ACG-120-002 (2026-07-05, Yossi's report): a cached scan result can list a file the user * has since DELETED (e.g. a wp-config-sample.php lookalike). Showing it is confusing — the * file is gone. Before serving cached results, drop any file_findings row whose file no * longer exists on disk, and recompute the headline counts so Critical / "N threats" match * the pruned list. A file finding with an absolute path outside ABSPATH, or a core-integrity * row (which is recomputed fresh each scan), is left untouched. */ private static function prune_vanished_findings( $result ) { if ( empty( $result['file_findings'] ) || ! is_array( $result['file_findings'] ) ) { return $result; } $kept = array(); $removed = 0; foreach ( $result['file_findings'] as $ff ) { $rel = is_array( $ff ) && isset( $ff['filepath'] ) ? (string) $ff['filepath'] : ''; if ( '' === $rel ) { $kept[] = $ff; continue; } $abs = ABSPATH . ltrim( str_replace( '\\', '/', $rel ), '/' ); if ( @file_exists( $abs ) ) { $kept[] = $ff; } else { $removed++; } } if ( 0 === $removed ) { return $result; } $result['file_findings'] = array_values( $kept ); // Recompute the summary from the pruned findings so the headline counts stay truthful. if ( isset( $result['summary'] ) && is_array( $result['summary'] ) ) { // ACG-148-013 (self-review, siege [01]): the persisted report stores core integrity under // $result['extra_findings']['core_integrity'] (see the $result literal built at the end of the // batch scan) — there is NO top-level $result['core_integrity'] key. Reading the wrong key made // this default to an EMPTY core set on every prune, so regenerating the summary ERASED the // "modified core file" verdict the moment ANY unrelated file finding vanished (the user deletes a // flagged shell, reloads → the core-integrity warning silently disappears). Read the real key, // with the legacy top-level key first for forward-compatibility. $core = ( isset( $result['core_integrity'] ) && is_array( $result['core_integrity'] ) ) ? $result['core_integrity'] : ( ( isset( $result['extra_findings']['core_integrity'] ) && is_array( $result['extra_findings']['core_integrity'] ) ) ? $result['extra_findings']['core_integrity'] : array( 'modified' => array(), 'unknown' => array() ) ); $verified = isset( $result['verified_clean'] ) ? (int) $result['verified_clean'] : 0; // ACG-137-B7 (self-review of the v1.0.137 diff, 2026-07-17): CARRY THE COVERAGE FACTS ACROSS // THE RECOMPUTE — a FALSE ALL-CLEAR bug, and the same "the fact never travels" axis as B2/B5. // // This recompute passed neither coverage input: // - $scan_skipped (5th arg) was OMITTED entirely -> defaulted to 0; // - $skipped read $result['discovery_skipped'], a key the scan result NEVER CONTAINS // (see the $result literal built at the end of the batch scan — it has no such key), // so it was ALWAYS 0 too. // Both coverage_warnings inputs therefore reset to zero here, coverage_complete flipped back // to TRUE, and is_clean could report a GREEN "site clean" over files that were never scanned // — exactly the false all-clear the comment above generate_summary() exists to prevent, // re-introduced by the pruner. // // The SUMMARY is the durable carrier of these facts (skipped_dirs / skipped_files are written // into it and persisted with the report), so reconstruct from the summary we are replacing. // This also gives those two keys their first live reader — until now both were write-only. $prev = ( isset( $result['summary'] ) && is_array( $result['summary'] ) ) ? $result['summary'] : array(); $skipped = isset( $prev['skipped_dirs'] ) ? (int) $prev['skipped_dirs'] : ( isset( $result['discovery_skipped'] ) ? (int) $result['discovery_skipped'] : 0 ); $scan_sk = isset( $prev['skipped_files'] ) ? (int) $prev['skipped_files'] : 0; $fresh = self::generate_summary( $result['file_findings'], $verified, $core, $skipped, $scan_sk ); // Preserve fields the summary regenerator does not own (e.g. acknowledged_hidden). if ( isset( $result['summary']['acknowledged_hidden'] ) ) { $fresh['acknowledged_hidden'] = $result['summary']['acknowledged_hidden']; } $result['summary'] = $fresh; } // Persist the pruned result so the next read is already clean. if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::save( 'malware-last-scan', $result, 'cache' ); } return $result; } /** * @param bool $keep_last_scan Keep the malware VERDICT (see ACG-149-144 below); working data is always cleaned. */ public static function clear_results( $keep_last_scan = false ) { // ───────────────────────────────────────────────────────────────────────────────────────────── // ACG-149-144 (owner report, 2026-07-27): CREATING A BASELINE USED TO DELETE THE MALWARE RESULT. // // The owner ran a malware scan, saw results, then created a baseline — and the page came back // saying "Run your first malware scan". Traced to Batch_Scanner::finalize_baseline() calling this // method unconditionally: the verdict lives in File_Storage 'malware-last-scan', get_last_scan() // returned null, so render_status_banner()'s $scanned went false and it fell to its "never // scanned" branch. Worse than the wrong label: the threat list he had just been shown was gone. // // The v145 rationale for clearing was "prior Scan Details represent the pre-baseline state … the // files they flagged as threats are now part of the accepted baseline". That CONFLATES THE TWO // ENGINES. A baseline accepts the current file state for CHANGE detection; malware detection is // signature-based and independent of it. A backdoor does not stop being a backdoor because it was // baselined — which is exactly what the owner observed: "the same threats keep appearing". // Accepting a file as the change-reference is NOT the user accepting malware in it. // // So the caller now chooses. The baseline path keeps the verdict (it is still true) and the // BASELINE-RELATIVE data is still cleared by finalize_baseline() itself // (guardpress_last_report_v1 etc.), which is what the v145 finding was actually about. The // "Clear Results" BUTTON still clears everything — that is a user asking for it, so its behaviour // is unchanged by construction (default false). if ( ! $keep_last_scan ) { // Clear scan result (file-based + legacy DB) if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::delete( 'malware-last-scan', 'cache' ); } delete_option( self::OPTION_LAST_SCAN ); // ACG-149-R37-E: the SCHEDULED record is cleared here too — and only here, on the explicit // "Clear Results" action. Round 37 stopped an ordinary manual scan from retiring it (a Quick // scan wiped a verdict it had never looked at), which left the red notice with no way for the // user to dismiss it. A user pressing "Clear Results" IS the dismissal, and it is the one // place where discarding a verdict is what was actually asked for. The baseline path passes // $keep_last_scan = true and is therefore unaffected — R34's fix stands. self::clear_scheduled_findings(); } // Working data (file list, cached signatures, in-flight state) is ALWAYS cleaned: it is per-scan // scratch, and leaving a stale malware_state behind could confuse a later scan's resume. self::cleanup_scan_data(); // Clear checksums cache (file-based + legacy DB) if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::delete( 'checksums-cache', 'cache' ); } delete_option( self::OPTION_CHECKSUMS_CACHE ); self::$checksums_option_cache = null; } /** * Get signature statistics (v7.9 - counts all sources) * @return array */ public static function get_signature_stats() { $total = count( self::get_signatures() ); // Built-in (30) // Add Signatures Database count if ( class_exists( 'GuardPress_Signatures_Database' ) ) { $total += GuardPress_Signatures_Database::get_count(); } // Add Threat Feed count — read the CACHED count only. // Must NOT call get_signatures() here: that auto-fetches from the // server when an update is due, which would fire a live HTTP request // (and stamp last_update) during admin page render. get_status() // counts the cached signatures without any network call. if ( class_exists( 'GuardPress_Threat_Feed' ) ) { $status = GuardPress_Threat_Feed::get_status(); $total += isset( $status['signature_count'] ) ? (int) $status['signature_count'] : 0; } return array( 'total' => $total ); } // ==================== ULTIMATE SCANNER INTEGRATION ==================== public static function ultimate_scanner_available() { return class_exists( 'GuardPress_Ultimate_Scanner' ); } public static function ultimate_scan_file( $filepath ) { if ( ! self::ultimate_scanner_available() ) { return array( 'error' => 'Ultimate Scanner not loaded' ); } $result = GuardPress_Ultimate_Scanner::analyze( $filepath ); return self::convert_ultimate_result( $result ); } public static function ultimate_start_scan( $type = 'regular' ) { if ( ! class_exists( 'GuardPress_Ultimate_Security_Engine' ) ) { return array( 'error' => 'Security Engine not loaded' ); } return GuardPress_Ultimate_Security_Engine::start_scan( $type ); } public static function ultimate_continue_scan() { if ( ! class_exists( 'GuardPress_Ultimate_Security_Engine' ) ) { return array( 'error' => 'Security Engine not loaded' ); } return GuardPress_Ultimate_Security_Engine::continue_scan(); } public static function ultimate_get_status() { if ( ! class_exists( 'GuardPress_Ultimate_Security_Engine' ) ) { return null; } return GuardPress_Ultimate_Security_Engine::get_scan_status(); } public static function ultimate_get_results() { if ( ! class_exists( 'GuardPress_Ultimate_Security_Engine' ) ) { return null; } return GuardPress_Ultimate_Security_Engine::get_scan_results(); } public static function ultimate_quarantine_file( $filepath ) { if ( ! class_exists( 'GuardPress_Ultimate_Security_Engine' ) ) { return array( 'error' => 'Security Engine not loaded' ); } return GuardPress_Ultimate_Security_Engine::quarantine_file( $filepath ); } public static function ultimate_generate_report() { if ( ! class_exists( 'GuardPress_Ultimate_Security_Engine' ) ) { return array( 'error' => 'Security Engine not loaded' ); } return GuardPress_Ultimate_Security_Engine::generate_report(); } public static function ultimate_get_stats() { if ( ! self::ultimate_scanner_available() ) { return array(); } return array( 'scanner_stats' => GuardPress_Ultimate_Scanner::get_stats(), 'signature_count' => class_exists( 'GuardPress_Ultimate_Signatures' ) ? GuardPress_Ultimate_Signatures::get_count() : 0, 'engine_version' => defined( 'GuardPress_Ultimate_Scanner::VERSION' ) ? GuardPress_Ultimate_Scanner::VERSION : '3.0.0', ); } private static function convert_ultimate_result( $result ) { $findings = array(); foreach ( $result['indicators'] ?? array() as $indicator ) { $findings[] = array( 'type' => $indicator['type'] ?? 'pattern', 'severity' => $indicator['severity'] ?? 'medium', 'name' => $indicator['title'] ?? 'Detection', 'description' => $indicator['description'] ?? '', 'line' => $indicator['line'] ?? null, 'recommendation' => $result['recommendation'] ?? '', ); } return array( 'filepath' => str_replace( wp_normalize_path( ABSPATH ), '', wp_normalize_path( $result['filepath'] ?? '' ) ), // FIX (2026-06-13): normalize both sides (Windows/mixed-slash) 'findings' => $findings, 'risk_score' => $result['risk_score'] ?? 0, 'severity' => $result['severity'] ?? 'safe', 'confidence' => $result['confidence'] ?? 0, 'is_threat' => $result['is_threat'] ?? false, 'recommendation' => $result['recommendation'] ?? '', 'layers' => $result['layers'] ?? array(), ); } } GuardPress_Malware_Scanner::init();