= self::MAX_API_CALLS_PER_SCAN ) { return false; } // Query URLhaus API $result = self::query_api( $url ); // FIX (audit M-01): a transient failure (timeout / 429 / 5xx / malformed // JSON) returns null. Fail OPEN for the user, but do NOT cache the URL as // clean — otherwise a momentary outage of the external service would pin a // possibly-malicious URL as "safe" for the whole cache lifetime. if ( null === $result ) { return false; } if ( isset( $result['query_status'] ) && $result['query_status'] === 'ok' ) { // URL is known malicious! $url_info = self::parse_response( $result ); self::add_to_cache( $url, $url_info ); return $url_info; } // Only a genuine "no_results" answer is a confirmed-clean verdict that is // safe to cache. Any other status (invalid_url, etc.) is not cached clean. if ( isset( $result['query_status'] ) && $result['query_status'] === 'no_results' ) { self::add_to_cache( $url, false ); } return false; } /** * Extract and check all URLs from content * * @param string $content File content to scan * @return array Array of malicious URLs found with details */ public static function scan_content( $content ) { $malicious_urls = array(); // FIX (audit 2026-06-10): privacy — URLhaus checks send extracted URLs // (which can include internal hostnames/credentials) to abuse.ch. Only do // so when the user opted into external threat intelligence. // FIX (audit follow-up 7.4): fail CLOSED — if the consent gate is unavailable // for any reason, do NOT send URLs to abuse.ch. Proceed only when the gate // class exists AND has explicitly allowed external threat intelligence. if ( ! class_exists( 'GuardPress_Malware_Scanner' ) || ! method_exists( 'GuardPress_Malware_Scanner', 'external_intel_allowed' ) || ! GuardPress_Malware_Scanner::external_intel_allowed() ) { return $malicious_urls; } // Extract URLs from content $urls = self::extract_urls( $content ); if ( empty( $urls ) ) { return $malicious_urls; } // Check each URL (with rate limiting) foreach ( $urls as $url ) { $result = self::check_url( $url ); if ( $result ) { $result['url'] = $url; $malicious_urls[] = $result; } } return $malicious_urls; } /** * Extract URLs from content * * @param string $content Content to parse * @return array Unique URLs found */ private static function extract_urls( $content ) { $urls = array(); // Match http/https URLs $pattern = '/https?:\/\/[^\s\'"<>\)\]\}\\\\]+/i'; if ( preg_match_all( $pattern, $content, $matches ) ) { $urls = array_unique( $matches[0] ); } // Remove duplicates and filter $urls = array_unique( $urls ); $urls = array_filter( $urls, function( $url ) { // Skip WordPress.org, common CDNs, etc. // Domains that are legitimate but sometimes abused by attackers // to host malware. The DOMAIN itself is not malicious — only // specific URLs on these domains may be. Checking the full URL // against the URLhaus API would still catch truly malicious // payloads, but domain-only matching produces false positives // in library files that legitimately reference these sites. $safe_domains = array( // WordPress ecosystem 'wordpress.org', 'w.org', 'wp.com', 'gravatar.com', // Google / CDNs 'googleapis.com', 'gstatic.com', 'google.com', 'cloudflare.com', 'jsdelivr.net', 'cdnjs.cloudflare.com', 'unpkg.com', 'jquery.com', // Social / major platforms 'facebook.com', 'twitter.com', 'linkedin.com', 'youtube.com', // Code hosting (commonly referenced in library source files) 'github.com', 'githubusercontent.com', 'raw.githubusercontent.com', 'gitlab.com', 'bitbucket.org', 'sourceforge.net', 'launchpad.net', // Package registries 'packagist.org', 'npmjs.com', 'npmjs.org', 'pypi.org', 'rubygems.org', 'nuget.org', // Documentation / reference sites 'readthedocs.io', 'docs.python.org', 'php.net', 'developer.mozilla.org', 'stackoverflow.com', 'wikipedia.org', 'wikimedia.org', // Archive / legitimate file hosting 'archive.org', 'web.archive.org', // Microsoft ecosystem 'microsoft.com', 'windows.net', 'azure.com', 'live.com', 'outlook.com', // Apple ecosystem 'apple.com', 'icloud.com', // Amazon (AWS, CDN) 'amazonaws.com', 'amazon.com', 'cloudfront.net', // Other major CDNs / services 'bootstrapcdn.com', 'fontawesome.com', 'fonts.googleapis.com', 'maxcdn.com', ); // FIX (audit 2026-06-10): match on the parsed HOST, not a substring of // the whole URL. The old `stripos( $url, $domain )` skipped the URLhaus // reputation check for any URL that merely CONTAINED a safe domain // anywhere — e.g. http://evil.com/?ref=wordpress.org — letting an // attacker trivially bypass the check. Now a URL is treated as safe // only when its host IS the safe domain or a genuine subdomain of it. $host = strtolower( (string) wp_parse_url( $url, PHP_URL_HOST ) ); if ( '' === $host ) { return true; // unpar. — let the API decide } foreach ( $safe_domains as $domain ) { $domain = strtolower( $domain ); if ( $host === $domain || ( strlen( $host ) > strlen( $domain ) + 1 && substr( $host, -( strlen( $domain ) + 1 ) ) === '.' . $domain ) ) { return false; // host is the safe domain or a subdomain of it } } return true; }); // Limit to first 15 URLs to avoid excessive API calls return array_slice( array_values( $urls ), 0, 15 ); } /** * Normalize URL for caching * * @param string $url URL to normalize * @return string|false Normalized URL or false if invalid */ private static function normalize_url( $url ) { $url = trim( (string) $url ); // Drop the #fragment FIRST (audit follow-up 7.3) — it is never sent to the // server, and stripping it before everything else keeps the cache key // identical for the same URL with or without a fragment. We deliberately do // NOT rtrim a trailing slash: a trailing slash can be a distinct resource, so // removing it would change the URL we check and split the cache key. $url = preg_replace( '/#.*$/', '', (string) $url ); // Basic validation if ( strlen( $url ) < 10 || strlen( $url ) > 2000 ) { return false; } if ( ! preg_match( '/^https?:\/\//i', $url ) ) { return false; } // FIX (audit follow-up): lowercase only the scheme://host portion. Paths and // query strings can be case-sensitive on the origin server, so lowercasing // the whole URL could send a different URL to URLhaus (missing a malicious // path) and split the cache key from the real URL. // NOTE: the '~' delimiter is deliberate — a '#' delimiter would collide with // the literal '#' inside the [^/?#] class and silently invalidate the pattern. return preg_replace_callback( '~^(https?://[^/?#]+)~i', static function ( $m ) { return strtolower( $m[1] ); }, $url ); } /** * Check local cache * * @param string $url URL to check * @return array|false|null */ private static function check_local_cache( $url ) { if ( self::$url_cache === null ) { self::$url_cache = get_option( self::OPTION_URL_CACHE, array() ); } $url_key = md5( $url ); if ( isset( self::$url_cache[ $url_key ] ) ) { $entry = self::$url_cache[ $url_key ]; if ( isset( $entry['cached_at'] ) && ( time() - $entry['cached_at'] ) < self::CACHE_DURATION ) { return isset( $entry['url_info'] ) ? $entry['url_info'] : false; } } return null; } /** * Add URL to cache * * @param string $url URL * @param array|false $url_info Info or false if clean */ private static function add_to_cache( $url, $url_info ) { if ( self::$url_cache === null ) { self::$url_cache = get_option( self::OPTION_URL_CACHE, array() ); } $url_key = md5( $url ); self::$url_cache[ $url_key ] = array( 'cached_at' => time(), 'url_info' => $url_info, ); // Limit cache size if ( count( self::$url_cache ) > self::MAX_CACHE_SIZE ) { uasort( self::$url_cache, function( $a, $b ) { return ( $a['cached_at'] ?? 0 ) - ( $b['cached_at'] ?? 0 ); }); self::$url_cache = array_slice( self::$url_cache, (int)( self::MAX_CACHE_SIZE * 0.2 ), null, true ); } update_option( self::OPTION_URL_CACHE, self::$url_cache, false ); } /** * Query URLhaus API * * @param string $url URL to check * @return array|null Parsed API response array, or null on a transient failure */ private static function query_api( $url ) { self::$api_calls++; $response = wp_remote_post( self::API_URL, array( 'timeout' => 5, 'body' => array( 'url' => $url, ), 'headers' => array( 'User-Agent' => 'GuardPress/' . self::PLUGIN_VERSION . ' (+https://guardpress.ai)', ), ) ); // FIX (audit M-01): a transient failure must be distinguishable from a real // "clean" answer so the caller can fail OPEN without caching as clean. // Return null for ANY failure; only a well-formed JSON body is a real result. if ( is_wp_error( $response ) ) { return null; } if ( (int) wp_remote_retrieve_response_code( $response ) !== 200 ) { return null; // 429 / 5xx / other — temporary, not a verdict. } $body = wp_remote_retrieve_body( $response ); $data = json_decode( $body, true ); if ( ! is_array( $data ) || ! isset( $data['query_status'] ) ) { return null; // malformed / empty JSON — not a verdict. } return $data; } /** * Parse URLhaus API response * * @param array $response API response * @return array Parsed info */ private static function parse_response( $response ) { $info = array( 'source' => 'URLhaus', 'confidence' => 1.0, 'severity' => 'critical', 'is_known' => true, ); if ( isset( $response['threat'] ) ) { $info['threat_type'] = sanitize_text_field( $response['threat'] ); } if ( isset( $response['url_status'] ) ) { $info['status'] = sanitize_text_field( $response['url_status'] ); } if ( isset( $response['tags'] ) && is_array( $response['tags'] ) ) { $info['tags'] = array_map( 'sanitize_text_field', $response['tags'] ); $info['malware_name'] = implode( ', ', array_slice( $info['tags'], 0, 3 ) ); } if ( isset( $response['date_added'] ) ) { $info['first_seen'] = sanitize_text_field( $response['date_added'] ); } $info['description'] = sprintf( /* translators: %s is the threat type (e.g. malware distribution) */ __( 'Known malicious URL: %s', 'ai-cyberguard' ), $info['threat_type'] ?? 'malware distribution' ); return $info; } /** * Reset API counter */ public static function reset_api_counter() { self::$api_calls = 0; } /** * Get API call count */ public static function get_api_calls() { return self::$api_calls; } /** * Clear cache */ public static function clear_cache() { self::$url_cache = array(); delete_option( self::OPTION_URL_CACHE ); } }