longest pattern token) const MAX_OVERSIZE_ROWS = 200; // per-table cap on oversize rows streamed each scan /** * Suspicious patterns to look for in database * Only include patterns that are almost always malicious */ private static $db_patterns = array( // Dangerous JavaScript - only flag truly suspicious patterns 'eval(' => array( 'severity' => 'high', 'title' => 'Eval Function', 'explanation' => 'Contains an eval() call, which runs code dynamically. This is common and legitimate in JavaScript (calculators, page builders, embedded widgets), but can also be abused by malware. Worth checking with a developer if you do not recognise this content.', ), 'document.write(unescape' => array( 'severity' => 'critical', 'title' => 'Obfuscated Document Write', 'explanation' => 'Uses unescape(), a technique that can hide code. Sometimes used by older legitimate scripts, sometimes by malware to obscure a payload. Have a developer confirm if you do not recognise it.', ), 'String.fromCharCode' => array( 'severity' => 'high', 'title' => 'Character Code Obfuscation', 'explanation' => 'Builds text from character codes, which can be used to obscure content. This appears in some legitimate scripts as well as in malware. Worth a developer check if unfamiliar.', ), 'atob(' => array( 'severity' => 'high', 'title' => 'Base64 Decode', 'explanation' => 'Decodes base64 data in JavaScript. Many legitimate scripts do this, but it can also conceal a malicious payload. Have a professional review it if you do not recognise this content.', ), // Hidden redirects 'window.location.href=' => array( 'severity' => 'high', 'title' => 'JavaScript Redirect', 'explanation' => 'Changes the page location (a redirect). This is normal in many themes and plugins, but can also be used to send visitors elsewhere. Check with a developer if the destination is unfamiliar.', ), 'top.location=' => array( 'severity' => 'high', 'title' => 'Frame Busting Redirect', 'explanation' => 'Redirects the top-level page even from within a frame. Used legitimately in some cases, but also by unwanted redirects. Worth confirming with a developer if unexpected.', ), // PHP code in database - always bad ' array( 'severity' => 'critical', 'title' => 'PHP Code in Database', 'explanation' => 'Looks like PHP code stored in database content, which is unusual for normal posts or options. This can be legitimate (some plugins store templates), but it can also indicate injected code. Recommended to have a developer verify this one.', ), ' array( 'severity' => 'critical', 'title' => 'PHP Short Tag', 'explanation' => 'Looks like a PHP short echo tag in database content. Occasionally legitimate, but PHP in stored content is worth confirming with a developer.', ), // Known malware patterns 'WP_INSERT_USER' => array( 'severity' => 'critical', 'title' => 'User Creation Code', 'explanation' => 'Contains text related to creating administrator users. This can be legitimate (some plugins manage users), but because a fake admin is a common backdoor, it is strongly recommended to have a developer verify this.', ), 'wp_create_user' => array( 'severity' => 'critical', 'title' => 'User Creation Function', 'explanation' => 'References a WordPress user-creation function in an unexpected location. May be legitimate plugin data, but worth a developer check given the sensitivity.', ), 'add_action(\'init\',\'create' => array( 'severity' => 'critical', 'title' => 'Backdoor Hook', 'explanation' => 'Contains an init-hook pattern that could, in some cases, be used to run code on every page load. Often legitimate, but recommended for a developer to confirm.', ), // Hidden iframes (only suspicious ones) 'visibility:hidden' => array( 'severity' => 'high', 'title' => 'Hidden Element', 'explanation' => 'Contains a hidden element. Frequently legitimate (layout, tracking), but hidden content can also load unwanted code. Worth checking if you do not recognise it.', ), 'display:none' => array( 'severity' => 'medium', 'title' => 'Hidden Element', 'explanation' => 'Contains a hidden element. Usually harmless, but occasionally used to conceal content. A developer can confirm if it is expected.', 'min_context' => ' array( 'severity' => 'critical', 'title' => 'Shell Execution', 'explanation' => 'Matches a shell-command execution pattern. This can appear inside stored file paths or settings (a false alarm), but real shell execution in content is dangerous. Strongly recommended to have a developer verify this entry.', ), 'base64_decode' => array( 'severity' => 'high', 'title' => 'Base64 Decode', 'explanation' => 'Decodes base64 data. Common in legitimate code, but also used to hide payloads. Have a developer review it if the content is unfamiliar.', ), 'passthru' => array( 'severity' => 'critical', 'title' => 'Command Passthru', 'explanation' => 'Matches a system-command pattern (such as passthru). This often appears harmlessly inside stored file paths or plugin data (a common false alarm), but genuine command execution would be dangerous. Recommended to have a developer confirm this entry.', ), ); /** * Suspicious option names - known malware indicators */ private static $suspicious_options = array( 'wp_zxcvbn', 'wp_roofs', 'wp_checksum', 'class_generic_support', 'widget_generic_support', 'wp_check_hash', ); /** * Scan database for suspicious content * * @return array Scan results */ public static function scan() { global $wpdb; $results = array( 'scanned_at' => current_time( 'mysql' ), 'total_issues' => 0, 'options' => array(), 'posts' => array(), 'postmeta' => array(), 'users' => array(), 'summary' => '', 'coverage' => array(), 'coverage_complete' => true, 'incomplete' => false, ); // Each scan_* helper now returns a struct: // array( 'findings' => array, 'eligible'|'scanned'|'skipped' => int, 'complete' => bool ) // We unpack 'findings' into the existing result keys so the total_issues // math below is unchanged, and aggregate honest coverage metadata. $options_res = self::scan_options(); $posts_res = self::scan_posts(); $postmeta_res = self::scan_postmeta(); $users_res = self::scan_users(); $results['options'] = $options_res['findings']; $results['posts'] = $posts_res['findings']; $results['postmeta'] = $postmeta_res['findings']; $results['users'] = $users_res['findings']; // GP-REL-008: per-table coverage so the UI can never claim a complete // (all-clear) scan when rows were left unscanned. $results['coverage'] = array( 'wp_options' => array( 'scanned' => (int) $options_res['scanned'], 'skipped' => (int) $options_res['skipped'], // ACG-032-013(b): own-prefix options skipped from content matching are // disclosed here (NOT counted as scanned, and NOT forcing incomplete). 'policy_skipped' => isset( $options_res['policy_skipped'] ) ? (int) $options_res['policy_skipped'] : 0, 'complete' => (bool) $options_res['complete'], ), 'wp_posts' => array( 'scanned' => (int) $posts_res['scanned'], 'skipped' => (int) $posts_res['skipped'], 'complete' => (bool) $posts_res['complete'], ), 'wp_postmeta' => array( 'scanned' => (int) $postmeta_res['scanned'], 'skipped' => (int) $postmeta_res['skipped'], 'complete' => (bool) $postmeta_res['complete'], ), 'wp_users' => array( 'scanned' => (int) $users_res['scanned'], 'skipped' => (int) $users_res['skipped'], 'complete' => (bool) $users_res['complete'], ), ); $results['coverage_complete'] = ( $options_res['complete'] && $posts_res['complete'] && $postmeta_res['complete'] && $users_res['complete'] ); // Mirror the file-integrity 'incomplete' convention for the dashboard widget. $results['incomplete'] = ! $results['coverage_complete']; $total_skipped = (int) $options_res['skipped'] + (int) $posts_res['skipped'] + (int) $postmeta_res['skipped'] + (int) $users_res['skipped']; // Calculate totals $results['total_issues'] = count( $results['options'] ) + count( $results['posts'] ) + count( $results['postmeta'] ) + count( $results['users'] ); // Generate summary — NEVER claim "complete" / all-clear on partial coverage. if ( $results['total_issues'] === 0 && $results['coverage_complete'] ) { $results['summary'] = __( '✅ Database scan complete. No suspicious content found.', 'ai-cyberguard' ); } elseif ( $results['total_issues'] === 0 && ! $results['coverage_complete'] ) { $results['summary'] = sprintf( /* translators: %d is the number of database rows that could not be checked */ __( '⚠️ Database scan PARTIAL — %d rows could not be checked. No suspicious content found in the rows that were scanned. Re-run to scan the rest.', 'ai-cyberguard' ), $total_skipped ); } else { $results['summary'] = sprintf( /* translators: %d is the number of suspicious database entries found */ __( '⚠️ Found %d suspicious entries in database!', 'ai-cyberguard' ), $results['total_issues'] ); } return $results; } /** * Scan wp_options table */ private static function scan_options() { global $wpdb; $findings = array(); // ACG-033-009 (audit 2026-06-20): the old broad PREFIX skip // (guardpress_* / ai_cyberguard_*) was unsafe — "prefix possession is not // authenticity". An attacker can write an option NAMED like ours // (e.g. `guardpress_attacker_payload`) and hide a PHP/shell payload in it; // under the prefix rule that row was auto-trusted (policy_skipped) yet the // summary could still say "complete / no suspicious content". We now skip // ONLY an EXACT allowlist of the specific option NAMES the plugin // legitimately writes that store malware SIGNATURE / pattern-matching DATA, // which would self-flag if content-scanned (false positive on our own data). // Every OTHER option — including unknown guardpress_*/ai_cyberguard_*-looking // names — is scanned normally, so a payload planted in a plugin-looking // option name is now DETECTED and coverage is honest. If a key cannot be // positively identified as one of these known signature-bearing options, // it is SCANNED. // // Why exactly these keys (sources): // - guardpress_threat_signatures_v2 / _v1 : OPTION_SIGNATURES — the threat-feed // signature cache (raw malware regex/tokens, ~2.3MB). class-threat-feed.php. // - guardpress_malware_hashes_v2 / _v1 : OPTION_MALWARE_HASHES — the plugin's // own malware hash database. class-threat-feed.php. // - guardpress_smart_signatures : OPTION_SIGNATURES of the smart feed — // stores raw detection patterns (literally contains tokens like the // eval-open / wp_insert_user). class-smart-threat-feed.php. // - guardpress_signature_stats : OPTION_SIGNATURE_STATS — per-signature // stats keyed by signature id/pattern. class-smart-threat-feed.php. // - guardpress_threat_api_error / guardpress_api_error_cache : feed API error // caches that can echo back a REJECTED signature snippet. class-threat-feed.php. // These are the plugin's own verified data; scanning them would self-FP, so // they stay skipped — but they are disclosed as policy_skipped (informational) // and do NOT force coverage incomplete (a normal install always has them). // NOTE: the verdict cache and checksums cache are stored in FILES // (GuardPress_File_Storage), NOT in wp_options, so they need no entry here. $own_signature_option_names = array( 'guardpress_threat_signatures_v2' => true, 'guardpress_threat_signatures_v1' => true, 'guardpress_malware_hashes_v2' => true, 'guardpress_malware_hashes_v1' => true, 'guardpress_smart_signatures' => true, 'guardpress_signature_stats' => true, 'guardpress_threat_api_error' => true, 'guardpress_api_error_cache' => true, ); // GP-REL-008: deterministic keyset pagination to end-of-table. // Previously a single unordered "LIMIT 5000" left every eligible row // beyond the window invisible while the summary still claimed // "complete". We now walk the PRIMARY KEY (option_id) in ordered // pages until a short page proves end-of-table, bounded by a hard // per-table safety budget. The WHERE filters are preserved exactly so // detection coverage is a strict superset of the old behaviour. $last_id = 0; $scanned = 0; $policy_skipped = 0; // ACG-032-013(b): own-prefix options NOT content-scanned (honest disclosure) $complete = true; while ( true ) { $wpdb->last_error = ''; // ACG-031-008 (audit 2026-06-20): the lower LENGTH bound (> 50) is REMOVED — // it created a blind zone where a short malicious payload (e.g. the 25-byte // `prepare // ACG-032-013(c) (audit 2026-06-20): the `_transient_`/`_site_transient_` // exclusions are REMOVED. Transients are attacker-writable and held no // plugin signatures, so they were a silent blind zone; they are now scanned // like any other option (self-FP risk is handled by the own-prefix policy // skip below, not by skipping transients). $options = $wpdb->get_results( $wpdb->prepare( "SELECT option_id, option_name, option_value FROM {$wpdb->options} WHERE LENGTH(option_value) < 100000 AND option_id > %d ORDER BY option_id ASC LIMIT %d", $last_id, self::BATCH ) ); // ACG-031-007 (audit 2026-06-20): a DB error (null/false result or a set // last_error) is NOT end-of-table — stop and mark coverage incomplete so a // permission/timeout/fault is never reported as a clean "scan complete". if ( null === $options || false === $options || '' !== $wpdb->last_error ) { $complete = false; break; } if ( empty( $options ) ) { break; // true end-of-table (genuine empty page) } foreach ( $options as $option ) { $last_id = (int) $option->option_id; // ACG-033-009 (audit 2026-06-20): skip from content matching ONLY the // EXACT known signature-bearing own-option names (see allowlist above). // Those legitimately store the plugin's malware signature/pattern data and // would self-flag if scanned, so they stay skipped — disclosed as // policy_skipped (informational), NOT counted as scanned, and NOT forcing // coverage incomplete (a normal install always has them). EVERY other // option — including attacker-chosen guardpress_*/ai_cyberguard_*-looking // names — is scanned normally, so a payload planted in such a name is now // DETECTED instead of being silently auto-trusted. // SA-A5-01 (self-audit 2026-06-20): name possession is NOT authenticity. The // plugin always writes these options as WordPress-SERIALIZED data. An attacker // who can write a wp_options row (SQLi elsewhere, compromised admin, direct DB) // could otherwise plant a RAW payload under one of these reserved names and have // it auto-trusted → a green all-clear over live malicious content. Skip ONLY when // the value carries the authentic serialized shape; anything else (e.g. a raw // `option_name ] ) && self::is_authentic_own_option( $option->option_name, $option->option_value ) ) { $policy_skipped++; continue; } $scanned++; $issues = self::check_content( $option->option_value ); if ( ! empty( $issues ) ) { $findings[] = array( 'table' => 'wp_options', 'id' => $option->option_id, 'name' => $option->option_name, 'value_preview' => self::get_preview( $option->option_value ), 'issues' => $issues, ); } // Check for suspicious option names foreach ( self::$suspicious_options as $suspicious ) { if ( stripos( $option->option_name, $suspicious ) !== false ) { $findings[] = array( 'table' => 'wp_options', 'id' => $option->option_id, 'name' => $option->option_name, 'value_preview' => self::get_preview( $option->option_value ), 'issues' => array( array( 'pattern' => $suspicious, 'severity' => 'medium', 'title' => __( 'Suspicious Option Name', 'ai-cyberguard' ), 'explanation' => __( 'This option name is associated with known malware.', 'ai-cyberguard' ), ), ), ); } } } // Short page => end-of-table reached. if ( count( $options ) < self::BATCH ) { break; } // Safety budget: stop before running forever on a hostile table, // and report the remaining eligible rows as skipped (NOT complete). if ( $scanned >= self::MAX_ROWS_OPTIONS ) { $complete = false; break; } } $skipped = 0; if ( ! $complete ) { $wpdb->last_error = ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- COUNT probe to honestly report unscanned rows beyond the safety budget $cnt = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->options} WHERE LENGTH(option_value) < 100000 AND option_id > %d", $last_id ) ); $skipped = ( null === $cnt || '' !== $wpdb->last_error ) ? 0 : (int) $cnt; } // ACG-031-008: oversize pass. Rows excluded by the upper LENGTH bound are still // scanned — streamed in 256 KiB chunks (with overlap) so memory stays bounded — // instead of being a silent blind zone. Any beyond the bounded cap are counted // as skipped and mark coverage incomplete. // ACG-032-013(c): transients are no longer excluded from the oversize pass either. $ov = self::scan_oversize( $wpdb->options, 'option_id', 'option_value', 'wp_options', 100000, '' ); foreach ( $ov['findings'] as $f ) { $findings[] = $f; } $scanned += $ov['scanned']; $skipped += $ov['skipped']; if ( ! $ov['complete'] ) { $complete = false; } return array( 'findings' => $findings, 'scanned' => $scanned, 'skipped' => $skipped, 'policy_skipped' => $policy_skipped, // ACG-032-013(b): own-prefix options not content-scanned 'complete' => $complete, ); } /** * ACG-031-008 (audit 2026-06-20): stream-scan rows whose value exceeds the page * LENGTH cap, in overlapping SUBSTRING chunks, so an oversize malicious payload is * inspected without ever loading the whole cell into PHP memory. Bounded by * MAX_OVERSIZE_ROWS; any beyond that are counted as skipped (coverage incomplete). * * @param string $table Full table name ($wpdb->options / $wpdb->posts / $wpdb->postmeta). * @param string $pk Primary-key column. * @param string $col Value column to scan. * @param string $label Human table label for findings. * @param int $min_len Rows with LENGTH(col) >= this are "oversize". * @param string $extra Extra WHERE (no leading AND), or ''. * @return array{findings:array,scanned:int,skipped:int,complete:bool} */ private static function scan_oversize( $table, $pk, $col, $label, $min_len, $extra = '' ) { global $wpdb; $findings = array(); $scanned = 0; $skipped = 0; $complete = true; $where = "LENGTH({$col}) >= " . (int) $min_len . ( '' !== $extra ? " AND {$extra}" : '' ); $wpdb->last_error = ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- bounded list of oversize-row primary keys; literals are integer-cast / static $rows = $wpdb->get_results( $wpdb->prepare( "SELECT {$pk} AS gp_pk FROM {$table} WHERE {$where} ORDER BY {$pk} ASC LIMIT %d", self::MAX_OVERSIZE_ROWS + 1 ) ); if ( null === $rows || false === $rows || '' !== $wpdb->last_error ) { return array( 'findings' => $findings, 'scanned' => 0, 'skipped' => 0, 'complete' => false ); } $ids = array(); foreach ( (array) $rows as $r ) { if ( is_object( $r ) && isset( $r->gp_pk ) ) { $ids[] = (int) $r->gp_pk; } } if ( count( $ids ) > self::MAX_OVERSIZE_ROWS ) { $complete = false; // more oversize rows than we will scan this run $ids = array_slice( $ids, 0, self::MAX_OVERSIZE_ROWS ); // SA-A5-02 (self-audit 2026-06-20): report the REAL count left unscanned (one COUNT), // not a flat "1" — so the "%d rows could not be checked" summary is honest. $where // contains only an integer-cast LENGTH bound + internal $extra, so it is safe inline. $wpdb->last_error = ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- COUNT of oversize rows; WHERE has only integer-cast/static literals $oversize_total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE {$where}" ); $skipped += ( $oversize_total > self::MAX_OVERSIZE_ROWS ) ? ( $oversize_total - self::MAX_OVERSIZE_ROWS ) : 1; } foreach ( $ids as $id ) { $res = self::scan_large_value( $table, $pk, $col, $id ); if ( isset( $res['__error__'] ) ) { $complete = false; continue; } $scanned++; if ( ! empty( $res ) ) { $findings[] = array( 'table' => $label, 'id' => $id, 'name' => '(oversize value)', 'value_preview' => '', 'issues' => $res ); } } return array( 'findings' => $findings, 'scanned' => $scanned, 'skipped' => $skipped, 'complete' => $complete ); } /** Stream one oversize cell via SUBSTRING(), scanning each chunk; overlap covers boundary splits. */ private static function scan_large_value( $table, $pk, $col, $id ) { global $wpdb; $issues = array(); $offset = 0; // ACG-033-010 (audit 2026-06-20): CONTEXT-dependent rules need two tokens in the // SAME string (e.g. 'display:none' only flags when combined with ' requires ' requires ' array( ' array( ' bool: the pattern's own token seen somewhere in the row $ctx_ctx = array(); // pattern => bool: at least one required context token seen somewhere foreach ( $ctx_rules as $p => $ctx_tokens ) { $ctx_own[ $p ] = false; $ctx_ctx[ $p ] = false; } do { $wpdb->last_error = ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- bounded streamed read of one flagged oversize cell $chunk = $wpdb->get_var( // ───────────────────────────────────────────────────────────────────────────────────── // ACG-149-157 (adversarial audit, MySQL-only — invisible on SQLite): // MySQL/MariaDB SUBSTRING() counts CHARACTERS, while the loop guard below counts BYTES // with strlen(). On a multibyte value the two disagree: after the final chunk the guard // stayed true, the next read ran past the end, SUBSTRING returned '', get_var() turned // that into null, and the function returned __error__ — THROWING AWAY EVERY FINDING // COLLECTED FROM THE EARLIER CHUNKS. // Proven with two rows of IDENTICAL byte length (300,005) carrying the same payload: // the ASCII one reported "PHP Code in Database (critical)"; the HEBREW one lost the // finding entirely. That matters here specifically — this plugin's own author runs a // Hebrew site, and page-builder JSON on any non-English site sits in the affected range. // CAST(... AS BINARY) makes SUBSTRING operate on BYTES, so the offsets, the CHUNK_BYTES // window and the strlen() guard all finally speak the same unit. $wpdb->prepare( "SELECT SUBSTRING(CAST({$col} AS BINARY), %d, %d) FROM {$table} WHERE {$pk} = %d", $offset + 1, self::CHUNK_BYTES, (int) $id ) ); if ( null === $chunk || '' !== $wpdb->last_error ) { return array( '__error__' => true ); } if ( '' === $chunk ) { break; } $found = self::check_content( $chunk ); if ( ! empty( $found ) ) { foreach ( $found as $f ) { $key = isset( $f['pattern'] ) ? $f['pattern'] : count( $issues ); $issues[ $key ] = $f; // dedupe identical patterns across chunks } } // ACG-033-010: update cross-chunk feature flags for context rules (booleans only). foreach ( $ctx_rules as $p => $ctx_tokens ) { if ( ! $ctx_own[ $p ] && stripos( $chunk, $p ) !== false ) { $ctx_own[ $p ] = true; } if ( ! $ctx_ctx[ $p ] ) { foreach ( $ctx_tokens as $ct ) { if ( stripos( $chunk, $ct ) !== false ) { $ctx_ctx[ $p ] = true; break; } } } } $offset += ( self::CHUNK_BYTES - self::CHUNK_OVERLAP ); } while ( strlen( (string) $chunk ) >= self::CHUNK_BYTES ); // ACG-033-010: after the last chunk, emit any context rule whose own token AND a // required context token both appeared SOMEWHERE in the row but were split across // chunks (so per-chunk detection above did not already record them). This makes // oversize coverage honest for long-range contextual payloads. foreach ( $ctx_rules as $p => $ctx_tokens ) { if ( $ctx_own[ $p ] && $ctx_ctx[ $p ] && ! isset( $issues[ $p ] ) ) { if ( isset( self::$db_patterns[ $p ] ) ) { $info = self::$db_patterns[ $p ]; $issues[ $p ] = array( 'pattern' => $p, 'severity' => $info['severity'], 'title' => $info['title'], 'explanation' => $info['explanation'], ); } } } return array_values( $issues ); } /** * Scan wp_posts table */ private static function scan_posts() { global $wpdb; $findings = array(); // GP-REL-008: keyset pagination over the PRIMARY KEY (ID) to end-of-table, // bounded by a per-table safety budget. WHERE filters preserved exactly. $last_id = 0; $scanned = 0; $complete = true; while ( true ) { $wpdb->last_error = ''; // ACG-031-008: lower bound (> 100) removed — short malicious post_content is no // longer a blind zone; check_content() applies its own length floor. // ACG-032-016 (audit 2026-06-20): post_content is LONGTEXT and was previously // selected with NO upper byte ceiling, so a few huge bodies in a 2000-row page // could exhaust memory/time. We now mirror scan_options/scan_postmeta: bound the // bulk page to LENGTH(post_content) < 100000 and stream oversize bodies separately // via the existing scan_oversize() helper. (The lower-bound removal from // ACG-031-008 is preserved — no lower bound is re-added.) // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- the malware scanner must read live, uncached post rows directly to detect injected content; cursor + limit are bound via $wpdb->prepare $posts = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_title, post_content, post_type, post_status FROM {$wpdb->posts} WHERE post_status != 'trash' AND LENGTH(post_content) < 100000 AND ID > %d ORDER BY ID ASC LIMIT %d", $last_id, self::BATCH ) ); // ACG-031-007: SQL error is not end-of-table. if ( null === $posts || false === $posts || '' !== $wpdb->last_error ) { $complete = false; break; } if ( empty( $posts ) ) { break; } foreach ( $posts as $post ) { $last_id = (int) $post->ID; $scanned++; $issues = self::check_content( $post->post_content ); if ( ! empty( $issues ) ) { $findings[] = array( 'table' => 'wp_posts', 'id' => $post->ID, 'name' => $post->post_title ?: '(no title)', 'type' => $post->post_type, 'status' => $post->post_status, 'value_preview' => self::get_preview( $post->post_content ), 'issues' => $issues, 'edit_link' => admin_url( 'post.php?post=' . $post->ID . '&action=edit' ), ); } } if ( count( $posts ) < self::BATCH ) { break; } if ( $scanned >= self::MAX_ROWS_POSTS ) { $complete = false; break; } } $skipped = 0; if ( ! $complete ) { $wpdb->last_error = ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- COUNT probe to honestly report unscanned rows beyond the safety budget $cnt = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status != 'trash' AND LENGTH(post_content) < 100000 AND ID > %d", $last_id ) ); $skipped = ( null === $cnt || '' !== $wpdb->last_error ) ? 0 : (int) $cnt; } // ACG-032-016: oversize post bodies (>= 100000) are no longer a blind zone — // streamed in bounded 256 KiB chunks via the existing helper so a huge LONGTEXT // cannot exhaust memory yet injected content in it is still detected. $ov = self::scan_oversize( $wpdb->posts, 'ID', 'post_content', 'wp_posts', 100000, "post_status != 'trash'" ); foreach ( $ov['findings'] as $f ) { $findings[] = $f; } $scanned += $ov['scanned']; $skipped += $ov['skipped']; if ( ! $ov['complete'] ) { $complete = false; } return array( 'findings' => $findings, 'scanned' => $scanned, 'skipped' => $skipped, 'complete' => $complete, ); } /** * Scan wp_postmeta table */ private static function scan_postmeta() { global $wpdb; $findings = array(); // GP-REL-008: keyset pagination over the PRIMARY KEY (meta_id) to // end-of-table, bounded by a per-table safety budget. WHERE filters // preserved exactly. $last_id = 0; $scanned = 0; $complete = true; while ( true ) { $wpdb->last_error = ''; // ACG-031-008: lower bound (> 100) removed (short payloads now scanned via // check_content's own floor). Upper bound kept for page memory; oversize rows // streamed separately below. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- the malware scanner must read live, uncached postmeta rows directly to detect injected content; cursor + limit are bound via $wpdb->prepare // ACG-032-013(c) (audit 2026-06-20): the `_edit_`/`_wp_attachment_` exclusions // are REMOVED. This postmeta is attacker-writable and holds no plugin // signatures, so it was a silent blind zone; injected content there is now // detected like any other meta row. $metas = $wpdb->get_results( $wpdb->prepare( "SELECT meta_id, post_id, meta_key, meta_value FROM {$wpdb->postmeta} WHERE LENGTH(meta_value) < 50000 AND meta_id > %d ORDER BY meta_id ASC LIMIT %d", $last_id, self::BATCH ) ); // ACG-031-007: SQL error is not end-of-table. if ( null === $metas || false === $metas || '' !== $wpdb->last_error ) { $complete = false; break; } if ( empty( $metas ) ) { break; } foreach ( $metas as $meta ) { $last_id = (int) $meta->meta_id; $scanned++; $issues = self::check_content( $meta->meta_value ); if ( ! empty( $issues ) ) { $findings[] = array( 'table' => 'wp_postmeta', 'id' => $meta->meta_id, 'post_id' => $meta->post_id, 'name' => $meta->meta_key, 'value_preview' => self::get_preview( $meta->meta_value ), 'issues' => $issues, ); } } if ( count( $metas ) < self::BATCH ) { break; } if ( $scanned >= self::MAX_ROWS_POSTMETA ) { $complete = false; break; } } $skipped = 0; if ( ! $complete ) { $wpdb->last_error = ''; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- COUNT probe to honestly report unscanned rows beyond the safety budget $cnt = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE LENGTH(meta_value) < 50000 AND meta_id > %d", $last_id ) ); $skipped = ( null === $cnt || '' !== $wpdb->last_error ) ? 0 : (int) $cnt; } // ACG-031-008: oversize postmeta values (>= 50000) streamed in chunks. // ACG-032-013(c): _edit_/_wp_attachment_ no longer excluded from the oversize pass. $ov = self::scan_oversize( $wpdb->postmeta, 'meta_id', 'meta_value', 'wp_postmeta', 50000, '' ); foreach ( $ov['findings'] as $f ) { $findings[] = $f; } $scanned += $ov['scanned']; $skipped += $ov['skipped']; if ( ! $ov['complete'] ) { $complete = false; } return array( 'findings' => $findings, 'scanned' => $scanned, 'skipped' => $skipped, 'complete' => $complete, ); } /** * Scan for suspicious users */ private static function scan_users() { global $wpdb; $findings = array(); // GP-REL-008: bound the admin enumeration so a site with a huge number // of administrator accounts cannot run unbounded. We take the most // recently registered admins (the relevant window for "recently created // backdoor account" detection) and, if we hit the cap, report the // remainder as skipped + coverage incomplete. $admins = get_users( array( 'role' => 'administrator', 'orderby' => 'registered', 'order' => 'DESC', 'number' => self::MAX_USERS, ) ); $complete = true; $skipped = 0; if ( count( $admins ) >= self::MAX_USERS ) { // We fetched a full cap — there may be more admins we did not examine. $total_admins = 0; $have_total = false; if ( function_exists( 'count_users' ) ) { $counts = count_users(); if ( isset( $counts['avail_roles']['administrator'] ) ) { $total_admins = (int) $counts['avail_roles']['administrator']; $have_total = true; } } // SA-A5-03 (self-audit 2026-06-20): fail CLOSED on an unknown total. With a reliable // total, report exactly how many admins were skipped. But if count_users() cannot give // the admin count (filtered / empty avail_roles / large multisite), do NOT default to // 0 and claim "complete" — an older (501st+) backdoor admin would be invisible AND // the scan would say complete. Mark coverage incomplete instead. if ( $have_total && $total_admins > self::MAX_USERS ) { $complete = false; $skipped = $total_admins - self::MAX_USERS; } elseif ( ! $have_total ) { $complete = false; // unknown total after a cap hit → cannot honestly claim complete } } foreach ( $admins as $admin ) { $suspicious = false; $reasons = array(); // Check for suspicious email patterns $email = $admin->user_email; $suspicious_domains = array( 'tempmail', 'guerrilla', 'mailinator', '10minute', 'throwaway' ); foreach ( $suspicious_domains as $domain ) { if ( stripos( $email, $domain ) !== false ) { $suspicious = true; $reasons[] = __( 'Temporary/disposable email address', 'ai-cyberguard' ); break; } } // Check for generic usernames $generic_names = array( 'admin', 'administrator', 'wordpress', 'support', 'manager' ); foreach ( $generic_names as $name ) { if ( strtolower( $admin->user_login ) === $name || strtolower( $admin->user_login ) === $name . '1' ) { // Don't flag if it's the only admin or was created long ago $created = strtotime( $admin->user_registered ); $week_ago = time() - ( 7 * 24 * 60 * 60 ); if ( $created > $week_ago ) { $suspicious = true; $reasons[] = __( 'Generic username created recently', 'ai-cyberguard' ); } break; } } // Check for users with no posts (possible backdoor account). // GP-REL-008: "no activity" alone is NOT suspicious — a brand-new // legitimate admin on a fresh install has no posts. Previously this // lone low note produced a finding (contradictory false positive on // clean sites). Only ADD it as corroboration when another genuine // signal (disposable email / recent generic username) already // flagged the account; never let it stand on its own. if ( $suspicious ) { $post_count = count_user_posts( $admin->ID ); $created = strtotime( $admin->user_registered ); $month_ago = time() - ( 30 * 24 * 60 * 60 ); if ( $post_count === 0 && $created > $month_ago ) { $reasons[] = __( 'Admin account with no activity', 'ai-cyberguard' ); } } // Only record a finding when the account is genuinely suspicious. // (A high-signal reason always sets $suspicious=true above, so this // both removes the fresh-install false positive and preserves every // real backdoor-account detection.) if ( $suspicious && ! empty( $reasons ) ) { $findings[] = array( 'table' => 'wp_users', 'id' => $admin->ID, 'name' => $admin->user_login, 'email' => $admin->user_email, 'registered' => $admin->user_registered, 'issues' => array( array( 'severity' => 'high', 'title' => __( 'Suspicious Admin Account', 'ai-cyberguard' ), 'explanation' => implode( '. ', $reasons ), ), ), 'edit_link' => admin_url( 'user-edit.php?user_id=' . $admin->ID ), ); } } return array( 'findings' => $findings, 'scanned' => count( $admins ), 'skipped' => $skipped, 'complete' => $complete, ); } /** * SA-A5-01 (self-audit 2026-06-20): does an allowlisted own-option value carry the AUTHENTIC * shape the plugin writes (a WordPress-serialized value)? The plugin stores its signature/ * hash/stats options via update_option() with arrays, so a genuine value is always * PHP-serialized. A raw payload an attacker planted under one of these reserved names (e.g. * ` false ) ); if ( ! is_array( $decoded ) ) { return false; } // ACG-036-005 (audit 2026-06-20, HIGH): the serialized-array shape is NECESSARY but NOT // SUFFICIENT — an attacker who can write a wp_options row could store a serialized ARRAY with a // malicious string LEAF under a reserved name and have it auto-trusted (green all-clear over // live malware). Require a keyed integrity MAC that matches THIS exact value. Only data the // plugin itself wrote and stamped (see stamp_own_option) carries a valid MAC, and the MAC key // comes from a wp-config salt an attacker writing wp_options cannot read — so a planted payload // (no valid MAC) falls through to a full content scan and is DETECTED. $stored = (string) get_option( self::own_option_mac_key( $name ), '' ); if ( '' === $stored ) { return false; // not proven ours → scan it } return hash_equals( $stored, self::own_option_mac( $name, $value ) ); } /** * ACG-036-005: reserved option names the plugin authenticates with a MAC (mirrors the scan * allowlist). Kept in one place so stamp/affirm and the scan check never drift. * * @return string[] */ private static function own_option_names() { return array( 'guardpress_threat_signatures_v2', 'guardpress_threat_signatures_v1', 'guardpress_malware_hashes_v2', 'guardpress_malware_hashes_v1', 'guardpress_smart_signatures', 'guardpress_signature_stats', 'guardpress_threat_api_error', 'guardpress_api_error_cache', ); } /** * ACG-036-005: per-install MAC secret. Keyed to a wp-config salt constant (filesystem, NOT the * database), so an attacker who can only WRITE wp_options cannot read it to forge a MAC. Falls * back to a one-time random DB secret only when no salt constant is defined (very rare) — weaker, * but still far above pure name-trust. * * @return string */ private static function own_option_secret() { foreach ( array( 'SECRET_AUTH_KEY', 'AUTH_KEY', 'AUTH_SALT', 'NONCE_SALT', 'LOGGED_IN_KEY' ) as $c ) { if ( defined( $c ) ) { $v = (string) constant( $c ); if ( '' !== $v && false === strpos( $v, 'put your unique phrase here' ) ) { return 'gpownmac|' . $v; } } } $k = (string) get_option( 'guardpress_own_data_secret', '' ); if ( '' === $k ) { $k = function_exists( 'wp_generate_password' ) ? wp_generate_password( 64, true, true ) : substr( hash( 'sha256', uniqid( '', true ) ), 0, 64 ); update_option( 'guardpress_own_data_secret', $k, false ); } return 'gpownmac|' . $k; } /** ACG-036-005: companion option name holding the MAC for $name. */ private static function own_option_mac_key( $name ) { return $name . '::gpmac'; } /** ACG-036-005: compute the keyed MAC for an exact serialized option value. */ private static function own_option_mac( $name, $value ) { return hash_hmac( 'sha256', (string) $name . '|' . (string) $value, self::own_option_secret() ); } /** * ACG-036-005: stamp the CURRENT value of one of the plugin's own options with its MAC. Called by * the feed/stats writers immediately AFTER they update_option() a GENUINE value, and by the * one-time affirm on upgrade. NEVER call this from the scan path — it would trust whatever is * currently stored, including an attacker payload. The MAC is computed over the SERIALIZED bytes * the database scanner reads from wp_options. * * @param string $name option name */ public static function stamp_own_option( $name ) { if ( ! in_array( $name, self::own_option_names(), true ) ) { return; } $val = get_option( $name, null ); if ( null === $val || false === $val ) { return; } $ser = maybe_serialize( $val ); // same bytes the scanner sees as option_value update_option( self::own_option_mac_key( $name ), self::own_option_mac( $name, $ser ), false ); } /** * ACG-037-003 (audit 2026-06-21, HIGH): this used to STAMP the current stored value of every * reserved option on admin_init (version-gated). That was a SIGNING ORACLE: the version-gate * option is itself attacker-writable, so an attacker who can write wp_options could plant a * malicious serialized array under a reserved name AND reset the gate, and the next admin request * would compute a valid secret-keyed MAC over the attacker value — turning it "authentic" and * bypassing the scan. It NEVER signs current state now. Instead, ONE-TIME per release, it PURGES * any reserved option that is NOT already authentically stamped (no valid MAC): genuine caches are * harmlessly re-derived by their trusted writers (which stamp at write time), and an attacker's * unstamped payload is removed rather than scanned-as-FP or, worse, blessed. Purging can never * bless attacker data, so the attacker-writable gate only ever allows a harmless re-purge. * MUST NOT run inside the scan path. */ public static function affirm_own_options() { $ver = defined( 'GUARDPRESS_VERSION' ) ? (string) GUARDPRESS_VERSION : '1'; $done = (string) get_option( 'guardpress_own_data_affirmed', '' ); if ( $done === $ver ) { return; } foreach ( self::own_option_names() as $name ) { $val = get_option( $name, null ); if ( null === $val || false === $val ) { continue; } // Keep ONLY values that already carry a valid MAC (genuine, stamped by a trusted writer). // Everything else (unstamped genuine cache OR attacker payload) is removed — never signed. if ( ! self::is_authentic_own_option( $name, maybe_serialize( $val ) ) ) { delete_option( $name ); delete_option( self::own_option_mac_key( $name ) ); } } update_option( 'guardpress_own_data_affirmed', $ver, false ); } /** * Check content for suspicious patterns */ private static function check_content( $content ) { $issues = array(); // Unserialize if needed. // SECURITY: 'allowed_classes' => false prevents PHP object injection / gadget-chain attacks. // We only accept arrays and scalars — never objects — from untrusted DB content. if ( is_serialized( $content ) ) { // Corrupt/truncated serialized data (e.g. a half-written giant transient) makes // unserialize() emit a warning in PHP 8 that a leading @ does not suppress; a no-op error // handler keeps the scan output clean. allowed_classes=false stays (object-injection safe), // and the value is still scanned as raw text below, so detection is unchanged. set_error_handler( static function () { return true; } ); $unserialized = unserialize( $content, array( 'allowed_classes' => false ) ); restore_error_handler(); if ( is_array( $unserialized ) ) { // FIX R-2 (audit 2026-05-25): reverted L-17 change. The L-17 // print_r → wp_json_encode swap was technically "more // deterministic" but BROKE TWO downstream false-positive // suppressors: // 1) Line ~499 uses `/["\']base64_decode["\']\s*=>/i` — // print_r yields `[base64_decode] => x`, JSON yields // `{"base64_decode":"x"}`, suppressor never matches JSON. // 2) Line ~478 uses `/\/\/.*eval\(|\/\*.*eval\(/` — // wp_json_encode escapes `/` to `\/` by default, breaking // this regex's literal `/` characters. // Result was a spike in false-positive DB scan findings on // legitimate plugins that store arrays with keys like // 'base64_decode' (very common in caching/options plugins). // print_r is the correct primitive for THIS specific text- // shaped pattern-matching use case. $content = print_r( $unserialized, true ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.prevent_path_disclosure_print_r, WordPress.PHP.DevelopmentFunctions.error_log_print_r } elseif ( is_string( $unserialized ) ) { $content = $unserialized; } } // ACG-032-013(a) (audit 2026-06-20): the old "< 20" floor was a blind zone. // Real payloads fit in well under 20 bytes (e.g. a short PHP phpinfo tag is // 18 bytes; the open-tag token is 5 bytes; the short-echo token is 3 bytes). // The floor is now the length of the SHORTEST detection token, so nothing // scannable is skipped, while still cheaply discarding values too short to // contain ANY token. static $min_token_len = null; if ( null === $min_token_len ) { $min_token_len = 5; // small, sound default (open-tag token and eval( are both 5) foreach ( self::$db_patterns as $tok => $unused ) { $len = strlen( $tok ); if ( $len > 0 && $len < $min_token_len ) { $min_token_len = $len; } } } if ( strlen( $content ) < $min_token_len ) { return $issues; } // Known safe patterns to skip $safe_patterns = array( 'application/ld+json', // Schema.org structured data 'application/json', // JSON content 'text/javascript', // Normal JS type declarations 'recaptcha', // Google reCAPTCHA 'googleapis.com', // Google APIs 'googletagmanager', // Google Tag Manager 'facebook.com/plugins', // Facebook embeds 'twitter.com/widgets', // Twitter embeds 'youtube.com/embed', // YouTube embeds 'vimeo.com/video', // Vimeo embeds 'maps.google.com', // Google Maps 'cdn.jsdelivr.net', // CDN 'cdnjs.cloudflare.com', // CDN 'unpkg.com', // CDN ); // FIX (audit 2026-06-10): SECURITY — the old code short-circuited here: // if the content contained ANY "safe" substring (e.g. youtube.com/embed), // it scanned ONLY critical patterns and returned, so an attacker could // hide every high/medium injection simply by appending a whitelisted URL // to their payload. The safe-pattern list is no longer used to SKIP // detection; the full pattern scan below runs unconditionally, and each // pattern keeps its own precise context checks (min_context, iframe/script // pairing) to control genuine false positives. foreach ( self::$db_patterns as $pattern => $info ) { if ( stripos( $content, $pattern ) !== false ) { // Check min_context requirement if ( isset( $info['min_context'] ) ) { if ( stripos( $content, $info['min_context'] ) === false ) { continue; // Skip if context not found } } // Additional false positive checks if ( $pattern === 'eval(' ) { // FIX (audit 2026-06-10): the old suppressor // `/\/\/.*eval\(|\/\*.*eval\(|\*.*eval\(/i` skipped eval() // whenever ANY '*' (e.g. a multiplication `$a * $b`) preceded // it, and the unbounded `.*` was a ReDoS risk. eval() in // stored DB content is almost always malicious — only skip it // when it is clearly inside a LINE comment AND no request // superglobal is anywhere in the content. $commented = preg_match( '~(?://|\#)[^\n]{0,120}eval\s*\(~i', $content ); $has_superglobal = preg_match( '~\$_(?:GET|POST|REQUEST|COOKIE|SERVER)~i', $content ); if ( $commented && ! $has_superglobal ) { continue; } } if ( $pattern === 'display:none' ) { // Only flag if combined with iframe or suspicious script if ( stripos( $content, '/i', $content ) ) { continue; } } $issues[] = array( 'pattern' => $pattern, 'severity' => $info['severity'], 'title' => $info['title'], 'explanation' => $info['explanation'], ); } } return $issues; } /** * Get preview of content */ private static function get_preview( $content, $length = 100 ) { $content = wp_strip_all_tags( $content ); $content = preg_replace( '/\s+/', ' ', $content ); if ( strlen( $content ) > $length ) { $content = substr( $content, 0, $length ) . '...'; } return $content; } /** * Get severity color */ public static function get_severity_color( $severity ) { $colors = array( 'critical' => '#dc2626', 'high' => '#ea580c', 'medium' => '#d97706', 'low' => '#0891b2', ); return isset( $colors[ $severity ] ) ? $colors[ $severity ] : '#6b7280'; } /** * Clean a specific option */ public static function delete_option( $option_id ) { global $wpdb; if ( ! current_user_can( 'manage_options' ) ) { return false; } return $wpdb->delete( $wpdb->options, array( 'option_id' => intval( $option_id ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- capability-gated cleanup write to remove a flagged malicious option; must hit the live table } }