info) */ public static function get_malware_hashes() { // BINLOG FIX (v8.2): Read from file instead of DB if ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'threat-malware-hashes', null, 'cache' ); if ( is_array( $loaded ) ) { return $loaded; } // Migration: try DB $db = get_option( self::OPTION_MALWARE_HASHES, array() ); if ( ! empty( $db ) ) { GuardPress_File_Storage::save( 'threat-malware-hashes', $db, 'cache' ); } return $db; } return get_option( self::OPTION_MALWARE_HASHES, array() ); } /** * Check if a file hash matches known malware * * @param string $hash MD5 hash of file * @return array|false Malware info or false if clean */ public static function check_hash( $hash ) { $hashes = self::get_malware_hashes(); $hash = strtolower( $hash ); if ( isset( $hashes[ $hash ] ) ) { return $hashes[ $hash ]; } return false; } /** * Check if update is needed based on license type * * @param int $last_update Timestamp of last update * @return bool */ private static function needs_update( $last_update ) { if ( empty( $last_update ) ) { return true; } $elapsed = time() - $last_update; // Minimum interval to prevent hammering if ( $elapsed < self::MIN_UPDATE_INTERVAL ) { return false; } // Determine update interval based on license $is_pro = class_exists( 'GuardPress_License' ) && GuardPress_License::is_pro(); $interval = $is_pro ? self::PRO_UPDATE_INTERVAL : self::FREE_UPDATE_INTERVAL; return $elapsed >= $interval; } /** * Fetch signatures from server * Fixed: Cache API errors to prevent log spam * * @return array|false */ private static function fetch_from_server() { // WP.org compliance: Only fetch from external server if user has opted in // This applies to both auto-updates AND manual updates if ( ! get_option( 'guardpress_threat_feed_enabled', false ) ) { return false; // User hasn't enabled external threat feed } // Check if we recently had an API error - don't retry for 24 hours $api_error = get_option( self::OPTION_API_ERROR_CACHE, array() ); if ( ! empty( $api_error ) && isset( $api_error['time'] ) ) { if ( ( time() - $api_error['time'] ) < self::API_ERROR_CACHE_INTERVAL ) { // Silently skip - already logged the first time return false; } } // Check license state - EXPIRED users don't get new threat intel // (as per license expiration spec: "Keep last known data") if ( class_exists( 'GuardPress_Freemius_License' ) ) { $state = GuardPress_Freemius_License::get_state(); if ( $state === 'expired' ) { // Keep last known data - don't fetch new updates (no log needed) return false; } } $is_pro = class_exists( 'GuardPress_License' ) && GuardPress_License::is_pro(); $license_type = $is_pro ? 'pro' : 'free'; // Get last update time for delta updates $last_update = get_option( self::OPTION_LAST_UPDATE, 0 ); $since = $last_update > 0 ? gmdate( 'Y-m-d H:i:s', $last_update ) : ''; // Build API URL with parameters $url = add_query_arg( array( 'license' => $license_type, 'version' => defined( 'GUARDPRESS_VERSION' ) ? GUARDPRESS_VERSION : '1.0.0', 'since' => $since, ), self::API_ENDPOINT ); // FIX v142-1 (v1.1.0, ε-FINDING-v141-3): Use v2-free per-installation // credentials instead of the v1 hardcoded-salt token. The v1 path // (token derived from `md5( site_url . [hardcoded_string] )`) was // architecturally insecure because the salt was world-readable in the // wp.org distribution. See {@see GuardPress_Free_Credentials} for the // registration flow. // // If the installation is not yet registered, attempt to register now. // On failure (network error, server rate-limit, etc.), cache the // error and return false; the next cron tick will retry. $plugin_version = defined( 'GUARDPRESS_VERSION' ) ? GUARDPRESS_VERSION : '1.0.0'; if ( ! class_exists( 'GuardPress_Free_Credentials' ) || ! GuardPress_Free_Credentials::ensure_registered() ) { self::cache_api_error( 'Authentication unavailable: registration pending' ); return false; } $auth_headers = GuardPress_Free_Credentials::build_headers( 'signatures' ); if ( null === $auth_headers ) { self::cache_api_error( 'Authentication unavailable: header build failed' ); return false; } $args = array( 'timeout' => 30, 'sslverify' => true, // hardening: prevent MITM on signature updates 'user-agent' => 'GuardPress/' . $plugin_version, 'headers' => array_merge( $auth_headers, array( 'Accept' => 'application/json', ) ), ); $response = wp_remote_get( $url, $args ); if ( is_wp_error( $response ) ) { self::cache_api_error( 'Connection failed: ' . $response->get_error_message() ); return false; } $code = wp_remote_retrieve_response_code( $response ); if ( $code !== 200 ) { self::cache_api_error( 'Server returned HTTP ' . $code ); return false; } $body = wp_remote_retrieve_body( $response ); // FIX V137-FREE-PORT-GP-128-11 (May 2026, mirrors PRO V128-01 / // V136-GP-128-11): verify the server's HMAC response signature // BEFORE json_decode so a CA-compromise / MITM-tampered signature // payload can never reach the parser. This matters more here than // on AI status because the parsed payload becomes the local malware- // detection signature set — an attacker who can rewrite the body // could weaken or poison detection. Permissive default — see // STRICT_RESPONSE_SIG in class-free-credentials.php. // GP-REL-014 (audit 2026-06-19): the detection-feed payload becomes the local malware // signature set, so it MUST be signed — fail CLOSED on a missing/invalid signature whether // or not the install is registered (require_signed=true). The previous `is_registered()` // short-circuit let an UNREGISTERED install parse an unsigned/tampered feed; now an // unverifiable response is rejected and the caller keeps the trusted bundled signatures. if ( class_exists( 'GuardPress_Free_Credentials' ) && ! GuardPress_Free_Credentials::verify_response_signature( (string) $body, $response, true ) ) { self::cache_api_error( 'Response signature verification failed' ); return false; } $data = json_decode( $body, true ); if ( json_last_error() !== JSON_ERROR_NONE ) { self::cache_api_error( 'Invalid JSON response' ); return false; } // Check for success if ( ! isset( $data['success'] ) || ! $data['success'] ) { self::cache_api_error( 'API error: ' . ( $data['error'] ?? 'Unknown' ) ); return false; } // SUCCESS! Clear any cached error delete_option( self::OPTION_API_ERROR_CACHE ); // If delta update, merge with existing if ( isset( $data['is_delta'] ) && $data['is_delta'] ) { // BINLOG FIX (v8.2): Read existing from file first if ( class_exists( 'GuardPress_File_Storage' ) ) { $existing = GuardPress_File_Storage::load( 'threat-signatures', null, 'cache' ); if ( ! is_array( $existing ) ) { $existing = get_option( self::OPTION_SIGNATURES, array() ); } } else { $existing = get_option( self::OPTION_SIGNATURES, array() ); } $new_sigs = $data['signatures'] ?? array(); // FIX F-4 (audit 2026-05-25 round 2): validate every incoming // signature before merging it into the local detection store. // The threat-feed endpoint signs responses with HMAC v2-free, // BUT the response-signature mode is permissive by default // (see class-free-credentials.php STRICT_RESPONSE_SIG), so a // MITM that strips the signature header can inject arbitrary // signatures. Without validation, a malicious sig like // pattern: /(a+)+$/ → catastrophic backtracking (DoS) // pattern: /<\?php.*/s → flags every PHP file as malware // would be persisted and executed against every scan. $new_sigs = self::validate_remote_signatures( $new_sigs ); // Merge (add new to existing) $existing_ids = array(); foreach ( $existing as $sig ) { $existing_ids[ $sig['id'] ?? '' ] = true; } foreach ( $new_sigs as $sig ) { if ( ! isset( $existing_ids[ $sig['id'] ?? '' ] ) ) { $existing[] = $sig; } } $data['signatures'] = $existing; } elseif ( isset( $data['signatures'] ) && is_array( $data['signatures'] ) ) { // FIX F-4: also validate full-replacement signature payloads. $data['signatures'] = self::validate_remote_signatures( $data['signatures'] ); } return $data; } /** * FIX F-4 (audit 2026-05-25 round 2): validate signature payloads * received from the threat-feed server BEFORE they enter the local * detection store. * * Rejects signatures that: * - Have no 'pattern' field (malformed) * - Have a pattern longer than MAX_PATTERN_LEN (suspicious — real * signatures are short) * - Fail a compile-only preg_match against an empty string (catches * unbalanced delimiters, invalid regex syntax, dangerous modifiers) * - Use the catastrophic-backtracking shape (a+)+ family — heuristic * * The compile-only check uses `@preg_match($pat, '')` — this compiles * the pattern in PCRE without actually matching, so a malformed * regex is detected at validation time, not at scan time. * * Returns the filtered array; unsafe signatures are silently dropped * and (when WP_DEBUG) logged for diagnostics. */ private static function validate_remote_signatures( $sigs ) { if ( ! is_array( $sigs ) ) { return array(); } $MAX_PATTERN_LEN = 500; $clean = array(); $rejected_count = 0; foreach ( $sigs as $sig ) { if ( ! is_array( $sig ) ) { $rejected_count++; continue; } $pattern = isset( $sig['pattern'] ) ? (string) $sig['pattern'] : ''; if ( $pattern === '' || strlen( $pattern ) > $MAX_PATTERN_LEN ) { $rejected_count++; continue; } // Compile-only check. @-suppressed because invalid regex emits // E_WARNING in PHP < 8.0 (and TypeError-like behaviour later). $compile_ok = ( @preg_match( $pattern, '' ) !== false ); if ( ! $compile_ok ) { $rejected_count++; continue; } // Heuristic: refuse the canonical catastrophic-backtracking // shape `(x+)+`, `(x*)+`, etc. — these are vanishingly rare in // real malware signatures and very common in DoS payloads. if ( 1 === preg_match( '/\([^)]+[+*]\)[+*]/', $pattern ) ) { $rejected_count++; continue; } $clean[] = $sig; } if ( $rejected_count > 0 && function_exists( 'guardpress_debug_log' ) ) { guardpress_debug_log( sprintf( 'GuardPress F-4: rejected %d malformed/unsafe signature(s) from threat-feed response.', $rejected_count ) ); } return $clean; } /** * Scheduled update callback */ public static function scheduled_update() { // FIX (audit follow-up F-103-01): the AUTOMATIC cron must NOT force-refresh. // It now honours FREE_UPDATE_INTERVAL (7 days) so a FREE site contacts the // server about weekly, matching the disclosed wording. (The first-scan consent // and the manual "Refresh" button still force-refresh — those are user actions.) if ( ! get_option( 'guardpress_threat_feed_enabled', false ) ) { return; // feed turned off — stop the recurring external calls } self::get_signatures( false ); } /** * AJAX handler for manual update */ /** * First-scan consent + update. The pre-scan popup is the explicit, informed * consent moment (it discloses the single request to our servers), so this * enables the Threat Feed and fetches the freshest signatures in one step, * then reports the new counts (which the Settings box then reflects). */ public static function ajax_consent_update_threats() { check_ajax_referer( 'guardpress_ajax', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( array( 'message' => __( 'Unauthorized', 'ai-cyberguard' ) ), 403 ); } // Record the user's explicit consent (given via the pre-scan popup). update_option( 'guardpress_threat_feed_enabled', true ); update_option( 'guardpress_threat_feed_auto_update', true ); // Actually schedule the recurring auto-update cron — setting the option // alone does NOT schedule it. enable_auto_updates() is the only place the // event is registered, and it is idempotent (guards with wp_next_scheduled). if ( method_exists( __CLASS__, 'enable_auto_updates' ) ) { self::enable_auto_updates(); } // FIX F-104-03 (+ round-5 hardening): the consent popup is meant for the // FIRST scan, so we force a fresh fetch only when one has never succeeded // ( $last_update <= 0 ). Repeated calls (double-clicks, popup re-fires, or // a replayed nonce by a logged-in admin) then go through // get_signatures( false ), which honours the 7-day interval and returns // the cached set with NO network call. // // On a genuine first run we additionally apply the SAME 60-second // anti-hammer floor that ajax_update_threats() uses (shared marker), so a // replayed consent against a DOWN server can't issue a wp_remote_get on // every click — on failure fetch_from_server() never advances // $last_update, so it would otherwise stay 0 and keep re-forcing. And we // only clear the API-error backoff on that genuine first attempt, never // on every call (which would defeat the 24h fetch_from_server() backoff). $last_update = (int) get_option( self::OPTION_LAST_UPDATE, 0 ); $force = ( $last_update <= 0 ); if ( $force ) { $first_key = 'guardpress_threat_feed_first_call_attempt'; $first_attempt = (int) get_option( $first_key, 0 ); if ( $first_attempt > 0 && ( time() - $first_attempt ) < MINUTE_IN_SECONDS ) { // Within the floor — do not force another network fetch. $force = false; } else { update_option( $first_key, time(), false ); delete_option( self::OPTION_API_ERROR_CACHE ); } } self::get_signatures( $force ); $status = self::get_status(); wp_send_json_success( array( 'signatures' => intval( $status['signature_count'] ?? 0 ), 'hashes' => intval( $status['hash_count'] ?? 0 ), 'message' => __( 'Threat database updated to the latest signatures.', 'ai-cyberguard' ), ) ); } public static function ajax_update_threats() { check_ajax_referer( 'guardpress_ajax', 'nonce' ); if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'Unauthorized' ); } // FIX F-3 (audit 2026-05-25 round 2): refuse to refresh threats when // the user has not explicitly enabled the threat feed in Settings. // // The prior code SILENTLY enabled the feature on first manual click, // arguing "the user clicked Refresh = consent." That argument fails // wp.org review (§7: consent must be granular and informed) AND // creates a real privacy issue: the click-handler also persists the // option, meaning later cron events from THAT installation will // continue making external calls without further user awareness. // // The correct flow: refuse the call, return a clear error explaining // the user must enable it in Settings → Privacy first. The button // remains visible (rendered server-side) so the admin sees there IS a // feature, but clicking it does not opt them in. if ( ! get_option( 'guardpress_threat_feed_enabled', false ) ) { wp_send_json_error( array( 'message' => __( 'Threat Signature updates require your explicit consent. Please enable "Threat Signature Updates" in Settings & Security → Privacy & External Requests, then try again.', 'ai-cyberguard' ), 'requires_consent' => true, 'consent_link' => admin_url( 'admin.php?page=guardpress_settings#privacy' ), ) ); } // FIX RC-105-02 (audit 2026-06-17): the cached API-error backoff is now // cleared only AFTER the rate-limit checks pass (just before the actual // fetch below), NOT here. Clearing it up-front let an admin defeat the // 24h fetch_from_server() backoff by re-clicking Refresh against a down // server — a rate-limited/floored click should not wipe the backoff. // FIX H-3 (audit 2026-05-25): TWO rate-limit bugs fixed here. // // BUG 1 (rate-limit bypass on fresh install): the prior code skipped // the rate-limit check entirely when $last_update was empty. On a // fresh install (or after clear_cache() cleared OPTION_LAST_UPDATE), // an authenticated admin could hammer the endpoint with unlimited // remote fetches to guardpress.ai/api/signatures/. We fix this by // tracking a separate first-call attempt marker that enforces a // 60-second floor even before the first successful update lands. // // BUG 2 (PRO has no rate limit): the prior code only emitted // wp_send_json_error() when ! $is_pro. PRO users fell through to // get_signatures(true) regardless of how recently they refreshed — // contradicting the in-code comment that "PRO users can update every // hour". Now both editions enforce their respective interval. $last_update = (int) get_option( self::OPTION_LAST_UPDATE, 0 ); $is_pro = class_exists( 'GuardPress_License' ) && GuardPress_License::is_pro(); $interval = $is_pro ? self::PRO_UPDATE_INTERVAL : self::FREE_UPDATE_INTERVAL; $now = time(); if ( $last_update <= 0 ) { // First-ever call (or post-reset) — apply a short anti-hammer floor. // 60 seconds prevents reload-loop / scripted abuse without blocking // legitimate "I just installed, let me get fresh threats" flow. $first_call_key = 'guardpress_threat_feed_first_call_attempt'; $first_attempt = (int) get_option( $first_call_key, 0 ); $min_floor = MINUTE_IN_SECONDS; if ( $first_attempt > 0 && ( $now - $first_attempt ) < $min_floor ) { wp_send_json_error( array( 'message' => __( 'Please wait a moment before retrying.', 'ai-cyberguard' ), 'next_update' => human_time_diff( $now, $first_attempt + $min_floor ), 'is_pro' => $is_pro, ) ); } // Record this attempt BEFORE the remote call so concurrent requests // hit the floor too. autoload=false: marker is only read here. update_option( $first_call_key, $now, false ); } else { $elapsed = $now - $last_update; if ( $elapsed < $interval ) { $wait_time = human_time_diff( $now, $last_update + $interval ); $message = $is_pro ? sprintf( /* translators: %s: human-readable duration */ __( 'PRO threat updates are available every hour. Next update available in %s.', 'ai-cyberguard' ), $wait_time ) : sprintf( /* translators: %s: human-readable duration */ __( 'Threat updates are available every 7 days. Next update available in %s.', 'ai-cyberguard' ), $wait_time ); wp_send_json_error( array( 'message' => $message, 'next_update' => $wait_time, 'is_pro' => $is_pro, ) ); } } // Rate-limit passed — this call will actually fetch, so clear any stale // API-error backoff now (RC-105-02: moved here from before the checks). delete_option( self::OPTION_API_ERROR_CACHE ); $signatures = self::get_signatures( true ); $count = is_array( $signatures ) ? count( $signatures ) : 0; // Check if the API call just failed (error was cached during fetch_from_server) $api_error = get_option( self::OPTION_API_ERROR_CACHE, array() ); if ( ! empty( $api_error ) ) { $error_msg = isset( $api_error['message'] ) ? $api_error['message'] : __( 'Unknown error', 'ai-cyberguard' ); if ( $count === 0 ) { // No signatures at all — real failure wp_send_json_error( array( /* translators: %s is the error message returned by the server. */ 'message' => sprintf( __( 'Could not connect to GuardPress server: %s. Please try again later.', 'ai-cyberguard' ), $error_msg ), ) ); } else { // API failed but we have cached signatures — inform user wp_send_json_error( array( /* translators: 1: error message returned by the server, 2: number of previously cached signatures. */ 'message' => sprintf( __( 'Could not refresh from server (%1$s). Using %2$d previously cached signatures.', 'ai-cyberguard' ), $error_msg, $count ), ) ); } } wp_send_json_success( array( /* translators: %d is the number of threat signatures loaded. */ 'message' => sprintf( __( 'Updated! %d threat signatures loaded.', 'ai-cyberguard' ), $count ), 'count' => $count, 'updated' => gmdate( 'Y-m-d H:i:s' ), ) ); } /** * Get feed status * * @return array */ public static function get_status() { $last_update = get_option( self::OPTION_LAST_UPDATE, 0 ); // BINLOG FIX (v8.2): Read from file instead of loading 2.3MB from DB if ( class_exists( 'GuardPress_File_Storage' ) ) { $signatures = GuardPress_File_Storage::load( 'threat-signatures', null, 'cache' ); $hashes = GuardPress_File_Storage::load( 'threat-malware-hashes', null, 'cache' ); if ( ! is_array( $signatures ) ) { $signatures = get_option( self::OPTION_SIGNATURES, array() ); } if ( ! is_array( $hashes ) ) { $hashes = get_option( self::OPTION_MALWARE_HASHES, array() ); } } else { $signatures = get_option( self::OPTION_SIGNATURES, array() ); $hashes = get_option( self::OPTION_MALWARE_HASHES, array() ); } $is_pro = class_exists( 'GuardPress_License' ) && GuardPress_License::is_pro(); $interval = $is_pro ? self::PRO_UPDATE_INTERVAL : self::FREE_UPDATE_INTERVAL; $next_update = $last_update + $interval; return array( 'last_update' => $last_update, 'last_update_ago' => $last_update ? human_time_diff( $last_update ) . ' ' . __( 'ago', 'ai-cyberguard' ) : __( 'Never', 'ai-cyberguard' ), 'next_update' => $next_update, 'next_update_in' => $next_update > time() ? human_time_diff( time(), $next_update ) : __( 'Now', 'ai-cyberguard' ), 'signature_count' => is_array( $signatures ) ? count( $signatures ) : 0, 'hash_count' => is_array( $hashes ) ? count( $hashes ) : 0, 'update_interval' => $is_pro ? __( 'Real-time (hourly)', 'ai-cyberguard' ) : __( 'Weekly (7 days)', 'ai-cyberguard' ), 'is_pro' => $is_pro, ); } /** * Get combined patterns (built-in + threat feed) * * @return array */ public static function get_all_patterns() { // Built-in patterns (always available) $builtin = self::get_builtin_patterns(); // Feed patterns $feed = self::get_signatures(); if ( ! is_array( $feed ) ) { $feed = array(); } // Merge with feed patterns taking priority (newer) return array_merge( $builtin, $feed ); } /** * Get built-in patterns (hardcoded baseline) * * @return array */ public static function get_builtin_patterns() { return array( // === PHP Code Execution === array( 'id' => 'eval_usage', 'name' => 'eval() Usage', 'pattern' => '/\beval\s*\(\s*(\$|base64|gzinflate|str_rot13)/i', 'severity' => 'high', 'description' => 'Dynamic code execution via eval()', 'category' => 'code_execution', ), array( 'id' => 'create_function', 'name' => 'create_function()', 'pattern' => '/\bcreate_function\s*\(/i', 'severity' => 'high', 'description' => 'Deprecated function that can execute arbitrary code', 'category' => 'code_execution', ), array( 'id' => 'assert_code', 'name' => 'assert() with code', 'pattern' => '/\bassert\s*\(\s*[\'"]\s*\$/i', 'severity' => 'high', 'description' => 'assert() used for code execution', 'category' => 'code_execution', ), array( 'id' => 'preg_replace_e', 'name' => 'preg_replace /e modifier', 'pattern' => '/preg_replace\s*\(\s*[\'"][^\'"]*\/[a-z]*e[a-z]*[\'"]/i', 'severity' => 'critical', 'description' => 'preg_replace with deprecated /e modifier for code execution', 'category' => 'code_execution', ), // === Base64/Encoding === array( 'id' => 'base64_decode_eval', 'name' => 'Base64 Decode + Eval', 'pattern' => '/eval\s*\(\s*base64_decode\s*\(/i', 'severity' => 'critical', 'description' => 'Obfuscated code execution', 'category' => 'obfuscation', ), array( 'id' => 'gzinflate_decode', 'name' => 'Compressed Code', 'pattern' => '/gzinflate\s*\(\s*base64_decode/i', 'severity' => 'critical', 'description' => 'Compressed and encoded malicious code', 'category' => 'obfuscation', ), array( 'id' => 'str_rot13_decode', 'name' => 'ROT13 Obfuscation', 'pattern' => '/str_rot13\s*\(\s*base64_decode/i', 'severity' => 'high', 'description' => 'ROT13 encoded malicious code', 'category' => 'obfuscation', ), // === Web Shells - encoded to prevent false positives === array( 'id' => 'shell_c99', 'name' => 'C99 Shell', 'pattern' => '/' . self::_d('Yzk5c2hlbGx8Yzk5X2J1ZmZfcHJlcGFyZXxjOTlzaF9zdXJs') . '/i', 'severity' => 'critical', 'description' => 'C99 web shell detected', 'category' => 'webshell', ), array( 'id' => 'shell_r57', 'name' => 'R57 Shell', 'pattern' => '/' . self::_d('cjU3c2hlbGx8cjU3X3B3ZF9mb3Jt') . '/i', 'severity' => 'critical', 'description' => 'R57 web shell detected', 'category' => 'webshell', ), array( 'id' => 'shell_wso', 'name' => 'WSO Shell', 'pattern' => '/' . self::_d('V1NPXHMrXGR8RmlsZXNNYW58V2ViXHMqU2hlbGxccypieQ==') . '/i', 'severity' => 'critical', 'description' => 'Known webshell detected', 'category' => 'webshell', ), array( 'id' => 'shell_type_1', 'name' => 'B374K Shell', 'pattern' => '/' . self::_d('YjM3NGt8YjM3NGtfY29uZmlnfG1pbmlfc2hlbGw=') . '/i', 'severity' => 'critical', 'description' => 'B374K mini shell detected', 'category' => 'webshell', ), array( 'id' => 'shell_generic', 'name' => 'Generic Shell Pattern', 'pattern' => '/\$_(GET|POST|REQUEST|COOKIE)\s*\[\s*[\'"][^\'"]+[\'"]\s*\]\s*\(/i', 'severity' => 'critical', 'description' => 'Direct execution of user input', 'category' => 'webshell', ), // === Backdoors === array( 'id' => 'backdoor_passthru', 'name' => 'Command Passthru', 'pattern' => '/passthru\s*\(\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Command execution via passthru()', 'category' => 'backdoor', ), array( 'id' => 'backdoor_system', 'name' => 'System Command', 'pattern' => '/system\s*\(\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Command execution via system()', 'category' => 'backdoor', ), array( 'id' => 'backdoor_exec', 'name' => 'Exec Command', 'pattern' => '/\bexec\s*\(\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Command execution via exec()', 'category' => 'backdoor', ), array( 'id' => 'backdoor_shell_exec', 'name' => 'Shell Exec', 'pattern' => '/shell_exec\s*\(\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Command execution via shell_exec()', 'category' => 'backdoor', ), array( 'id' => 'backdoor_proc_open', 'name' => 'Process Open', 'pattern' => '/proc_open\s*\(/i', 'severity' => 'high', 'description' => 'Process execution via proc_open()', 'category' => 'backdoor', ), array( 'id' => 'backdoor_popen', 'name' => 'Pipe Open', 'pattern' => '/popen\s*\(\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Process execution via popen()', 'category' => 'backdoor', ), // === File Operations === array( 'id' => 'file_put_dangerous', 'name' => 'Dangerous File Write', 'pattern' => '/file_put_contents\s*\([^,]+,\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Writing user input to files', 'category' => 'file_operation', ), array( 'id' => 'fwrite_dangerous', 'name' => 'Dangerous fwrite', 'pattern' => '/fwrite\s*\([^,]+,\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Writing user input via fwrite()', 'category' => 'file_operation', ), array( 'id' => 'move_uploaded_file_danger', 'name' => 'Upload Without Validation', 'pattern' => '/move_uploaded_file\s*\([^)]+\$_(GET|POST|REQUEST)/i', 'severity' => 'high', 'description' => 'File upload with user-controlled destination', 'category' => 'file_operation', ), // === Database Injection === array( 'id' => 'sql_injection_direct', 'name' => 'Direct SQL Injection', 'pattern' => '/\$wpdb->(query|get_results|get_var|get_row)\s*\([^)]*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Direct use of user input in SQL query', 'category' => 'sql_injection', ), // === Include/Require === array( 'id' => 'include_remote', 'name' => 'Remote File Include', 'pattern' => '/(include|require|include_once|require_once)\s*\(\s*[\'"]?(https?:|ftp:)/i', 'severity' => 'critical', 'description' => 'Remote file inclusion attempt', 'category' => 'file_include', ), array( 'id' => 'include_user_input', 'name' => 'User Input Include', 'pattern' => '/(include|require|include_once|require_once)\s*\(\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'critical', 'description' => 'Including files based on user input', 'category' => 'file_include', ), // === Cryptocurrency Mining === array( 'id' => 'crypto_coinhive', 'name' => 'CoinHive Miner', 'pattern' => '/coinhive\.min\.js|CoinHive\.Anonymous/i', 'severity' => 'high', 'description' => 'Cryptocurrency miner detected', 'category' => 'crypto_miner', ), array( 'id' => 'crypto_generic', 'name' => 'Generic Crypto Miner', 'pattern' => '/cryptonight|stratum\+tcp|xmrig/i', 'severity' => 'high', 'description' => 'Cryptocurrency mining code detected', 'category' => 'crypto_miner', ), // === Spam/SEO Injection === array( 'id' => 'seo_spam_links', 'name' => 'SEO Spam Links', 'pattern' => '/]+href=[\'"]https?:\/\/[^"\']+[\'"][^>]*style=[\'"][^"\']*display\s*:\s*none/i', 'severity' => 'medium', 'description' => 'Hidden spam links for SEO', 'category' => 'spam', ), array( 'id' => 'pharma_spam', 'name' => 'Pharma Spam', 'pattern' => '/(viagra|cialis|pharmacy|pills|medication)[^<]*<\/a>/i', 'severity' => 'medium', 'description' => 'Pharmaceutical spam content', 'category' => 'spam', ), // === Suspicious Variables === array( 'id' => 'globals_overwrite', 'name' => 'Globals Overwrite', 'pattern' => '/\$GLOBALS\s*\[\s*[\'"][^\'"]+[\'"]\s*\]\s*=\s*\$_(GET|POST|REQUEST)/i', 'severity' => 'high', 'description' => 'Overwriting globals with user input', 'category' => 'suspicious', ), array( 'id' => 'hex_encoded', 'name' => 'Hex Encoded String', 'pattern' => '/\\\\x[0-9a-fA-F]{2}(\\\\x[0-9a-fA-F]{2}){10,}/i', 'severity' => 'medium', 'description' => 'Long hex-encoded string (possible obfuscation)', 'category' => 'obfuscation', ), array( 'id' => 'long_base64', 'name' => 'Long Base64 String', 'pattern' => '/[\'"][a-zA-Z0-9+\/]{500,}={0,2}[\'"]/i', 'severity' => 'medium', 'description' => 'Very long base64 encoded string', 'category' => 'obfuscation', ), // === Known Malware Signatures - encoded === array( 'id' => 'malware_theme_inject', 'name' => 'WP-VCD Malware', 'pattern' => '/' . self::_d('d3BfY2RfY29kZXx3cF92Y2R8dGhlbWVzX2plNDk4amhnamhnamtkdGprZw==') . '/i', 'severity' => 'critical', 'description' => 'WP-VCD malware infection', 'category' => 'malware', ), array( 'id' => 'malware_wp_feed', 'name' => 'WP Feed Malware', 'pattern' => '/wp_feed\.php|wp-feed\.php/i', 'severity' => 'critical', 'description' => 'WordPress feed malware', 'category' => 'malware', ), array( 'id' => 'malware_spam_tool', 'name' => 'PHP Spam Tool', 'pattern' => '/' . self::_d('bGVhZm1haWxlcnxMZWFmXHMqUEhQTWFpbGVy') . '/i', 'severity' => 'critical', 'description' => 'Malicious mailer script', 'category' => 'malware', ), array( 'id' => 'malware_sostel', 'name' => 'Sostel Backdoor', 'pattern' => '/sostel|indoxploit/i', 'severity' => 'critical', 'description' => 'Sostel/IndoXploit backdoor', 'category' => 'malware', ), ); } /** * Cache API error and log once * Prevents log spam by only logging the first occurrence * * @param string $message Error message */ private static function cache_api_error( $message ) { $cached = get_option( self::OPTION_API_ERROR_CACHE, array() ); // Only log if this is a new error (not cached) if ( empty( $cached ) || ! isset( $cached['time'] ) ) { self::log_error( $message . ' (will retry in 24 hours, using built-in signatures)' ); } // Cache the error update_option( self::OPTION_API_ERROR_CACHE, array( 'time' => time(), 'message' => $message, ), false ); // ACG-036-005: stamp this own-option's integrity MAC so the DB scanner trusts the genuine // value (which may echo a rejected-signature snippet) without scanning, while a payload // planted under this name has no valid MAC and is still scanned. if ( class_exists( 'GuardPress_Database_Scanner' ) ) { GuardPress_Database_Scanner::stamp_own_option( self::OPTION_API_ERROR_CACHE ); } } /** * Log error message * * @param string $message */ private static function log_error( $message ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { guardpress_debug_log( '[GuardPress Threat Feed] ' . $message ); } } /** * Clear cached data (for uninstall) */ public static function clear_cache() { // Clear file-based cache if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::delete( 'threat-signatures', 'cache' ); GuardPress_File_Storage::delete( 'threat-malware-hashes', 'cache' ); } // Also clear legacy DB (migration cleanup) delete_option( self::OPTION_SIGNATURES ); delete_option( self::OPTION_LAST_UPDATE ); delete_option( self::OPTION_MALWARE_HASHES ); delete_option( self::OPTION_API_ERROR_CACHE ); // FIX NEW-MEDIUM-2 (audit 2026-05-25 round 2): the H-3 first-call // anti-hammer marker MUST be reset alongside OPTION_LAST_UPDATE. // Otherwise after clear_cache(), $last_update=0 but $first_attempt // retains its (now-stale) old timestamp; the next manual refresh // misreads "minute-floor expired" and bypasses the 60-second floor, // partly re-opening the H-3 bypass for one refresh cycle. delete_option( 'guardpress_threat_feed_first_call_attempt' ); wp_clear_scheduled_hook( 'guardpress_threat_feed_update' ); } }