'object', 'properties' => array( 'verdict' => array( 'type' => 'string', 'enum' => array( 'confirmed_malware', 'suspicious', 'likely_legitimate', 'needs_manual_review' ), ), 'confidence' => array( 'type' => 'integer' ), 'severity' => array( 'type' => 'string', 'enum' => array( 'critical', 'high', 'medium', 'low', 'info' ), ), 'title' => array( 'type' => 'string' ), 'why' => array( 'type' => 'string' ), 'affected_functionality' => array( 'type' => 'string' ), 'remediation' => array( 'type' => 'string', 'enum' => array( 'delete', 'replace_official_file', 'replace_plugin', 'replace_theme', 'remove_db_record', 'remove_cron', 'remove_js', 'remove_spam', 'remove_user', 'fix_config', 'update', 'manual_review', 'no_action' ), ), 'remediation_details' => array( 'type' => 'string' ), 'replace_from_official_safer' => array( 'type' => 'boolean' ), 'indicators' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), ), 'cleanup_order' => array( 'type' => 'integer' ), ), 'required' => array( 'verdict', 'confidence', 'severity', 'title', 'why', 'affected_functionality', 'remediation', 'remediation_details', 'replace_from_official_safer', 'indicators', 'cleanup_order' ), 'additionalProperties' => false, ); } /** * The system instructions: the role, the knowledge files and the answer rules. * * @param string $purpose malware|hardening. * @param string $rules Extra answer rules. * @return array blocks */ private static function system_blocks( $purpose, $rules ) { $knowledge = Softvolt_Ai_Bodyguard_Knowledge::text_for( $purpose ); $role = 'You are the AI analyst inside "AI GuardWall", a WordPress security plugin. You help the site owner (who may not be technical) understand and safely clean their own WordPress site. ' . 'Follow the knowledge files below exactly: they define what counts as malware, how to minimise false positives, and how to report.' . ( '' !== $knowledge ? "\n\n" . $knowledge : '' ); return array( array( 'text' => $role, 'cache' => true, ), array( 'text' => $rules, 'cache' => false, ), ); } /** * Analyse one finding and store the answer on it. * * @since 1.0.0 * @param int $finding_id Finding. * @return array|WP_Error The stored analysis. */ public static function analyze_finding( $finding_id ) { $finding = Softvolt_Ai_Bodyguard_Findings::get( $finding_id ); if ( ! $finding ) { return new WP_Error( 'svabg_no_finding', __( 'That finding no longer exists.', 'ai-guardwall' ) ); } $consent = Softvolt_Ai_Bodyguard_Providers::consent_error(); if ( $consent ) { return $consent; } $client = Softvolt_Ai_Bodyguard_Providers::client(); if ( is_wp_error( $client ) ) { return $client; } $rules = self::rules(); $system = self::system_blocks( 'malware', $rules ); $user = self::finding_prompt( $finding ); if ( $client instanceof Softvolt_Ai_Bodyguard_Claude_Client ) { /* translators: 1: finding ID, 2: where it is. */ $client->label = sprintf( __( 'Analyse finding #%1$d (%2$s)', 'ai-guardwall' ), $finding_id, Softvolt_Ai_Bodyguard_Helpers::trim_text( (string) $finding['location'], 60 ) ); } $result = $client->complete( $system, $user, (int) Softvolt_Ai_Bodyguard_Settings::get( 'ai_max_tokens', 6000 ), self::schema() ); if ( Softvolt_Ai_Bodyguard_Claude::is_waiting( $result ) ) { return $result; } if ( is_wp_error( $result ) ) { Softvolt_Ai_Bodyguard_Providers::remember_error( $result->get_error_message() ); Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'ai_analysis', sprintf( /* translators: 1: finding ID, 2: value */ __( 'AI analysis of finding #%1$d failed: %2$s', 'ai-guardwall' ), $finding_id, $result->get_error_message() ) ); return $result; } $json = self::normalise( $result['json'] ); if ( null === $json ) { Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'ai_analysis', sprintf( /* translators: %d: finding ID */ __( 'AI analysis of finding #%d returned no usable JSON.', 'ai-guardwall' ), $finding_id ), array( 'text' => Softvolt_Ai_Bodyguard_Helpers::trim_text( $result['text'], 800 ) ) ); return new WP_Error( 'svabg_ai_json', __( 'The model did not answer in the expected format. Try again or choose another model.', 'ai-guardwall' ) ); } $json['model'] = isset( $result['model'] ) ? $result['model'] : ''; $json['provider'] = (string) Softvolt_Ai_Bodyguard_Settings::get( 'provider' ); $json['analysed_at'] = gmdate( 'Y-m-d H:i:s' ); $json['usage'] = isset( $result['usage'] ) ? $result['usage'] : array(); Softvolt_Ai_Bodyguard_Findings::set_ai( $finding_id, $json['verdict'], $json['confidence'], $json ); Softvolt_Ai_Bodyguard_Logger::log( 'info', 'ai_analysis', sprintf( /* translators: 1: finding ID, 2: verdict, 3: confidence */ __( 'AI analysed finding #%1$d: %2$s (%3$d%%).', 'ai-guardwall' ), $finding_id, $json['verdict'], $json['confidence'] ), array( 'usage' => $json['usage'] ) ); return $json; } /** * The rules of a verdict (with the JSON schema it follows), for the model and for Claude Desktop. * * @since 1.6.0 * @return string */ public static function rules() { return 'Answer with a single JSON object and nothing else, following this schema exactly: ' . wp_json_encode( self::schema() ) . "\n\nRules for the answer:\n" . "- verdict: confirmed_malware only when the evidence is unambiguous (web shell, backdoor, encoded payload loader, hidden admin creation, SEO spam, redirect malware, miner, skimmer). suspicious when intent is unclear. likely_legitimate when this is normal plugin/theme/library code (minified or obfuscated commercial libraries, legitimate use of system functions, developer tooling). needs_manual_review when the snippet is too short to decide.\n" . "- confidence: 0-100, your confidence in the verdict.\n" . "- severity: the impact if the verdict is right.\n" . "- why: 2-5 plain sentences on what the code does and why it is (or is not) malicious; quote the decisive line(s).\n" . "- affected_functionality: which legitimate WordPress functionality could be affected by the file/record or by removing it (for example: a plugin feature, the theme, uploads, logins, nothing).\n" . "- remediation: the single best action; replace_official_file for modified core files when an official copy exists, replace_plugin/replace_theme for modified repository plugins/themes, delete only when the file is wholly malicious and you are highly confident, remove_js/remove_spam/remove_db_record for database injections, no_action for likely_legitimate.\n" . "- replace_from_official_safer: true when re-downloading the official file/plugin/theme is safer than hand-editing.\n" . "- indicators: short bullet facts (function names, domains, line numbers) that support the verdict.\n" . "- cleanup_order: 1 for backdoors/web shells (clean first), 2 for loaders and hidden admins, 3 for injected content/spam, 4 for hardening/config items, 5 for likely legitimate.\n" . '- Never recommend deleting a file unless highly confident it is malicious. Prefer evidence over assumptions.'; } /** * Analyse several findings within a time budget. * * @since 1.0.0 * @param int[] $ids Findings. * @param int $budget Seconds. * @return array|WP_Error array( 'done' => ids, 'failed' => id => message, 'remaining' => ids ), or * "waiting for Claude Desktop" once every finding without an answer has its task. */ public static function analyze_many( $ids, $budget = 25 ) { $start = microtime( true ); $done = array(); $failed = array(); $waiting = null; $ids = array_values( array_unique( array_map( 'intval', (array) $ids ) ) ); while ( $ids ) { if ( $done && Softvolt_Ai_Bodyguard_Helpers::out_of_time( $start, $budget ) ) { break; } $id = array_shift( $ids ); $result = self::analyze_finding( $id ); if ( Softvolt_Ai_Bodyguard_Claude::is_waiting( $result ) ) { // Every finding gets its task now, so Claude can answer them all in one go. $waiting = null === $waiting ? $result : $waiting; continue; } if ( is_wp_error( $result ) ) { $failed[ $id ] = $result->get_error_message(); if ( in_array( $result->get_error_code(), array( 'svabg_no_consent', 'svabg_no_key', 'svabg_no_provider', 'svabg_no_model', 'svabg_unreachable' ), true ) ) { break; // Nothing will succeed until the owner fixes the connection. } } else { $done[] = $id; } } if ( null !== $waiting ) { return $waiting; } return array( 'done' => $done, 'failed' => $failed, 'remaining' => $ids, ); } /** * Build the task text for one finding. * * @param array $f Finding (hydrated). * @return string */ public static function finding_prompt( $f ) { $meta = $f['meta_arr']; $lines = array(); $lines[] = '## Site facts'; $lines[] = '- WordPress ' . Softvolt_Ai_Bodyguard_Helpers::wp_version() . ', PHP ' . PHP_VERSION . ', locale ' . get_locale(); $lines[] = '- Site host: ' . (string) wp_parse_url( home_url(), PHP_URL_HOST ); $lines[] = '- Active theme: ' . wp_get_theme()->get( 'Name' ) . ' (' . get_stylesheet() . ')'; if ( ! empty( $meta['plugin_slug'] ) ) { $index = Softvolt_Ai_Bodyguard_Integrity::plugin_index(); $slug = $meta['plugin_slug']; $name = isset( $index[ $slug ] ) ? $index[ $slug ]['name'] . ' ' . $index[ $slug ]['version'] : $slug; $lines[] = '- Plugin: ' . $name . ( isset( $meta['integrity'] ) ? ' (checksum status: ' . $meta['integrity'] . ')' : '' ); } if ( ! empty( $meta['theme_slug'] ) ) { $lines[] = '- Theme folder: ' . $meta['theme_slug']; } if ( isset( $meta['integrity'] ) && empty( $meta['plugin_slug'] ) ) { $lines[] = '- Official checksum status: ' . $meta['integrity'] . ' (verified files are never sent to you; "modified" means the file differs from WordPress.org, "unknown" means WordPress.org has no such file, "unavailable" means no checksums exist for it)'; } $lines[] = ''; $lines[] = '## Finding'; $lines[] = '- Category: ' . $f['category']; $lines[] = '- Location: ' . $f['location'] . ( $f['line'] ? ' (line ' . (int) $f['line'] . ')' : '' ); $lines[] = '- Scanner title: ' . $f['title']; $lines[] = '- Scanner severity/confidence: ' . $f['severity'] . ' / ' . (int) $f['confidence'] . '%'; $lines[] = '- Scanner reasoning: ' . wp_strip_all_tags( $f['description'] ); if ( ! empty( $meta['hits'] ) && is_array( $meta['hits'] ) ) { $lines[] = '- Matched indicators:'; foreach ( array_slice( $meta['hits'], 0, 12 ) as $hit ) { $lines[] = sprintf( ' - [%s] %s (line %d, %dx): %s', $hit['id'], $hit['title'], (int) $hit['line'], (int) $hit['count'], isset( $hit['excerpt'] ) ? $hit['excerpt'] : '' ); } } // No email address or other contact detail of a user is sent. foreach ( array( 'size', 'mtime_human', 'post_type', 'post_status', 'option_name', 'meta_key', 'user_login', 'registered', 'hook', 'details' ) as $key ) { if ( ! empty( $meta[ $key ] ) && is_scalar( $meta[ $key ] ) ) { $lines[] = '- ' . str_replace( '_', ' ', $key ) . ': ' . $meta[ $key ]; } } $lines[] = ''; $lines[] = '## Code / content to analyse'; $snippet = self::snippet_for( $f ); $lines[] = '' !== $snippet ? "```\n" . $snippet . "\n```" : '(no content available; decide from the indicators above or ask for manual review)'; $lines[] = ''; $lines[] = 'Analyse this finding and answer with the JSON object only.'; // Database passwords, keys, salts, tokens and email addresses never leave the site. return Softvolt_Ai_Bodyguard_Helpers::redact( implode( "\n", $lines ) ); } /** * Files that hold credentials by nature (wp-config.php, .env, SQL dumps, key files): only the matched * lines are ever sent from them, never the whole file. * * @since 1.5.1 * @param string $rel Site-relative path. * @return bool */ public static function is_sensitive_file( $rel ) { return (bool) preg_match( '/(^|\/)(wp-config[^\/]*\.php|\.env[^\/]*|[^\/]*\.sql(\.gz)?|\.htpasswd|\.user\.ini|php\.ini|auth\.json|\.git-credentials|[^\/]*\.(pem|key|p12|pfx|crt)|id_[rd]sa[^\/]*)$/i', (string) $rel ); } /** * The code around the matched lines (or the whole file when small and not a file of credentials). * * @param array $f Finding. * @return string */ public static function snippet_for( $f ) { $max = (int) Softvolt_Ai_Bodyguard_Settings::get( 'ai_snippet_chars', 12000 ); $meta = $f['meta_arr']; if ( ! empty( $meta['rel'] ) ) { $abs = Softvolt_Ai_Bodyguard_Helpers::safe_abs_path( $meta['rel'] ); if ( $abs && is_readable( $abs ) ) { $size = (int) filesize( $abs ); $content = (string) file_get_contents( $abs, false, null, 0, min( $size, 6 * 1024 * 1024 ) ); $sensitive = self::is_sensitive_file( $meta['rel'] ); if ( $size <= $max && ! $sensitive ) { $i = 1; $out = array(); foreach ( preg_split( '/\r\n|\r|\n/', $content ) as $line ) { $out[] = sprintf( '%5d | %s', $i++, strlen( $line ) > 1200 ? substr( $line, 0, 1200 ) . ' …[line truncated]' : $line ); } return implode( "\n", $out ); } $lines_hit = array(); if ( $f['line'] ) { $lines_hit[] = (int) $f['line']; } foreach ( isset( $meta['hits'] ) ? (array) $meta['hits'] : array() as $hit ) { if ( ! empty( $hit['line'] ) ) { $lines_hit[] = (int) $hit['line']; } } $lines_hit = array_values( array_unique( $lines_hit ) ); sort( $lines_hit ); if ( ! $lines_hit ) { $lines_hit = array( 1 ); } if ( $sensitive ) { $parts = array( '(This file holds credentials by nature, so only the matched lines are shown, with secrets removed.)' ); foreach ( array_slice( $lines_hit, 0, 12 ) as $ln ) { $parts[] = Softvolt_Ai_Bodyguard_Helpers::lines_around( $content, $ln, 3, 1500 ); } return Softvolt_Ai_Bodyguard_Helpers::redact( substr( implode( "\n ...\n", array_unique( $parts ) ), 0, $max ) ); } $per = max( 1500, (int) ( $max / max( 1, count( $lines_hit ) ) ) ); $parts = array(); foreach ( $lines_hit as $ln ) { $parts[] = Softvolt_Ai_Bodyguard_Helpers::lines_around( $content, $ln, 15, $per ); } $parts[] = "\n(First 40 lines of the file for context)\n" . Softvolt_Ai_Bodyguard_Helpers::lines_around( $content, 20, 20, 3000 ); return substr( implode( "\n ...\n", array_unique( $parts ) ), 0, $max ); } } if ( ! empty( $meta['content'] ) ) { return substr( (string) $meta['content'], 0, $max ); } if ( ! empty( $f['snippet'] ) ) { return substr( (string) $f['snippet'], 0, $max ); } return ''; } /** * Check and tidy a model's JSON answer. * * @param mixed $json Decoded answer. * @return array|null */ public static function normalise( $json ) { if ( ! is_array( $json ) || empty( $json['verdict'] ) ) { return null; } $schema = self::schema(); $out = array(); foreach ( $schema['properties'] as $key => $def ) { $value = isset( $json[ $key ] ) ? $json[ $key ] : null; if ( isset( $def['enum'] ) ) { $value = is_string( $value ) ? strtolower( trim( $value ) ) : ''; if ( ! in_array( $value, $def['enum'], true ) ) { $value = 'remediation' === $key ? 'manual_review' : ( 'severity' === $key ? 'medium' : 'needs_manual_review' ); } } elseif ( 'integer' === $def['type'] ) { $value = (int) $value; if ( 'confidence' === $key ) { $value = max( 0, min( 100, $value ) ); } } elseif ( 'boolean' === $def['type'] ) { $value = (bool) $value; } elseif ( 'array' === $def['type'] ) { $value = array_values( array_filter( array_map( 'strval', is_array( $value ) ? $value : array() ) ) ); $value = array_slice( $value, 0, 20 ); } else { $value = is_scalar( $value ) ? sanitize_textarea_field( (string) $value ) : ''; $value = mb_substr( $value, 0, 4000 ); } $out[ $key ] = $value; } return $out; } }