update( Softvolt_Ai_Bodyguard_Db::table( 'scans' ), array( 'status' => 'aborted', 'finished_at' => gmdate( 'Y-m-d H:i:s' ) ), array( 'id' => (int) $old['scan_id'] ) ); } $wpdb->insert( Softvolt_Ai_Bodyguard_Db::table( 'scans' ), array( 'type' => 'scheduled' === $type ? 'scheduled' : 'manual', 'status' => 'running', 'started_at' => gmdate( 'Y-m-d H:i:s' ), ) ); $scan_id = (int) $wpdb->insert_id; if ( ! $scan_id ) { return new WP_Error( 'svabg_db', __( 'The scan could not be recorded. Deactivate and reactivate the plugin to recreate its tables.', 'ai-guardwall' ) ); } $last = self::last_scan(); $state = array( 'scan_id' => $scan_id, 'type' => $type, 'stage' => 'enumerate', 'offset' => 0, // The last scan list row done. 'total_files' => 0, 'files_scanned' => 0, 'findings' => 0, 'critical' => 0, 'started' => microtime( true ), 'started_ts' => time(), 'db' => array(), 'changes' => array(), 'hash_batch' => array(), 'baseline' => (bool) $wpdb->get_var( $wpdb->prepare( 'SELECT 1 FROM %i LIMIT 1', Softvolt_Ai_Bodyguard_Db::table( 'filehash' ) ) ), // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Maintenance query on demand. 'updated_slugs' => self::updated_slugs_since( $last ? $last['finished_at'] : '' ), 'core_updated' => get_option( 'svabg_last_scan_wp_version', '' ) !== Softvolt_Ai_Bodyguard_Helpers::wp_version(), 'last_scan_time' => $last && $last['finished_at'] ? strtotime( $last['finished_at'] . ' UTC' ) : 0, 'ai_queue' => null, 'errors' => array(), 'current' => '', 'message' => __( 'Preparing…', 'ai-guardwall' ), ); self::save( $state ); Softvolt_Ai_Bodyguard_Logger::log( 'info', 'scan_started', sprintf( /* translators: 1: scan ID, 2: type */ __( 'Scan #%1$d started (%2$s).', 'ai-guardwall' ), $scan_id, $type ) ); Softvolt_Ai_Bodyguard_Integrity::core_checksums(); return $scan_id; } /** * Run for up to $budget seconds. * * @since 1.0.0 * @param int $budget Seconds. * @return array progress */ public static function step( $budget = 12 ) { $state = self::state(); if ( empty( $state['scan_id'] ) || 'done' === $state['stage'] ) { return self::progress( $state ); } Softvolt_Ai_Bodyguard_Helpers::raise_limits( max( 60, (int) $budget * 3 ) ); $deadline = microtime( true ) + max( 3, (int) $budget ); // Keep the database connection from being counted as idle during long file batches. while ( microtime( true ) < $deadline && 'done' !== $state['stage'] ) { try { switch ( $state['stage'] ) { case 'enumerate': $count = Softvolt_Ai_Bodyguard_File_Scanner::enumerate( $state['scan_id'] ); if ( is_wp_error( $count ) ) { $state['errors'][] = $count->get_error_message(); $state['stage'] = 'database'; } else { $state['total_files'] = (int) $count; $state['stage'] = 'files'; } $state['message'] = __( 'Scanning files…', 'ai-guardwall' ); break; case 'files': self::files_stage( $state, $deadline ); break; case 'database': $state['message'] = __( 'Scanning the database…', 'ai-guardwall' ); if ( Softvolt_Ai_Bodyguard_Db_Scanner::step( $state['db'], $state, $deadline ) ) { $state['stage'] = 'config'; } break; case 'config': $state['message'] = __( 'Checking configuration and exposure…', 'ai-guardwall' ); Softvolt_Ai_Bodyguard_Config_Scanner::run( $state ); $state['stage'] = 'audit'; break; case 'audit': $state['message'] = __( 'Checking for known vulnerabilities, exposed files and weak passwords…', 'ai-guardwall' ); if ( Softvolt_Ai_Bodyguard_Audit::step( $state, $deadline ) ) { $state['stage'] = 'ai'; } break; case 'ai': self::ai_stage( $state, $deadline ); break; case 'finalize': self::finalize( $state ); $state['stage'] = 'done'; break; } } catch ( Throwable $e ) { $state['errors'][] = Softvolt_Ai_Bodyguard_Helpers::trim_text( $e->getMessage(), 300 ) . ( ! empty( $state['current'] ) ? ' @ ' . $state['current'] : '' ); Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'error', sprintf( /* translators: %s: value */ __( 'Scan error: %s', 'ai-guardwall' ), $e->getMessage() ), array( 'file' => $state['current'] ) ); if ( 'files' === $state['stage'] ) { $state['offset'] = isset( $state['offset_next'] ) ? $state['offset_next'] : $state['offset']; // Skip the file that crashed. } elseif ( 'ai' === $state['stage'] ) { $state['stage'] = 'finalize'; } elseif ( in_array( $state['stage'], array( 'database', 'config', 'audit' ), true ) ) { $next = array( 'database' => 'config', 'config' => 'audit', 'audit' => 'ai' ); $state['stage'] = $next[ $state['stage'] ]; } } self::save( $state ); } return self::progress( $state ); } private static function files_stage( array &$state, $deadline ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'scanlist' ); $n = 0; while ( microtime( true ) < $deadline ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT id, path FROM %i WHERE scan_id = %d AND id > %d ORDER BY id LIMIT 200", $table, (int) $state['scan_id'], (int) $state['offset'] ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery if ( ! $rows ) { $state['stage'] = 'database'; $state['message'] = __( 'Scanning the database…', 'ai-guardwall' ); break; } foreach ( $rows as $row ) { if ( microtime( true ) >= $deadline ) { break 2; } $state['offset_next'] = (int) $row['id']; if ( '' !== (string) $row['path'] ) { Softvolt_Ai_Bodyguard_File_Scanner::scan_file( (string) $row['path'], $state ); } $state['offset'] = (int) $row['id']; if ( ++$n % 200 === 0 ) { Softvolt_Ai_Bodyguard_File_Scanner::flush_hashes( $state ); self::save( $state ); } } } Softvolt_Ai_Bodyguard_File_Scanner::flush_hashes( $state ); } /** * Forget a scan's list of files (when it finished or was cancelled), and lists left by scans that died. * * @param int $scan_id Scan. */ public static function drop_list( $scan_id ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'scanlist' ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE scan_id <= %d", $table, (int) $scan_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } private static function ai_stage( array &$state, $deadline ) { unset( $deadline ); // Findings are analysed when the owner asks for it, on the Findings page. $state['stage'] = 'finalize'; } private static function finalize( array &$state ) { global $wpdb; $scan_id = (int) $state['scan_id']; $table = Softvolt_Ai_Bodyguard_Db::table( 'filehash' ); // Files that vanished since the last scan. if ( ! empty( $state['baseline'] ) ) { $deleted = $wpdb->get_col( $wpdb->prepare( "SELECT path FROM %i WHERE scan_id < %d LIMIT 500", $table, $scan_id ) ); foreach ( (array) $deleted as $path ) { if ( count( $state['changes'] ) < 600 ) { $state['changes'][] = array( 'type' => 'deleted', 'path' => $path ); } } } $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE scan_id < %d", $table, $scan_id ) ); Softvolt_Ai_Bodyguard_Findings::resolve_stale( $scan_id ); $counts = Softvolt_Ai_Bodyguard_Findings::counts( $scan_id ); $stats = array( 'type' => $state['type'], 'files_scanned' => (int) $state['files_scanned'], 'total_files' => (int) $state['total_files'], 'findings' => (int) $counts['total'], 'severity' => array_intersect_key( $counts, array_flip( Softvolt_Ai_Bodyguard_Helpers::severities() ) ), 'by_category' => Softvolt_Ai_Bodyguard_Findings::count_by( 'category', $scan_id ), 'confirmed' => isset( Softvolt_Ai_Bodyguard_Findings::count_by( 'verdict', $scan_id )['confirmed'] ) ? Softvolt_Ai_Bodyguard_Findings::count_by( 'verdict', $scan_id )['confirmed'] : 0, 'changes' => count( $state['changes'] ), 'duration' => (int) round( microtime( true ) - (float) $state['started'] ), 'errors' => array_slice( (array) $state['errors'], 0, 20 ), 'admins' => isset( $state['admins'] ) ? $state['admins'] : array(), 'wp_version' => Softvolt_Ai_Bodyguard_Helpers::wp_version(), ); $wpdb->update( Softvolt_Ai_Bodyguard_Db::table( 'scans' ), array( 'status' => 'finished', 'finished_at' => gmdate( 'Y-m-d H:i:s' ), 'stats' => wp_json_encode( $stats ), ), array( 'id' => $scan_id ) ); update_option( 'svabg_last_scan_wp_version', Softvolt_Ai_Bodyguard_Helpers::wp_version(), false ); self::drop_list( $scan_id ); $state['message'] = __( 'Scan finished.', 'ai-guardwall' ); Softvolt_Ai_Bodyguard_Logger::log( $counts['critical'] > 0 ? 'critical' : 'info', 'scan_finished', sprintf( /* translators: 1: scan ID, 2: files scanned, 3: findings, 4: critical */ __( 'Scan #%1$d finished: %2$d files, %3$d findings (%4$d critical).', 'ai-guardwall' ), $scan_id, $stats['files_scanned'], $stats['findings'], $counts['critical'] ) ); do_action( 'svabg_scan_finished', $scan_id, $stats ); if ( ! empty( $state['changes'] ) && ! empty( $state['baseline'] ) ) { do_action( 'svabg_file_changes', $scan_id, $state['changes'] ); } } /** * Progress for the UI. * * @param array|null $state State. * @return array */ public static function progress( $state = null ) { $state = null === $state ? self::state() : $state; if ( empty( $state['scan_id'] ) ) { return array( 'running' => false, 'done' => true, 'percent' => 0, 'stage' => 'idle', 'message' => __( 'No scan has run yet.', 'ai-guardwall' ) ); } $stage = $state['stage']; $percent = 0; switch ( $stage ) { case 'enumerate': $percent = 2; break; case 'files': $percent = 5 + ( $state['total_files'] > 0 ? 70 * min( 1, $state['files_scanned'] / $state['total_files'] ) : 0 ); break; case 'database': $percent = 75 + 15 * Softvolt_Ai_Bodyguard_Db_Scanner::progress( $state['db'] ); break; case 'config': $percent = 90; break; case 'audit': $percent = 91 + 3 * Softvolt_Ai_Bodyguard_Audit::progress( $state ); break; case 'ai': $percent = 94; break; case 'finalize': $percent = 98; break; case 'done': $percent = 100; break; } $counts = Softvolt_Ai_Bodyguard_Findings::counts( (int) $state['scan_id'] ); return array( 'running' => 'done' !== $stage, 'done' => 'done' === $stage, 'stalled' => 'done' !== $stage && ! empty( $state['updated'] ) && ( time() - (int) $state['updated'] ) > 3 * MINUTE_IN_SECONDS, 'scan_id' => (int) $state['scan_id'], 'stage' => $stage, 'percent' => (int) round( $percent ), 'files_scanned' => (int) $state['files_scanned'], 'total_files' => (int) $state['total_files'], 'findings' => (int) $counts['total'], 'counts' => $counts, 'current' => isset( $state['current'] ) ? $state['current'] : '', 'message' => isset( $state['message'] ) ? $state['message'] : '', 'errors' => isset( $state['errors'] ) ? array_slice( (array) $state['errors'], -5 ) : array(), 'elapsed' => isset( $state['started_ts'] ) ? time() - (int) $state['started_ts'] : 0, ); } public static function cancel() { global $wpdb; $state = self::state(); if ( ! empty( $state['scan_id'] ) && 'done' !== $state['stage'] ) { $wpdb->update( Softvolt_Ai_Bodyguard_Db::table( 'scans' ), array( 'status' => 'aborted', 'finished_at' => gmdate( 'Y-m-d H:i:s' ) ), array( 'id' => (int) $state['scan_id'] ) ); self::drop_list( (int) $state['scan_id'] ); Softvolt_Ai_Bodyguard_Logger::log( 'info', 'scan_finished', sprintf( /* translators: %d: scan ID */ __( 'Scan #%d was cancelled.', 'ai-guardwall' ), (int) $state['scan_id'] ) ); } $state['stage'] = 'done'; $state['message'] = __( 'Scan cancelled.', 'ai-guardwall' ); self::save( $state ); wp_clear_scheduled_hook( Softvolt_Ai_Bodyguard_Cron::HOOK_TICK ); } public static function get_scan( $scan_id ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'scans' ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = %d", $table, (int) $scan_id ), ARRAY_A ); if ( $row ) { $row['stats_arr'] = ! empty( $row['stats'] ) ? json_decode( $row['stats'], true ) : array(); } return $row; } public static function last_scan() { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'scans' ); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE status = 'finished' ORDER BY id DESC LIMIT 1", $table ), ARRAY_A ); if ( $row ) { $row['stats_arr'] = ! empty( $row['stats'] ) ? json_decode( $row['stats'], true ) : array(); } return $row; } public static function scans( $limit = 10 ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'scans' ); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i ORDER BY id DESC LIMIT %d", $table, (int) $limit ), ARRAY_A ); $rows = is_array( $rows ) ? $rows : array(); foreach ( $rows as $i => $row ) { $rows[ $i ]['stats_arr'] = ! empty( $row['stats'] ) ? json_decode( $row['stats'], true ) : array(); } return $rows; } public static function purge_old_scans( $keep = 20 ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'scans' ); $ids = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i ORDER BY id DESC LIMIT %d, 1000", $table, (int) $keep ) ); if ( $ids ) { $ids = array_map( 'intval', $ids ); $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE id IN ( {$placeholders} )", array_merge( array( $table ), $ids ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). $findings = Softvolt_Ai_Bodyguard_Db::table( 'findings' ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE scan_id IN ( {$placeholders} ) AND status IN ('resolved','deleted','repaired','cleaned')", array_merge( array( $findings ), $ids ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $placeholders holds %d placeholders only; the IDs are passed to prepare(). } Softvolt_Ai_Bodyguard_Remediation::purge_quarantine( 30 ); } /** * Plugins/themes updated since a date, from the activity log. */ private static function updated_slugs_since( $since ) { if ( '' === $since ) { return array(); } $rows = Softvolt_Ai_Bodyguard_Logger::query( array( 'since' => $since, 'per_page' => 300 ) ); $slugs = array(); foreach ( $rows['rows'] as $row ) { if ( ! in_array( $row['event'], array( 'plugin_change', 'theme_change' ), true ) ) { continue; } if ( ! preg_match( '/^(Plugin|Theme) (update|install): (.+)$/i', $row['message'], $m ) ) { continue; } foreach ( explode( ', ', $m[3] ) as $item ) { $item = trim( $item ); $slugs[] = false !== strpos( $item, '/' ) ? dirname( $item ) : $item; } } return array_values( array_unique( $slugs ) ); } }