self::$net_fail_streak, 'open' => self::$circuit_open, ), 'scan' ); } } /** * Check if we've reached the API budget limit * * @return bool True if limit reached */ /** RC-119-04: record a transient API failure; open the breaker after CIRCUIT_TRIP in a row. */ private static function note_transient_failure() { self::$net_fail_streak++; if ( self::$net_fail_streak >= self::CIRCUIT_TRIP ) { self::$circuit_open = true; } self::breaker_save(); // RC-120-03: persist so the breaker survives the next batch/process } public static function is_budget_exhausted() { self::breaker_load(); // RC-120-03: rehydrate the persisted breaker before deciding // RC-119-04: an OPEN circuit is treated as "no budget" so all later confirmations // are skipped (offline — the file keeps whatever local verdict it already has). return self::$circuit_open || self::$api_call_count >= self::MAX_API_CALLS_PER_SCAN; } /** * Check if a file is known malware (by hash only - no file reading) * * IMPORTANT: Only call this for files already flagged as suspicious! * This is a CONFIRMATION layer, not a primary scanner. * * @param string $file_path Path to file * @return array|false Array with malware info if found, false otherwise */ /** * ACG-085-003 (audit 2026-06-27): the shared no-follow contract for this lookup's read/hash. Prefers the canonical * GuardPress_FS_Helpers primitive; falls back to a self-contained, trusted-root-aware copy. True ONLY for a REGULAR * file (no symlink/FIFO/dir/socket/device) with NO symlink path component below the deepest trusted root and a * contained realpath. * * @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 ), '/' ) . '/' ) ); } public static function check_file( $file_path ) { // Check budget first if ( self::is_budget_exhausted() ) { return false; } // ACG-085-003 (audit 2026-06-27, HIGH): never filesize()/hash_file() THROUGH a symlinked path component or on a // non-regular file. is_readable() alone passes a FIFO (and file_get_contents/hash_file then BLOCK forever — a // scan DoS), and a parent directory swapped to a symlink would make hash_file() read an EXTERNAL target and // submit its hash. The shared no-symlink-component + regular-file contract rejects both before any size/hash. if ( ! self::is_safe_regular_file( $file_path ) ) { return false; } if ( ! file_exists( $file_path ) || ! is_readable( $file_path ) ) { return false; } // Skip large files (> 10MB - malware is usually small) $filesize = @filesize( $file_path ); if ( $filesize === false || $filesize > 10 * 1024 * 1024 ) { return false; } // Calculate hash (efficient - doesn't load entire file into memory) $hash = @hash_file( 'sha256', $file_path ); if ( ! $hash ) { return false; } return self::check_hash( $hash ); } /** * Check if a hash is known malware * * @param string $hash SHA256 hash * @return array|false Array with malware info if found, false otherwise */ public static function check_hash( $hash ) { if ( empty( $hash ) || strlen( $hash ) !== 64 ) { return false; } // Check budget if ( self::is_budget_exhausted() ) { return false; } $hash = strtolower( $hash ); // Check local cache first (no API call needed) $cached = self::check_cache( $hash ); if ( $cached !== null ) { return $cached; } // Query the API (counts against budget) $result = self::query_api( $hash ); // FIX (audit 2026-06-10): only cache DEFINITIVE answers. query_api now // returns null for a transient failure (timeout / 429 / 5xx / // unparseable). Caching that as "not malware" for 24h previously poisoned // lookups — a genuinely malicious file scanned during an API hiccup was // remembered as clean for a full day. Transient failures are not cached. if ( $result !== null ) { self::cache_result( $hash, $result ); } return ( $result === null ) ? false : $result; } /** * Check local cache * * @param string $hash SHA256 hash * @return array|false|null Null if not in cache */ private static function check_cache( $hash ) { // BINLOG FIX (v8.2): Moved from get_option() to File Storage. // Before: get_option() loaded ~100KB from DB on EVERY call. // cache_result() wrote UPDATE wp_options → 100KB to binlog each time. // Up to 25 calls × 100KB = 2.5MB binlog per scan. // After: File-based in guardpress-data/cache/ — zero binlog impact. if ( self::$hash_cache_memory === null ) { if ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'malwarebazaar-cache', null, 'cache' ); self::$hash_cache_memory = is_array( $loaded ) ? $loaded : array(); } else { self::$hash_cache_memory = get_option( self::OPTION_HASH_CACHE, array() ); } } if ( ! isset( self::$hash_cache_memory[ $hash ] ) ) { return null; } $entry = self::$hash_cache_memory[ $hash ]; // Check expiration if ( isset( $entry['time'] ) && ( time() - $entry['time'] ) > self::CACHE_EXPIRATION ) { return null; } return isset( $entry['data'] ) ? $entry['data'] : false; } /** * Cache a result * * @param string $hash SHA256 hash * @param array|false $result Result to cache */ private static function cache_result( $hash, $result ) { // BINLOG FIX (v8.2): Write to file instead of DB if ( self::$hash_cache_memory === null ) { if ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'malwarebazaar-cache', null, 'cache' ); self::$hash_cache_memory = is_array( $loaded ) ? $loaded : array(); } else { self::$hash_cache_memory = get_option( self::OPTION_HASH_CACHE, array() ); } } // Limit cache size to prevent file bloat if ( count( self::$hash_cache_memory ) >= self::MAX_CACHE_SIZE ) { // Remove oldest 20% of entries uasort( self::$hash_cache_memory, function( $a, $b ) { return ( $a['time'] ?? 0 ) - ( $b['time'] ?? 0 ); }); self::$hash_cache_memory = array_slice( self::$hash_cache_memory, (int)( self::MAX_CACHE_SIZE * 0.2 ), null, true ); } self::$hash_cache_memory[ $hash ] = array( 'time' => time(), 'data' => $result, ); // Write to file ONLY — no DB fallback for cache data. if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::save( 'malwarebazaar-cache', self::$hash_cache_memory, 'cache' ); } } /** * Query the MalwareBazaar API * * @param string $hash SHA256 hash * @return array|false Array with malware info if found, false otherwise */ private static function query_api( $hash ) { // Increment counter BEFORE the call self::$api_call_count++; $response = wp_remote_post( self::API_URL, array( 'timeout' => 5, // Reduced timeout for better UX 'body' => array( 'query' => 'get_info', 'hash' => $hash, ), 'headers' => array( 'User-Agent' => 'GuardPress/' . self::PLUGIN_VERSION . ' (+https://guardpress.ai)', ), ) ); if ( is_wp_error( $response ) ) { // FIX (audit 2026-06-10): transient failure → null (not cached), so a // network blip doesn't pin this hash as "clean" for 24h. self::note_transient_failure(); // RC-119-04 return null; } $code = wp_remote_retrieve_response_code( $response ); if ( $code !== 200 ) { self::note_transient_failure(); // RC-119-04: 429/5xx/etc. trip the breaker return null; // transient — do not cache } $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); if ( ! $data || ! isset( $data['query_status'] ) ) { self::note_transient_failure(); // RC-119-04: unparseable/unexpected = transient return null; } // A definitive answer (found or hash_not_found) — the service is healthy; reset. self::$net_fail_streak = 0; self::breaker_save(); // RC-120-03: persist the healthy reset across batches // Not found = not known malware (DEFINITIVE — safe to cache) if ( $data['query_status'] === 'hash_not_found' ) { return false; } // Found = known malware! // ACG-121 C3 (audit 2026-07-16): require data[0] to be a real 0-indexed RECORD before trusting it. // The old shape test (isset($data['data']) && !empty(...)) accepted an assoc-array/scalar 'data', so // $info became null: the isset() guards below then produced malware_name='Unknown Malware' but STILL // returned is_known=true / confidence=1.0 — the scanner would report "Confirmed Malware, risk 100" on // a file whose payload was merely malformed. A malformed payload must be "not known", never a // positive verdict. Returning false here is the SAFE default (same as hash_not_found); a genuine // detection is unaffected because a real MalwareBazaar hit always carries data[0] as an array. if ( $data['query_status'] === 'ok' && isset( $data['data'][0] ) && is_array( $data['data'][0] ) ) { $info = $data['data'][0]; // ACG-121 C2: sanitise every third-party field at INGEST, mirroring URLhaus::parse_response(). // malware_name flows into the finding 'name' rendered in wp-admin; sanitising here keeps a // compromised/tampered feed from putting markup into the results page regardless of the sink. $gp_txt = static function ( $v ) { return function_exists( 'sanitize_text_field' ) ? sanitize_text_field( (string) $v ) : strip_tags( (string) $v ); }; $malware_name = isset( $info['signature'] ) && $info['signature'] ? $gp_txt( $info['signature'] ) : 'Unknown Malware'; $av_detections = 0; if ( isset( $info['intelligence']['detections'] ) ) { $av_detections = intval( $info['intelligence']['detections'] ); } $gp_tags = array(); if ( isset( $info['tags'] ) && is_array( $info['tags'] ) ) { foreach ( $info['tags'] as $gp_tag ) { if ( is_scalar( $gp_tag ) ) { $gp_tags[] = $gp_txt( $gp_tag ); } } } return array( 'is_known' => true, 'confidence' => 1.0, 'source' => 'MalwareBazaar', 'malware_name' => $malware_name, 'sha256' => isset( $info['sha256_hash'] ) ? $gp_txt( $info['sha256_hash'] ) : $hash, 'file_type' => isset( $info['file_type'] ) ? $gp_txt( $info['file_type'] ) : '', 'first_seen' => isset( $info['first_seen'] ) ? $gp_txt( $info['first_seen'] ) : '', 'tags' => $gp_tags, 'av_detections' => $av_detections, 'description' => sprintf( /* translators: 1: malware name, 2: number of antivirus engines that detected it */ __( 'Confirmed malware "%1$s" - detected by %2$d antivirus engines.', 'ai-cyberguard' ), $malware_name, $av_detections ), ); } return false; } /** * Get cache statistics * * @return array Stats */ public static function get_stats() { // Use in-memory cache if available, else load from file/DB if ( self::$hash_cache_memory !== null ) { $cache = self::$hash_cache_memory; } elseif ( class_exists( 'GuardPress_File_Storage' ) ) { $loaded = GuardPress_File_Storage::load( 'malwarebazaar-cache', null, 'cache' ); $cache = is_array( $loaded ) ? $loaded : array(); } else { $cache = get_option( self::OPTION_HASH_CACHE, array() ); } $known_count = 0; foreach ( $cache as $entry ) { if ( isset( $entry['data']['is_known'] ) && $entry['data']['is_known'] ) { $known_count++; } } return array( 'cached_hashes' => count( $cache ), 'known_malware' => $known_count, 'api_calls_this_run' => self::$api_call_count, 'budget_remaining' => self::MAX_API_CALLS_PER_SCAN - self::$api_call_count, ); } /** * Clear the cache */ public static function clear_cache() { // Clear file-based cache if ( class_exists( 'GuardPress_File_Storage' ) ) { GuardPress_File_Storage::delete( 'malwarebazaar-cache', 'cache' ); } // Also clear legacy DB cache (migration cleanup) delete_option( self::OPTION_HASH_CACHE ); self::$hash_cache_memory = null; self::$api_call_count = 0; } }