self::EXPORT_KEY, 'version' => SOFTVOLT_AI_BODYGUARD_VERSION, 'exported' => gmdate( 'c' ), 'site' => home_url( '/' ), 'settings' => $saved, 'modules' => Softvolt_Ai_Bodyguard_Modules::get(), ); } /** * admin-post.php?action=svabg_settings_export */ public static function download_export() { if ( ! current_user_can( Softvolt_Ai_Bodyguard::cap() ) || ! check_admin_referer( 'svabg_settings_export' ) ) { wp_die( esc_html__( 'You are not allowed to do this.', 'ai-guardwall' ), 403 ); } $host = preg_replace( '/[^a-z0-9.-]/', '', strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ) ); nocache_headers(); header( 'Content-Type: application/json; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="ai-guardwall-settings-' . $host . '-' . gmdate( 'Y-m-d' ) . '.json"' ); header( 'X-Content-Type-Options: nosniff' ); Softvolt_Ai_Bodyguard_Logger::log( 'info', 'settings', __( 'Settings exported.', 'ai-guardwall' ) ); echo wp_json_encode( self::export_data(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- a JSON download. exit; } /** * Take over the settings of an export file. Every value goes through the * same cleaning as the settings form, with the same lockout guards. * * @param array $data Decoded export file. * @return array|WP_Error Summary. */ public static function import( array $data ) { if ( ( $data['plugin'] ?? '' ) !== self::EXPORT_KEY || ! isset( $data['settings'] ) || ! is_array( $data['settings'] ) ) { return new WP_Error( 'svabg_import_file', __( 'This is not an AI GuardWall settings file.', 'ai-guardwall' ) ); } $input = $data['settings']; unset( $input['_partial'], $input['_tabs'], $input['api_key'], $input['clear_api_key'], $input['captcha_secret_new'], $input['gsb_key_new'], $input['http_auth_pass_new'] ); // A file from an older version lacks the newer rules: they keep their current state. if ( isset( $input['hardening'] ) && is_array( $input['hardening'] ) ) { foreach ( Softvolt_Ai_Bodyguard_Hardening::rules() as $id => $rule ) { if ( ! array_key_exists( $id, $input['hardening'] ) && 'setting' !== $rule['type'] ) { $input['hardening'][ $id ] = Softvolt_Ai_Bodyguard_Settings::hardening_enabled( $id ); } } } if ( isset( $input['firewall_rules'] ) && is_array( $input['firewall_rules'] ) ) { $input['firewall_rules'] += (array) Softvolt_Ai_Bodyguard_Settings::get( 'firewall_rules', array() ); } $before = get_settings_errors( Softvolt_Ai_Bodyguard_Settings::OPTION ); $clean = Softvolt_Ai_Bodyguard_Settings::sanitize( wp_slash( $input ) ); $notes = array(); foreach ( array_slice( get_settings_errors( Softvolt_Ai_Bodyguard_Settings::OPTION ), count( $before ) ) as $e ) { $notes[] = wp_strip_all_tags( $e['message'] ); } update_option( Softvolt_Ai_Bodyguard_Settings::OPTION, $clean ); Softvolt_Ai_Bodyguard_Settings::flush(); $modules = 0; if ( isset( $data['modules'] ) && is_array( $data['modules'] ) ) { $wanted = isset( $data['modules']['enabled'] ) && is_array( $data['modules']['enabled'] ) ? $data['modules']['enabled'] : array(); $rest = $data['modules']; unset( $rest['enabled'] ); if ( $rest ) { Softvolt_Ai_Bodyguard_Modules::update( $rest ); } foreach ( array_keys( Softvolt_Ai_Bodyguard_Modules::registry() ) as $id ) { $on = ! empty( $wanted[ $id ] ); if ( $on !== Softvolt_Ai_Bodyguard_Modules::enabled( $id ) ) { Softvolt_Ai_Bodyguard_Modules::toggle( $id, $on ); $modules++; } } } Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'settings', sprintf( /* translators: %s: value */ __( 'Settings imported from %s.', 'ai-guardwall' ), esc_url_raw( (string) ( $data['site'] ?? '' ) ) ) ); return array( 'ok' => true, 'from' => (string) ( $data['site'] ?? '' ), 'modules' => $modules, 'notes' => $notes, 'login' => Softvolt_Ai_Bodyguard_Login_Url::enabled() ? Softvolt_Ai_Bodyguard_Login_Url::new_login_url() : wp_login_url(), ); } /** * Every setting back to its default (findings, log, keys and backups stay). */ public static function reset() { $current = get_option( Softvolt_Ai_Bodyguard_Settings::OPTION, array() ); $keep = array( 'activated_at' => is_array( $current ) && isset( $current['activated_at'] ) ? (int) $current['activated_at'] : time() ); update_option( Softvolt_Ai_Bodyguard_Settings::OPTION, $keep ); Softvolt_Ai_Bodyguard_Settings::flush(); delete_option( self::SNAPSHOT ); Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'settings', __( 'All settings were reset to their defaults.', 'ai-guardwall' ) ); return array( 'ok' => true ); } /* ----------------------------- emergency switch ---------------------------- */ public static function emergency_active() { return (bool) get_option( self::SNAPSHOT ); } /** * Switch every protection off at once (firewall, hardening, server rules, * hidden login), keeping a snapshot to switch them back on. */ public static function emergency_off() { $saved = get_option( Softvolt_Ai_Bodyguard_Settings::OPTION, array() ); $saved = is_array( $saved ) ? $saved : array(); if ( ! self::emergency_active() ) { update_option( self::SNAPSHOT, array( 'time' => time(), 'settings' => $saved ), false ); } $map = array(); foreach ( Softvolt_Ai_Bodyguard_Hardening::rules() as $id => $rule ) { if ( 'setting' !== $rule['type'] && 'check' !== $rule['type'] ) { $map[ $id ] = false; } } Softvolt_Ai_Bodyguard_Settings::update( array( 'hardening' => $map, 'firewall_mode' => 'off' ) ); Softvolt_Ai_Bodyguard_Hardening::apply_all_enabled(); Softvolt_Ai_Bodyguard_Logger::log( 'critical', 'hardening', __( 'Emergency switch: every protection was turned off.', 'ai-guardwall' ) ); return array( 'ok' => true, 'active' => true ); } public static function emergency_restore() { $snap = get_option( self::SNAPSHOT ); if ( ! is_array( $snap ) || ! isset( $snap['settings'] ) ) { return new WP_Error( 'svabg_snapshot', __( 'There is nothing to switch back on.', 'ai-guardwall' ) ); } $now = get_option( Softvolt_Ai_Bodyguard_Settings::OPTION, array() ); $now = is_array( $now ) ? $now : array(); // Only the protections come back; anything else changed since then is kept. $now['hardening'] = isset( $snap['settings']['hardening'] ) ? $snap['settings']['hardening'] : array(); $now['firewall_mode'] = isset( $snap['settings']['firewall_mode'] ) ? $snap['settings']['firewall_mode'] : 'block'; update_option( Softvolt_Ai_Bodyguard_Settings::OPTION, $now ); Softvolt_Ai_Bodyguard_Settings::flush(); delete_option( self::SNAPSHOT ); Softvolt_Ai_Bodyguard_Hardening::apply_all_enabled(); Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'hardening', __( 'Emergency switch: the protections were turned back on.', 'ai-guardwall' ) ); return array( 'ok' => true, 'active' => false ); } /* ------------------------------ file permissions ------------------------------ */ private static function rel( $path ) { if ( untrailingslashit( wp_normalize_path( $path ) ) === Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ) ) { return '/'; } return Softvolt_Ai_Bodyguard_Helpers::rel_path( $path ); } public static function is_windows() { return '\\' === DIRECTORY_SEPARATOR; } /** * The files and folders whose permissions matter, with what they should be. */ private static function permission_targets() { $root = Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ); $content = Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content' ); $config = Softvolt_Ai_Bodyguard_Wpconfig::path(); $list = array( $root => 0755, $root . '/wp-admin' => 0755, $root . '/wp-includes' => 0755, $content => 0755, Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/plugins' ) => 0755, Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/themes' ) => 0755, Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content/uploads' ) => 0755, $root . '/index.php' => 0644, $root . '/wp-admin/index.php' => 0644, Softvolt_Ai_Bodyguard_Htaccess::root_file() => 0644, ); if ( $config ) { $list[ wp_normalize_path( $config ) ] = 0640; } return array_filter( $list, function ( $path ) { return file_exists( $path ); }, ARRAY_FILTER_USE_KEY ); } /** * Current and recommended permissions. Fine = nothing allowed beyond the * recommendation, except that wp-config.php may stay 644 when the server * runs PHP as another user (then 640 would break the site). */ public static function permissions() { clearstatcache(); $out = array(); foreach ( self::permission_targets() as $path => $want ) { $perms = @fileperms( $path ); $mode = false === $perms ? 0 : ( $perms & 0777 ); $extra = $mode & ~$want; $ok = 0 === $extra || ( 0640 === $want && 0644 === $mode ); $out[] = array( 'path' => self::rel( $path ), 'type' => is_dir( $path ) ? 'dir' : 'file', 'current' => sprintf( '%o', $mode ), 'recommended' => sprintf( '%o', $want ), 'ok' => self::is_windows() ? true : $ok, 'world' => (bool) ( $mode & 0002 ), ); } return array( 'items' => $out, 'windows' => self::is_windows() ); } /** * Set the recommended permissions on the listed paths (only paths from the list above). * * @param array $paths Relative paths. */ public static function fix_permissions( array $paths ) { if ( self::is_windows() ) { return new WP_Error( 'svabg_windows', __( 'Windows servers do not use Unix file permissions.', 'ai-guardwall' ) ); } $done = array(); $failed = array(); foreach ( self::permission_targets() as $path => $want ) { $rel = self::rel( $path ); if ( ! in_array( $rel, $paths, true ) ) { continue; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- sets the permissions the site owner chose on a file the plugin manages. if ( @chmod( $path, $want ) ) { $done[] = $rel; } else { $failed[] = $rel; } } clearstatcache(); if ( $done ) { Softvolt_Ai_Bodyguard_Logger::log( 'notice', 'tool', sprintf( /* translators: %s: list of done */ __( 'File permissions fixed: %s', 'ai-guardwall' ), implode( ', ', $done ) ) ); } return array( 'ok' => ! $failed, 'fixed' => $done, 'failed' => $failed ); } /* ------------------------------- config backups ------------------------------- */ public static function site_broken() { $res = wp_remote_get( add_query_arg( 'svabg_check', wp_rand(), home_url( '/' ) ), array( 'timeout' => 15, 'sslverify' => apply_filters( 'https_local_ssl_verify', false ), 'redirection' => 3, ) ); return ! is_wp_error( $res ) && 500 <= (int) wp_remote_retrieve_response_code( $res ); } /* ------------------------------ database prefix ------------------------------ */ /** * Change the table prefix: a full database backup first, then every table * of this site is renamed in one statement, the prefixed option and user * meta keys follow, and wp-config.php is updated. Anything that fails is * undone. $dry_run returns the plan without changing anything. * * @param string $new New prefix (letters, digits, underscores; ends with _). * @param bool $dry_run Only plan. * @return array|WP_Error */ public static function change_prefix( $new, $dry_run = false ) { global $wpdb; $new = strtolower( trim( (string) $new ) ); $old = $wpdb->prefix; if ( is_multisite() ) { return new WP_Error( 'svabg_prefix_ms', __( 'The prefix of a multisite network cannot be changed here.', 'ai-guardwall' ) ); } if ( ! preg_match( '/^[a-z][a-z0-9_]{0,18}_$/', $new ) ) { return new WP_Error( 'svabg_prefix_bad', __( 'Use 2 to 20 letters, digits or underscores, starting with a letter and ending with an underscore, for example "k7x_".', 'ai-guardwall' ) ); } if ( $new === $old ) { return new WP_Error( 'svabg_prefix_same', __( 'That is the current prefix.', 'ai-guardwall' ) ); } $all = (array) $wpdb->get_col( 'SHOW TABLES' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $tables = array_values( array_filter( $all, function ( $t ) use ( $old ) { return 0 === strpos( $t, $old ); } ) ); foreach ( $tables as $t ) { $target = $new . substr( $t, strlen( $old ) ); if ( in_array( $target, $all, true ) ) { return new WP_Error( 'svabg_prefix_taken', sprintf( /* translators: %s: target */ __( 'A table called %s already exists; choose another prefix.', 'ai-guardwall' ), $target ) ); } } // Prefixes inside prefixes (wp_ and wp_shop_) would rename the other site's tables too. foreach ( $all as $t ) { if ( 0 === strpos( $t, $old ) && preg_match( '/^' . preg_quote( $old, '/' ) . '[a-z0-9]+_(options|users|posts)$/', $t ) ) { return new WP_Error( 'svabg_prefix_shared', sprintf( /* translators: %s: t */ __( 'Another WordPress install seems to share this database with a longer prefix (%s). Change the prefix by hand.', 'ai-guardwall' ), $t ) ); } } $config = Softvolt_Ai_Bodyguard_Wpconfig::path(); if ( '' === $config || ! Softvolt_Ai_Bodyguard_Wpconfig::is_writable() ) { return new WP_Error( 'svabg_prefix_config', __( 'wp-config.php is not writable, so the new prefix could not be saved there.', 'ai-guardwall' ) ); } $conf = (string) file_get_contents( $config ); if ( ! preg_match( '/^\s*\$table_prefix\s*=\s*([\'"])' . preg_quote( $old, '/' ) . '\1\s*;/m', $conf ) ) { return new WP_Error( 'svabg_prefix_config', __( 'The $table_prefix line in wp-config.php has an unusual form; change the prefix by hand.', 'ai-guardwall' ) ); } $pairs = array(); foreach ( $tables as $t ) { $pairs[] = $t; $pairs[] = $new . substr( $t, strlen( $old ) ); } $meta_keys = (array) $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT meta_key FROM {$wpdb->usermeta} WHERE meta_key LIKE %s", $wpdb->esc_like( $old ) . '%' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $plan = array( 'old' => $old, 'new' => $new, 'tables' => count( $tables ), 'meta_keys' => $meta_keys, 'options' => array( $old . 'user_roles' ), ); if ( $dry_run ) { return array_merge( array( 'ok' => true, 'dry_run' => true ), $plan ); } // 1. A full backup of this site's tables. $path = Softvolt_Ai_Bodyguard_Helpers::work_dir( 'db-backups' ) . '/before-prefix-change-' . gmdate( 'Ymd-His' ) . '-' . strtolower( wp_generate_password( 16, false, false ) ) . '.sql.gz'; $dump = Softvolt_Ai_Bodyguard_Db_Manager::dump_to_file( $tables, $path ); if ( is_wp_error( $dump ) ) { return new WP_Error( 'svabg_prefix_backup', sprintf( /* translators: %s: value */ __( 'Nothing was changed: the database backup failed (%s).', 'ai-guardwall' ), $dump->get_error_message() ) ); } // 2. Rename every table at once (atomic in MySQL). if ( false === $wpdb->query( $wpdb->prepare( 'RENAME TABLE ' . implode( ', ', array_fill( 0, count( $tables ), '%i TO %i' ) ), $pairs ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- The query text is only 'RENAME TABLE' plus one '%i TO %i' per table; table names are passed to prepare(). return new WP_Error( 'svabg_prefix_rename', sprintf( /* translators: %s: last error */ __( 'Nothing was changed: the tables could not be renamed (%s).', 'ai-guardwall' ), $wpdb->last_error ) ); } $undo = function () use ( $wpdb, $tables, $old, $new ) { $back = array(); foreach ( $tables as $t ) { $back[] = $new . substr( $t, strlen( $old ) ); $back[] = $t; } $wpdb->query( $wpdb->prepare( 'RENAME TABLE ' . implode( ', ', array_fill( 0, count( $tables ), '%i TO %i' ) ), $back ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- Same as above: placeholders only, names passed to prepare(). }; // 3. The prefixed keys inside the tables. $options = $new . 'options'; $usermeta = $new . 'usermeta'; $wpdb->query( $wpdb->prepare( "UPDATE %i SET option_name = %s WHERE option_name = %s", $options, $new . 'user_roles', $old . 'user_roles' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery foreach ( $meta_keys as $key ) { $wpdb->query( $wpdb->prepare( "UPDATE %i SET meta_key = %s WHERE meta_key = %s", $usermeta, $new . substr( $key, strlen( $old ) ), $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } // 4. wp-config.php. $updated = preg_replace( '/^(\s*\$table_prefix\s*=\s*)([\'"])' . preg_quote( $old, '/' ) . '\2(\s*;)/m', '${1}${2}' . $new . '${2}${3}', $conf, 1 ); if ( ! $updated || is_wp_error( Softvolt_Ai_Bodyguard_Wpconfig::write( $updated, $conf ) ) ) { foreach ( $meta_keys as $key ) { $wpdb->query( $wpdb->prepare( "UPDATE %i SET meta_key = %s WHERE meta_key = %s", $usermeta, $key, $new . substr( $key, strlen( $old ) ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } $wpdb->query( $wpdb->prepare( "UPDATE %i SET option_name = %s WHERE option_name = %s", $options, $old . 'user_roles', $new . 'user_roles' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery $undo(); return new WP_Error( 'svabg_prefix_config', __( 'wp-config.php could not be written, so every change was undone.', 'ai-guardwall' ) ); } $wpdb->set_prefix( $new ); wp_cache_flush(); Softvolt_Ai_Bodyguard_Logger::log( 'warning', 'tool', sprintf( /* translators: 1: old, 2: new, 3: number of tables, 4: file name */ __( 'Database prefix changed from %1$s to %2$s (%3$d tables). Backup: %4$s', 'ai-guardwall' ), $old, $new, count( $tables ), basename( $dump['path'] ) ) ); return array_merge( array( 'ok' => true, 'backup' => basename( $dump['path'] ) ), $plan ); } /* ----------------------------------- WHOIS ----------------------------------- */ /** * Who owns an IP address or a domain (RDAP, the modern WHOIS), cached for a day. * * @param string $q IP or domain. */ public static function whois( $q ) { $q = strtolower( trim( (string) $q ) ); if ( filter_var( $q, FILTER_VALIDATE_IP ) ) { $url = 'https://rdap.org/ip/' . rawurlencode( $q ); $type = 'ip'; } elseif ( preg_match( '/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/', $q ) ) { $url = 'https://rdap.org/domain/' . rawurlencode( $q ); $type = 'domain'; } else { return new WP_Error( 'svabg_whois_query', __( 'Enter an IP address or a domain name.', 'ai-guardwall' ) ); } $key = 'svabg_whois_' . md5( $q ); $cached = get_transient( $key ); if ( is_array( $cached ) ) { return $cached; } $res = wp_remote_get( $url, array( 'timeout' => 12, 'headers' => array( 'Accept' => 'application/rdap+json, application/json' ) ) ); if ( is_wp_error( $res ) ) { return new WP_Error( 'svabg_whois_net', sprintf( /* translators: %s: value */ __( 'The lookup failed: %s', 'ai-guardwall' ), $res->get_error_message() ) ); } $code = (int) wp_remote_retrieve_response_code( $res ); $data = json_decode( (string) wp_remote_retrieve_body( $res ), true ); if ( 200 !== $code || ! is_array( $data ) ) { return new WP_Error( 'svabg_whois_none', 404 === $code ? __( 'No registration data was found.', 'ai-guardwall' ) : sprintf( /* translators: %d: code */ __( 'The registry answered %d.', 'ai-guardwall' ), $code ) ); } $out = array( 'query' => $q, 'type' => $type, 'name' => (string) ( $data['name'] ?? ( $data['ldhName'] ?? '' ) ), 'handle' => (string) ( $data['handle'] ?? '' ), 'country' => (string) ( $data['country'] ?? '' ), 'range' => isset( $data['startAddress'], $data['endAddress'] ) ? $data['startAddress'] . ' – ' . $data['endAddress'] : '', 'cidr' => '', 'status' => isset( $data['status'] ) ? implode( ', ', (array) $data['status'] ) : '', 'org' => '', 'abuse' => '', 'registrar' => '', 'events' => array(), 'servers' => array(), 'hostname' => 'ip' === $type ? Softvolt_Ai_Bodyguard_Blocking::hostname( $q ) : '', 'source' => $url, ); if ( ! empty( $data['cidr0_cidrs'] ) ) { $c = array(); foreach ( (array) $data['cidr0_cidrs'] as $cidr ) { $c[] = ( $cidr['v4prefix'] ?? ( $cidr['v6prefix'] ?? '' ) ) . '/' . ( $cidr['length'] ?? '' ); } $out['cidr'] = implode( ', ', $c ); } foreach ( (array) ( $data['events'] ?? array() ) as $ev ) { if ( ! empty( $ev['eventAction'] ) && ! empty( $ev['eventDate'] ) ) { $out['events'][ (string) $ev['eventAction'] ] = substr( (string) $ev['eventDate'], 0, 10 ); } } foreach ( (array) ( $data['nameservers'] ?? array() ) as $ns ) { if ( ! empty( $ns['ldhName'] ) ) { $out['servers'][] = strtolower( (string) $ns['ldhName'] ); } } $walk = function ( $entities ) use ( &$walk, &$out ) { foreach ( (array) $entities as $e ) { $roles = (array) ( $e['roles'] ?? array() ); $card = self::vcard( $e['vcardArray'] ?? array() ); if ( array_intersect( $roles, array( 'registrant', 'administrative' ) ) && '' === $out['org'] && '' !== $card['name'] ) { $out['org'] = $card['name']; } if ( in_array( 'registrar', $roles, true ) && '' === $out['registrar'] ) { $out['registrar'] = $card['name']; } if ( in_array( 'abuse', $roles, true ) && '' === $out['abuse'] && '' !== $card['email'] ) { $out['abuse'] = $card['email']; } if ( ! empty( $e['entities'] ) ) { $walk( $e['entities'] ); } } }; $walk( $data['entities'] ?? array() ); set_transient( $key, $out, DAY_IN_SECONDS ); return $out; } private static function vcard( $vcard ) { $out = array( 'name' => '', 'email' => '' ); if ( ! is_array( $vcard ) || ! isset( $vcard[1] ) || ! is_array( $vcard[1] ) ) { return $out; } foreach ( $vcard[1] as $field ) { if ( ! is_array( $field ) || ! isset( $field[0], $field[3] ) ) { continue; } if ( 'fn' === $field[0] && '' === $out['name'] ) { $out['name'] = (string) ( is_array( $field[3] ) ? implode( ' ', $field[3] ) : $field[3] ); } if ( 'email' === $field[0] && '' === $out['email'] ) { $out['email'] = (string) ( is_array( $field[3] ) ? reset( $field[3] ) : $field[3] ); } } return $out; } /* -------------------------------- diagnostics -------------------------------- */ /** * The outside services the plugin talks to, and the site itself. */ public static function connectivity() { $targets = array( 'loopback' => array( __( 'This site (loopback request)', 'ai-guardwall' ), home_url( '/' ) ), 'rest' => array( __( 'This site\'s REST API', 'ai-guardwall' ), rest_url( Softvolt_Ai_Bodyguard_Rest::NS . '/' ) ), 'wporg' => array( __( 'WordPress.org (checksums, plugin data)', 'ai-guardwall' ), 'https://api.wordpress.org/core/version-check/1.7/' ), 'vuln' => array( __( 'WPVulnerability (known security holes)', 'ai-guardwall' ), 'https://www.wpvulnerability.net/core/' . rawurlencode( Softvolt_Ai_Bodyguard_Helpers::wp_version() ) . '/' ), 'spamhaus' => array( __( 'Spamhaus (threat lists)', 'ai-guardwall' ), 'https://www.spamhaus.org/drop/drop_v4.json' ), 'pwned' => array( __( 'Have I Been Pwned (breached passwords)', 'ai-guardwall' ), 'https://api.pwnedpasswords.com/range/21BD1' ), 'rdap' => array( __( 'RDAP (WHOIS)', 'ai-guardwall' ), 'https://rdap.org/' ), ); $out = array(); foreach ( $targets as $id => $t ) { $start = microtime( true ); $res = wp_remote_get( $t[1], array( 'timeout' => 10, 'redirection' => 2, 'limit_response_size' => 65536, // Outside services are always verified; this site's own address like WordPress's loopback checks. 'sslverify' => in_array( $id, array( 'loopback', 'rest' ), true ) ? apply_filters( 'https_local_ssl_verify', false ) : true, ) ); $ms = (int) round( ( microtime( true ) - $start ) * 1000 ); $code = is_wp_error( $res ) ? 0 : (int) wp_remote_retrieve_response_code( $res ); $out[] = array( 'id' => $id, 'label' => $t[0], 'host' => (string) wp_parse_url( $t[1], PHP_URL_HOST ), 'ok' => $code > 0 && $code < 500, 'code' => $code, 'ms' => $ms, 'error' => is_wp_error( $res ) ? $res->get_error_message() : '', ); } return $out; } public static function test_email( $to ) { $to = sanitize_email( (string) $to ); if ( ! is_email( $to ) ) { return new WP_Error( 'svabg_mail_to', __( 'Enter a valid email address.', 'ai-guardwall' ) ); } $error = null; $catch = function ( $e ) use ( &$error ) { $error = $e; }; add_action( 'wp_mail_failed', $catch ); $sent = wp_mail( $to, sprintf( /* translators: %s: setting */ __( '[%s] AI GuardWall test email', 'ai-guardwall' ), wp_specialchars_decode( (string) get_option( 'blogname' ), ENT_QUOTES ) ), sprintf( __( "This is a test from AI GuardWall on %1\$s, sent at %2\$s.\n\nIf you can read it, security alerts will reach you too.", 'ai-guardwall' ), home_url( '/' ), wp_date( 'Y-m-d H:i' ) ) ); remove_action( 'wp_mail_failed', $catch ); if ( ! $sent ) { return new WP_Error( 'svabg_mail_failed', $error instanceof WP_Error ? sprintf( /* translators: %s: value */ __( 'WordPress could not send it: %s', 'ai-guardwall' ), $error->get_error_message() ) : __( 'WordPress could not send it. Install an SMTP plugin so email leaves through a real mail server.', 'ai-guardwall' ) ); } Softvolt_Ai_Bodyguard_Logger::log( 'info', 'tool', sprintf( /* translators: %s: to */ __( 'Test email sent to %s.', 'ai-guardwall' ), $to ) ); return array( 'ok' => true ); } /* -------------------------------- server logs -------------------------------- */ /** * The PHP and WordPress error logs this server has. */ public static function log_files() { $candidates = array(); $ini = (string) ini_get( 'error_log' ); if ( '' !== $ini && 'syslog' !== $ini ) { $candidates[] = $ini; } if ( defined( 'WP_DEBUG_LOG' ) && is_string( WP_DEBUG_LOG ) && '' !== WP_DEBUG_LOG ) { $candidates[] = WP_DEBUG_LOG; } $candidates[] = Softvolt_Ai_Bodyguard_Helpers::site_dir( 'wp-content' ) . '/debug.log'; $candidates[] = Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ) . '/error_log'; $candidates[] = Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ) . '/php_errorlog'; $candidates[] = Softvolt_Ai_Bodyguard_Helpers::site_dir( '' ) . '/wp-admin/error_log'; $out = array(); $seen = array(); foreach ( $candidates as $path ) { $path = wp_normalize_path( $path ); if ( isset( $seen[ $path ] ) || ! @is_file( $path ) || ! @is_readable( $path ) ) { continue; } $seen[ $path ] = true; $out[] = array( 'id' => substr( md5( $path ), 0, 12 ), 'path' => Softvolt_Ai_Bodyguard_Helpers::rel_path( $path ), 'size' => (int) filesize( $path ), 'size_h' => Softvolt_Ai_Bodyguard_Helpers::human_size( (int) filesize( $path ) ), 'modified' => human_time_diff( (int) filemtime( $path ) ), 'abs' => $path, ); } return $out; } /** * The last lines of one log (at most the last 512 KB are read). */ public static function log_tail( $id, $lines = 200, $filter = '' ) { foreach ( self::log_files() as $f ) { if ( $f['id'] !== $id ) { continue; } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- large files are streamed in chunks; WP_Filesystem cannot stream. $fh = @fopen( $f['abs'], 'rb' ); if ( ! $fh ) { break; } $size = (int) $f['size']; $read = min( $size, 512 * 1024 ); fseek( $fh, $size - $read ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread -- large files are streamed in chunks; WP_Filesystem cannot stream. $text = (string) fread( $fh, $read ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- large files are streamed in chunks; WP_Filesystem cannot stream. fclose( $fh ); $all = preg_split( '/\r\n|\r|\n/', $text ); if ( $read < $size ) { array_shift( $all ); // A partial first line. } $all = array_values( array_filter( $all, 'strlen' ) ); if ( '' !== $filter ) { $all = array_values( array_filter( $all, function ( $l ) use ( $filter ) { return false !== stripos( $l, $filter ); } ) ); } $lines = max( 20, min( 2000, (int) $lines ) ); return array( 'path' => $f['path'], 'size' => $f['size_h'], 'total' => count( $all ), // A log line can quote a password or a key (a failed connection, a dumped variable): never shown. 'lines' => array_map( function ( $l ) { return Softvolt_Ai_Bodyguard_Helpers::trim_text( Softvolt_Ai_Bodyguard_Helpers::redact( $l, false ), 2000 ); }, array_slice( $all, -$lines ) ), ); } return new WP_Error( 'svabg_log', __( 'Log file not found.', 'ai-guardwall' ) ); } }