label */ public static function actions_for( $f ) { $meta = $f['meta_arr']; $actions = array(); $file = in_array( $f['category'], array( 'core', 'plugin', 'theme', 'mu', 'dropin', 'upload', 'root', 'other', 'config' ), true ) && ! empty( $meta['rel'] ); if ( $file && ! in_array( $f['status'], array( 'quarantined', 'deleted' ), true ) ) { $base = basename( $meta['rel'] ); if ( 'wp-config.php' !== $base && ! ( '.htaccess' === $base && 'root' === $f['category'] ) ) { $actions['quarantine'] = __( 'Quarantine (move out of the site)', 'ai-guardwall' ); $actions['delete'] = __( 'Delete (keeps a quarantined copy)', 'ai-guardwall' ); } } elseif ( 'db' === $f['category'] && ! empty( $meta['table'] ) ) { switch ( $meta['table'] ) { case 'posts': $actions['clean_db'] = __( 'Remove injected code from the post', 'ai-guardwall' ); $actions['delete_record'] = __( 'Move the post to the trash', 'ai-guardwall' ); break; case 'postmeta': $actions['clean_db'] = __( 'Remove injected code from the meta value', 'ai-guardwall' ); $actions['delete_record'] = __( 'Delete the meta value', 'ai-guardwall' ); break; case 'options': $actions['clean_db'] = __( 'Remove injected code from the option', 'ai-guardwall' ); $actions['delete_record'] = __( 'Delete the option', 'ai-guardwall' ); break; case 'comments': $actions['delete_record'] = __( 'Move the comment to the trash', 'ai-guardwall' ); break; } if ( ! empty( $meta['table'] ) && false !== strpos( $f['signature'], 'active_plugin' ) ) { $actions['delete_record'] = __( 'Deactivate this plugin entry', 'ai-guardwall' ); } } elseif ( 'cron' === $f['category'] && ! empty( $meta['hook'] ) ) { $actions['remove_cron'] = __( 'Remove the scheduled task', 'ai-guardwall' ); } elseif ( 'user' === $f['category'] && ! empty( $meta['user_id'] ) ) { if ( (int) $meta['user_id'] !== get_current_user_id() ) { $actions['delete_user'] = __( 'Delete this user (content reassigned to you)', 'ai-guardwall' ); } } if ( 'config' === $f['category'] && ! empty( $meta['rule'] ) ) { $actions['apply_rule'] = __( 'Switch the hardening rule on', 'ai-guardwall' ); } if ( 'open' === $f['status'] ) { $actions['ignore'] = __( 'Ignore', 'ai-guardwall' ); $actions['false_positive'] = __( 'Mark as false positive', 'ai-guardwall' ); } elseif ( in_array( $f['status'], array( 'ignored', 'false_positive', 'resolved' ), true ) ) { $actions['reopen'] = __( 'Reopen', 'ai-guardwall' ); } return $actions; } /** * Run an action. * * @since 1.0.0 * @param int $finding_id Finding. * @param string $action Action id. * @return array|WP_Error array( 'message' => string, 'status' => new status ) */ public static function run( $finding_id, $action ) { $f = Softvolt_Ai_Bodyguard_Findings::get( $finding_id ); if ( ! $f ) { return new WP_Error( 'svabg_no_finding', __( 'That finding no longer exists.', 'ai-guardwall' ) ); } $allowed = self::actions_for( $f ); if ( ! isset( $allowed[ $action ] ) ) { return new WP_Error( 'svabg_bad_action', __( 'That action is not available for this finding.', 'ai-guardwall' ) ); } switch ( $action ) { case 'ignore': case 'false_positive': Softvolt_Ai_Bodyguard_Findings::set_status( $finding_id, 'ignore' === $action ? 'ignored' : 'false_positive' ); return array( 'message' => __( 'Noted. It will not be reported again unless the content changes.', 'ai-guardwall' ), 'status' => 'ignore' === $action ? 'ignored' : 'false_positive' ); case 'reopen': Softvolt_Ai_Bodyguard_Findings::set_status( $finding_id, 'open' ); return array( 'message' => __( 'Reopened.', 'ai-guardwall' ), 'status' => 'open' ); case 'quarantine': return self::quarantine( $f, 'quarantined' ); case 'delete': return self::quarantine( $f, 'deleted' ); case 'clean_db': return self::clean_db( $f ); case 'delete_record': return self::delete_record( $f ); case 'remove_cron': return self::remove_cron( $f ); case 'delete_user': return self::delete_user( $f ); case 'apply_rule': Softvolt_Ai_Bodyguard_Settings::set_hardening( $f['meta_arr']['rule'], true ); Softvolt_Ai_Bodyguard_Hardening::apply_all_enabled(); Softvolt_Ai_Bodyguard_Findings::set_status( $finding_id, 'cleaned' ); self::log( $f, sprintf( /* translators: %s: rule */ __( 'Hardening rule "%s" switched on.', 'ai-guardwall' ), $f['meta_arr']['rule'] ) ); return array( 'message' => __( 'The hardening rule is on.', 'ai-guardwall' ), 'status' => 'cleaned' ); } return new WP_Error( 'svabg_bad_action', __( 'Unknown action.', 'ai-guardwall' ) ); } /* ------------------------------ files ------------------------------ */ /** Quarantined copies are kept in memory once, so very large files are refused. */ const SEAL_MAX = 16777216; /** * Keep a copy of a file in the quarantine table (compressed, as hexadecimal text): no copy of a removed * file is ever written to the disk, where a server could serve or run it. * * @since 1.5.1 * @param int $finding_id Finding (0 for none). * @param string $kind quarantined | deleted | replaced | default-file. * @param string $rel Site-relative path of the original. * @param string $data File contents. * @return int|WP_Error Row id. */ public static function store_copy( $finding_id, $kind, $rel, $data ) { global $wpdb; if ( ! function_exists( 'gzdeflate' ) ) { return new WP_Error( 'svabg_move', __( 'PHP\'s zlib extension is missing, so no copy can be kept and nothing was removed. Ask your host to enable zlib, or remove the file by FTP.', 'ai-guardwall' ) ); } $packed = bin2hex( (string) gzdeflate( (string) $data, 6 ) ); // The server's largest query (MySQL and MariaDB); other databases answer nothing and are not limited here. $quiet = $wpdb->suppress_errors( true ); $limit = (int) $wpdb->get_var( 'SELECT @@max_allowed_packet' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->suppress_errors( $quiet ); if ( $limit > 0 && strlen( $packed ) > $limit * 0.9 ) { return new WP_Error( 'svabg_move', __( 'The file is too large to keep a copy of it in the database. Remove it by FTP or with the file manager in your hosting panel.', 'ai-guardwall' ) ); } $ok = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery Softvolt_Ai_Bodyguard_Db::table( 'quarantine' ), array( 'finding_id' => (int) $finding_id, 'kind' => substr( (string) $kind, 0, 16 ), 'path' => (string) $rel, 'md5' => md5( (string) $data ), 'size' => strlen( (string) $data ), 'content' => $packed, 'created_at' => gmdate( 'Y-m-d H:i:s' ), ), array( '%d', '%s', '%s', '%s', '%d', '%s', '%s' ) ); if ( ! $ok ) { return new WP_Error( 'svabg_move', sprintf( /* translators: %s: database error */ __( 'No copy could be kept, so nothing was removed (%s).', 'ai-guardwall' ), $wpdb->last_error ) ); } return (int) $wpdb->insert_id; } private static function quarantine( $f, $new_status ) { $rel = $f['meta_arr']['rel']; $abs = Softvolt_Ai_Bodyguard_Helpers::safe_abs_path( $rel ); if ( ! $abs || ! file_exists( $abs ) ) { Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'resolved' ); return array( 'message' => __( 'The file is already gone.', 'ai-guardwall' ), 'status' => 'resolved' ); } if ( (int) @filesize( $abs ) > self::SEAL_MAX ) { return new WP_Error( 'svabg_move', __( 'The file is too large to keep a quarantined copy (16 MB at most). Remove it by FTP or with the file manager in your hosting panel.', 'ai-guardwall' ) ); } $data = @file_get_contents( $abs ); if ( false === $data ) { return new WP_Error( 'svabg_move', __( 'The file could not be read. Check its permissions, or remove it by FTP.', 'ai-guardwall' ) ); } $copy = self::store_copy( (int) $f['id'], $new_status, $rel, $data ); if ( is_wp_error( $copy ) ) { return $copy; } // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- removes the infected file and needs the result. if ( ! @unlink( $abs ) ) { self::drop_copy( $copy ); return new WP_Error( 'svabg_move', __( 'The file could not be moved. Check the folder permissions, or remove it by FTP.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], $new_status, 'quarantine:' . $copy ); self::log( $f, sprintf( /* translators: %s: path */ __( 'File moved to quarantine: %s', 'ai-guardwall' ), $rel ) ); return array( 'message' => 'deleted' === $new_status ? __( 'Deleted. A sealed copy is kept for 30 days.', 'ai-guardwall' ) : __( 'Moved to quarantine. The site can no longer run it; a sealed copy is kept for 30 days.', 'ai-guardwall' ), 'status' => $new_status, ); } /* ---------------------------- database ----------------------------- */ /** * Strip injected scripts, hidden iframes and hidden link blocks from HTML. * * @since 1.0.0 * @param string $html Content. * @return string */ public static function clean_html( $html ) { $home = (string) wp_parse_url( home_url(), PHP_URL_HOST ); $out = preg_replace_callback( '/]*>.*?<\/script>/is', function ( $m ) use ( $home ) { $tag = $m[0]; if ( Softvolt_Ai_Bodyguard_Signatures::scan( $tag, array( 'type' => 'js', 'category' => 'db' ) ) ) { return ''; } if ( preg_match( '/src\s*=\s*[\'"](?:https?:)?\/\/([^\'"\/]+)/i', $tag, $src ) ) { $host = strtolower( $src[1] ); if ( ! preg_match( '/' . Softvolt_Ai_Bodyguard_Signatures::EMBED_HOSTS . '$/i', $host ) && '' !== $home && false === strpos( $host, $home ) && preg_match( '/\.' . Softvolt_Ai_Bodyguard_Signatures::BAD_TLDS . '$/i', $host ) ) { return ''; } } return $tag; }, (string) $html ); $out = preg_replace( '/]*(?:(?:width|height)\s*=\s*[\'"]?\s*0\s*[\'"]?|display\s*:\s*none|visibility\s*:\s*hidden|position\s*:\s*absolute\s*;\s*(?:left|top)\s*:\s*-\d{3,})[^>]*>.*?<\/iframe>/is', '', $out ); $out = preg_replace( '/<(div|span|p)\b[^>]+style\s*=\s*[\'"][^\'"]*(?:display\s*:\s*none|visibility\s*:\s*hidden|position\s*:\s*absolute\s*;\s*(?:left|top)\s*:\s*-\d{3,}|text-indent\s*:\s*-\d{3,}|font-size\s*:\s*0)[^\'"]*[\'"][^>]*>\s*(?:<[^>]+>\s*){0,3}/is', '', $out ); $out = preg_replace( '/\bndsw\s*===?\s*undefined.*$/is', '', $out ); return null === $out ? (string) $html : $out; } private static function clean_recursive( $value ) { if ( is_string( $value ) ) { return self::clean_html( $value ); } if ( is_array( $value ) ) { foreach ( $value as $k => $v ) { $value[ $k ] = self::clean_recursive( $v ); } } return $value; } private static function clean_db( $f ) { $meta = $f['meta_arr']; switch ( $meta['table'] ) { case 'posts': $post = get_post( (int) $meta['id'] ); if ( ! $post ) { break; } $backups = (array) get_post_meta( $post->ID, '_svabg_backup_content', true ); $backups[] = array( 'time' => time(), 'content' => $post->post_content ); update_post_meta( $post->ID, '_svabg_backup_content', array_slice( $backups, -3 ) ); $cleaned = self::clean_html( $post->post_content ); if ( $cleaned === $post->post_content ) { return new WP_Error( 'svabg_nothing', __( 'Nothing matched the automatic cleaner. Edit the post by hand and remove the injected code.', 'ai-guardwall' ) ); } kses_remove_filters(); $result = wp_update_post( array( 'ID' => $post->ID, 'post_content' => $cleaned ), true ); kses_init_filters(); if ( is_wp_error( $result ) ) { return $result; } break; case 'postmeta': $value = get_post_meta( (int) $meta['id'], $meta['meta_key'], true ); $cleaned = self::clean_recursive( $value ); if ( $cleaned === $value ) { return new WP_Error( 'svabg_nothing', __( 'Nothing matched the automatic cleaner. Review the value by hand.', 'ai-guardwall' ) ); } update_post_meta( (int) $meta['id'], '_svabg_backup_' . sanitize_key( $meta['meta_key'] ), $value ); update_post_meta( (int) $meta['id'], $meta['meta_key'], $cleaned ); break; case 'options': $value = get_option( $meta['option_name'] ); $cleaned = self::clean_recursive( $value ); if ( $cleaned === $value ) { return new WP_Error( 'svabg_nothing', __( 'Nothing matched the automatic cleaner. Review the option by hand (for example the widget or theme-code screen that owns it).', 'ai-guardwall' ) ); } update_option( '_svabg_backup_' . substr( md5( $meta['option_name'] ), 0, 12 ), array( 'name' => $meta['option_name'], 'time' => time(), 'value' => $value ), false ); update_option( $meta['option_name'], $cleaned ); break; default: return new WP_Error( 'svabg_bad_action', __( 'This record cannot be cleaned automatically.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'cleaned' ); self::log( $f, sprintf( /* translators: %s: location */ __( 'Injected code removed from %s', 'ai-guardwall' ), $f['location'] ) ); return array( 'message' => __( 'Injected code removed. A backup of the original value was kept.', 'ai-guardwall' ), 'status' => 'cleaned' ); } private static function delete_record( $f ) { $meta = $f['meta_arr']; if ( false !== strpos( $f['signature'], 'active_plugin' ) && ! empty( $meta['details'] ) ) { $active = (array) get_option( 'active_plugins', array() ); $active = array_values( array_diff( $active, array( $meta['details'] ) ) ); update_option( 'active_plugins', $active ); Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'cleaned' ); self::log( $f, sprintf( /* translators: %s: details */ __( 'Active plugin entry removed: %s', 'ai-guardwall' ), $meta['details'] ) ); return array( 'message' => __( 'The plugin entry was removed from active_plugins. Delete its files too if they are malicious.', 'ai-guardwall' ), 'status' => 'cleaned' ); } switch ( $meta['table'] ) { case 'posts': wp_trash_post( (int) $meta['id'] ); $msg = __( 'The post was moved to the trash.', 'ai-guardwall' ); break; case 'postmeta': delete_post_meta( (int) $meta['id'], $meta['meta_key'] ); $msg = __( 'The meta value was deleted.', 'ai-guardwall' ); break; case 'options': update_option( '_svabg_backup_' . substr( md5( $meta['option_name'] ), 0, 12 ), array( 'name' => $meta['option_name'], 'time' => time(), 'value' => get_option( $meta['option_name'] ) ), false ); delete_option( $meta['option_name'] ); $msg = __( 'The option was deleted (a backup copy was kept).', 'ai-guardwall' ); break; case 'comments': wp_trash_comment( (int) $meta['id'] ); $msg = __( 'The comment was moved to the trash.', 'ai-guardwall' ); break; default: return new WP_Error( 'svabg_bad_action', __( 'This record cannot be removed automatically.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'deleted' ); self::log( $f, sprintf( /* translators: %s: location */ __( 'Database record removed: %s', 'ai-guardwall' ), $f['location'] ) ); return array( 'message' => $msg, 'status' => 'deleted' ); } private static function remove_cron( $f ) { $hook = $f['meta_arr']['hook']; $cron = _get_cron_array(); $n = 0; if ( is_array( $cron ) ) { foreach ( $cron as $timestamp => $hooks ) { if ( isset( $hooks[ $hook ] ) ) { foreach ( $hooks[ $hook ] as $event ) { wp_unschedule_event( $timestamp, $hook, isset( $event['args'] ) ? $event['args'] : array() ); $n++; } } } } wp_clear_scheduled_hook( $hook ); Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'cleaned' ); self::log( $f, sprintf( /* translators: %s: hook */ __( 'Scheduled task removed: %s', 'ai-guardwall' ), $hook ) ); return array( 'message' => sprintf( /* translators: %d: number */ _n( '%d scheduled event removed.', '%d scheduled events removed.', $n, 'ai-guardwall' ), $n ), 'status' => 'cleaned' ); } private static function delete_user( $f ) { $uid = (int) $f['meta_arr']['user_id']; if ( $uid === get_current_user_id() ) { return new WP_Error( 'svabg_self', __( 'You cannot delete your own account from here.', 'ai-guardwall' ) ); } $user = get_userdata( $uid ); if ( ! $user ) { Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'resolved' ); return array( 'message' => __( 'The user no longer exists.', 'ai-guardwall' ), 'status' => 'resolved' ); } require_once ABSPATH . 'wp-admin/includes/user.php'; if ( is_multisite() ) { require_once ABSPATH . 'wp-admin/includes/ms.php'; $ok = wpmu_delete_user( $uid ); } else { $ok = wp_delete_user( $uid, get_current_user_id() ); } if ( ! $ok ) { return new WP_Error( 'svabg_delete_user', __( 'The user could not be deleted.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Findings::set_status( $f['id'], 'deleted' ); self::log( $f, sprintf( /* translators: %s: user login */ __( 'User deleted: %s', 'ai-guardwall' ), $user->user_login ) ); return array( 'message' => __( 'The user was deleted and their content reassigned to you.', 'ai-guardwall' ), 'status' => 'deleted' ); } /* ------------------------------ misc ------------------------------- */ /** * Forget one stored copy. * * @param int $id Row. */ private static function drop_copy( $id ) { global $wpdb; $wpdb->delete( Softvolt_Ai_Bodyguard_Db::table( 'quarantine' ), array( 'id' => (int) $id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } /** * What the quarantine holds (without the contents): rel, time, finding, type. */ public static function quarantine_list() { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'quarantine' ); $out = array(); foreach ( (array) $wpdb->get_results( $wpdb->prepare( "SELECT id, finding_id, kind, path, created_at FROM %i ORDER BY id DESC LIMIT 200", $table ), ARRAY_A ) as $row ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $out[] = array( 'id' => (int) $row['id'], 'rel' => (string) $row['path'], 'time' => (int) strtotime( $row['created_at'] . ' UTC' ), 'finding' => (int) $row['finding_id'], 'status' => (string) $row['kind'], 'type' => 'file', ); } return $out; } public static function purge_quarantine( $days = 30 ) { global $wpdb; $table = Softvolt_Ai_Bodyguard_Db::table( 'quarantine' ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE created_at < %s", $table, gmdate( 'Y-m-d H:i:s', time() - max( 1, (int) $days ) * DAY_IN_SECONDS ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $dir = Softvolt_Ai_Bodyguard_Helpers::work_dir_path( 'quarantine' ); $cutoff = time() - max( 1, (int) $days ) * DAY_IN_SECONDS; if ( '' === $dir || ! is_dir( $dir ) ) { return; } foreach ( (array) glob( $dir . '/*' ) as $file ) { if ( preg_match( '/\.(quarantined|replaced|json)$/', $file ) && (int) @filemtime( $file ) < $cutoff ) { wp_delete_file( $file ); } } } private static function log( $f, $message ) { Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'remediation', $message, array( 'finding' => (int) $f['id'], 'location' => $f['location'] ) ); } }