get_charset_collate(); $table = $wpdb->prefix . self::TABLE; $sql = "CREATE TABLE $table ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, category VARCHAR(50) NOT NULL, severity VARCHAR(20) NOT NULL, description TEXT NOT NULL, evidence TEXT NULL, recommendation TEXT NOT NULL, can_auto_fix TINYINT(1) NOT NULL DEFAULT 0, status VARCHAR(20) NOT NULL DEFAULT 'open', created_at DATETIME NOT NULL, PRIMARY KEY (id) ) $charset_collate;"; dbDelta($sql); } public static function init() { add_action('admin_post_wpmm_scan_attack_surface', [__CLASS__, 'handle_scan']); add_action('admin_post_wpmm_attack_surface_status', [__CLASS__, 'handle_update_status']); add_action('admin_post_wpmm_attack_surface_fix', [__CLASS__, 'handle_fix']); add_action('admin_post_wpmm_check_cloaking', [__CLASS__, 'handle_check_cloaking']); } public static function handle_check_cloaking() { if (!current_user_can('manage_options')) wp_die('You do not have permission to do this.'); check_admin_referer('wpmm_check_cloaking'); $result = class_exists('WPMM_Detector') ? WPMM_Detector::check_cloaking(home_url('/')) : ['ok' => false, 'error' => 'Detector unavailable.']; set_transient('wpmm_cloaking_result', $result, HOUR_IN_SECONDS); wp_safe_redirect(admin_url('admin.php?page=wpmm-security-hub&tab=attack-surface&cloaking_checked=1')); exit; } protected static $carried_status = []; protected static function add_finding($category, $severity, $description, $evidence, $recommendation, $can_auto_fix = false) { global $wpdb; $status = (isset(self::$carried_status[$description]) && self::$carried_status[$description] === 'ignored') ? 'ignored' : 'open'; $wpdb->insert($wpdb->prefix . self::TABLE, [ 'category' => $category, 'severity' => $severity, 'description' => $description, 'evidence' => $evidence, 'recommendation' => $recommendation, 'can_auto_fix' => $can_auto_fix ? 1 : 0, 'status' => $status, 'created_at' => current_time('mysql', true), ]); } public static function run_scan() { global $wpdb; $table = $wpdb->prefix . self::TABLE; $previous = $wpdb->get_results("SELECT description, status FROM $table", ARRAY_A); $previous_status = []; foreach ($previous as $row) { $previous_status[$row['description']] = $row['status']; } self::$carried_status = $previous_status; $wpdb->query("TRUNCATE TABLE $table"); self::check_software_versions(); self::check_xmlrpc_rest(); self::check_exposed_files(); self::check_writable_directories(); self::check_directory_listing(); self::check_unused_plugins_themes(); self::check_unused_admin_accounts(); self::check_composer(); update_option('wpmm_attack_surface_last_scan', current_time('mysql', true)); if (class_exists('WPMM_Activity_Log')) { WPMM_Activity_Log::log('attack_surface_scanned', 'site', 'Attack surface scan completed'); } } protected static function check_software_versions() { global $wp_version; $core_updates = get_core_updates(); if (is_array($core_updates) && !empty($core_updates) && $core_updates[0]->response === 'upgrade') { self::add_finding('software_version', 'high', "WordPress core is outdated (running $wp_version, " . $core_updates[0]->version . ' available)', "Installed: $wp_version, Latest: {$core_updates[0]->version}", 'Update WordPress core as soon as possible.', false); } if (!function_exists('get_plugin_updates')) { require_once ABSPATH . 'wp-admin/includes/update.php'; require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $plugin_updates = get_plugin_updates(); foreach ($plugin_updates as $path => $data) { self::add_finding('software_version', 'medium', 'Plugin update available: ' . $data->Name, 'Installed: ' . $data->Version . ', Latest: ' . ($data->update->new_version ?? 'unknown'), 'Update this plugin from the Plugins page.', false); } $theme_updates = get_theme_updates(); foreach ($theme_updates as $slug => $data) { self::add_finding('software_version', 'medium', 'Theme update available: ' . $slug, 'An update is available for this theme.', 'Update this theme from the Appearance > Themes page.', false); } $php_version = phpversion(); if (version_compare($php_version, '8.1', '<')) { self::add_finding('software_version', 'medium', "PHP version is old ($php_version)", "Running PHP $php_version", 'Ask your host to upgrade to a currently-supported PHP version.', false); } } protected static function check_xmlrpc_rest() { if (class_exists('WPMM_Hardening') && !WPMM_Hardening::is_enabled('disable_xmlrpc')) { self::add_finding('exposure', 'low', 'XML-RPC is enabled and reachable', 'xmlrpc.php responds to requests', 'Consider disabling XML-RPC from the Hardening Center if not needed.', false); } if (class_exists('WPMM_Hardening') && !WPMM_Hardening::is_enabled('protect_rest_api')) { self::add_finding('exposure', 'low', 'REST API user listing is not restricted', '/wp-json/wp/v2/users is publicly listable', 'Enable "Protect REST API" from the Hardening Center.', false); } } protected static function check_exposed_files() { $probe_paths = [ ['.git/config', 'critical', 'Exposed .git repository - can reveal full source history'], ['.env', 'critical', 'Exposed .env file - commonly contains credentials'], ['wp-config.php.bak', 'critical', 'Exposed wp-config.php backup file'], ['wp-config.bak', 'critical', 'Exposed wp-config.php backup file'], ['wp-config.old', 'critical', 'Exposed wp-config.php backup file'], ['wp-content/debug.log', 'high', 'Publicly accessible WordPress debug log'], ['error_log', 'medium', 'Publicly accessible PHP error log'], ['readme.html', 'low', 'Default WordPress readme.html exposes the WordPress version'], ['.DS_Store', 'low', 'Exposed .DS_Store file (can leak directory structure)'], ['phpinfo.php', 'critical', 'Exposed phpinfo() file - reveals extensive server configuration'], ]; $base = home_url('/'); foreach ($probe_paths as [$path, $severity, $desc]) { $local_path = ABSPATH . $path; if (!is_file($local_path)) continue; $response = wp_remote_get($base . $path, ['timeout' => 2, 'redirection' => 0]); if (is_wp_error($response)) continue; $code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); if ($code === 200 && trim($body) !== '') { self::add_finding('exposed_file', $severity, $desc, "Publicly reachable at: $path", 'Remove this file, or block web access to it via .htaccess/Nginx config.', false); } } } protected static function check_writable_directories() { $paths_to_check = [ ABSPATH . 'wp-config.php' => 'wp-config.php', ABSPATH . '.htaccess' => '.htaccess', ]; foreach ($paths_to_check as $full_path => $label) { if (is_file($full_path) && wp_is_writable($full_path)) { self::add_finding('permissions', 'medium', "$label is writable by the web server", "File permissions allow writing to $label", 'Consider tightening file permissions once initial setup is complete (e.g. 644 or stricter).', true); } } } protected static function check_directory_listing() { $dirs = ['wp-content/uploads/', 'wp-content/plugins/', 'wp-content/themes/']; foreach ($dirs as $dir) { $response = wp_remote_get(home_url('/' . $dir), ['timeout' => 2]); if (is_wp_error($response)) continue; $body = wp_remote_retrieve_body($response); if (wp_remote_retrieve_response_code($response) === 200 && preg_match('/Index of \/|Directory Listing/i', $body)) { self::add_finding('exposure', 'medium', "Directory listing is enabled for $dir", 'Server returned a browsable file listing', 'Enable "Disable Directory Listing" from the Hardening Center.', true); } } } protected static function check_unused_plugins_themes() { if (!function_exists('get_plugins')) require_once ABSPATH . 'wp-admin/includes/plugin.php'; $all_plugins = get_plugins(); $active_plugins = get_option('active_plugins', []); $inactive_count = count($all_plugins) - count($active_plugins); if ($inactive_count > 0) { self::add_finding('unused_component', 'low', "$inactive_count inactive plugin(s) installed", 'Inactive plugins still exist on disk and can be a target even when deactivated', 'Delete plugins you are not using, rather than just deactivating them.', true); } $all_themes = wp_get_themes(); $active_theme = get_stylesheet(); $inactive_themes = count($all_themes) - 1; if ($inactive_themes > 0) { self::add_finding('unused_component', 'low', "$inactive_themes inactive theme(s) installed", 'Inactive themes still exist on disk', 'Delete themes you are not using.', true); } } protected static function check_unused_admin_accounts() { if (!class_exists('WPMM_User_Security')) return; $scan = WPMM_User_Security::scan_admin_accounts(); foreach ($scan as $row) { foreach ($row['flags'] as $flag) { if (strpos($flag, 'Dormant') === 0) { self::add_finding('unused_component', 'medium', 'Dormant administrator account: ' . $row['user']->user_login, $flag, 'Review whether this account is still needed, or downgrade/remove it.', false); } } } } protected static function check_composer() { $composer_json = ABSPATH . 'composer.json'; if (!is_file($composer_json)) return; $content = WPMM_FS::read($composer_json); if ($content === false) return; $data = json_decode($content, true); if (!is_array($data)) return; if (!empty($data['scripts'])) { foreach (['post-install-cmd', 'post-update-cmd', 'pre-install-cmd', 'pre-update-cmd'] as $hook) { if (!empty($data['scripts'][$hook])) { $commands = is_array($data['scripts'][$hook]) ? implode('; ', $data['scripts'][$hook]) : $data['scripts'][$hook]; self::add_finding('supply_chain', 'medium', "composer.json defines a \"$hook\" script that runs automatically", "Command(s): " . (function_exists('mb_substr') ? mb_substr($commands, 0, 200) : substr($commands, 0, 200)), 'This can be entirely legitimate (build steps, cache warming) - review that the command is one your team actually added.', false); } } } $lock_exists = is_file(ABSPATH . 'composer.lock'); if ($lock_exists) { $lock_mtime = filemtime(ABSPATH . 'composer.lock'); $json_mtime = filemtime($composer_json); if ($lock_mtime && $json_mtime && ($lock_mtime - $json_mtime) > (180 * DAY_IN_SECONDS)) { self::add_finding('supply_chain', 'low', 'composer.json was modified long after composer.lock', 'composer.json changed ' . human_time_diff($json_mtime, $lock_mtime) . ' after composer.lock - dependencies may not match what\'s declared', 'Run "composer update" to refresh the lockfile, or verify this gap is expected.', false); } } } public static function get_findings($status = null) { global $wpdb; $table = $wpdb->prefix . self::TABLE; if ($status) { return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE status = %s ORDER BY FIELD(severity,'critical','high','medium','low')", $status), ARRAY_A); } return $wpdb->get_results("SELECT * FROM $table ORDER BY FIELD(severity,'critical','high','medium','low')", ARRAY_A); } public static function get_score() { global $wpdb; $table = $wpdb->prefix . self::TABLE; $counts = $wpdb->get_row("SELECT SUM(severity='critical' AND status='open') as critical, SUM(severity='high' AND status='open') as high, SUM(severity='medium' AND status='open') as medium, SUM(severity='low' AND status='open') as low FROM $table", ARRAY_A); $critical = (int) ($counts['critical'] ?? 0); $high = (int) ($counts['high'] ?? 0); $medium = (int) ($counts['medium'] ?? 0); $low = (int) ($counts['low'] ?? 0); $penalty = ($critical * 25) + ($high * 10) + ($medium * 4) + ($low * 1); $score = max(0, 100 - $penalty); return ['score' => $score, 'critical' => $critical, 'high' => $high, 'medium' => $medium, 'low' => $low]; } public static function handle_scan() { if (!current_user_can('manage_options')) wp_die('You do not have permission to do this.'); check_admin_referer('wpmm_scan_attack_surface'); self::run_scan(); wp_safe_redirect(admin_url('admin.php?page=wpmm-security-hub&tab=attack-surface&scanned=1')); exit; } public static function handle_update_status() { if (!current_user_can('manage_options')) wp_die('You do not have permission to do this.'); check_admin_referer('wpmm_attack_surface_status'); global $wpdb; $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $status = isset($_POST['status']) ? sanitize_key($_POST['status']) : ''; if ($id && in_array($status, ['open', 'ignored', 'resolved'], true)) { $wpdb->update($wpdb->prefix . self::TABLE, ['status' => $status], ['id' => $id]); } wp_safe_redirect(admin_url('admin.php?page=wpmm-security-hub&tab=attack-surface')); exit; } public static function fix_finding($id) { global $wpdb; $finding = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE id = %d", $wpdb->prefix . self::TABLE, $id), ARRAY_A); if (!$finding) return ['ok' => false, 'error' => 'Finding not found.']; if ($finding['category'] === 'permissions') { $target = (strpos($finding['description'], 'wp-config.php') !== false) ? ABSPATH . 'wp-config.php' : ((strpos($finding['description'], '.htaccess') !== false) ? ABSPATH . '.htaccess' : null); if (!$target || !is_file($target)) return ['ok' => false, 'error' => 'File not found.']; if (!@chmod($target, 0440)) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- user-requested permission fix on wp-config.php/.htaccess; the result is verified right after. return ['ok' => false, 'error' => 'Could not change file permissions - your hosting may not allow PHP to do this. Change it manually via your hosting file manager or FTP client instead.']; } if (wp_is_writable($target)) { return ['ok' => false, 'error' => 'Permissions were changed, but the file is still reported as writable - this usually means your hosting runs PHP as a user/group that can\'t be restricted this way. Please adjust this manually with your host.']; } $wpdb->update($wpdb->prefix . self::TABLE, ['status' => 'resolved'], ['id' => $id]); if (class_exists('WPMM_Activity_Log')) { WPMM_Activity_Log::log('attack_surface_fixed', basename($target), 'File permissions tightened to 440 (read-only)'); } return ['ok' => true]; } if ($finding['category'] === 'unused_component' && strpos($finding['description'], 'inactive theme') !== false) { if (!function_exists('delete_theme')) require_once ABSPATH . 'wp-admin/includes/theme.php'; $active = get_stylesheet(); $deleted = 0; $errors = []; foreach (wp_get_themes() as $slug => $theme) { if ($slug === $active) continue; $result = delete_theme($slug); if (is_wp_error($result)) $errors[] = $slug; else $deleted++; } if ($deleted === 0 && !empty($errors)) { return ['ok' => false, 'error' => 'Could not delete themes: ' . implode(', ', $errors)]; } $wpdb->update($wpdb->prefix . self::TABLE, ['status' => 'resolved'], ['id' => $id]); if (class_exists('WPMM_Activity_Log')) { WPMM_Activity_Log::log('attack_surface_fixed', 'themes', "Deleted $deleted inactive theme(s)" . (!empty($errors) ? ' (failed: ' . implode(', ', $errors) . ')' : '')); } return ['ok' => true]; } if ($finding['category'] === 'unused_component' && strpos($finding['description'], 'inactive plugin') !== false) { if (!function_exists('delete_plugins')) require_once ABSPATH . 'wp-admin/includes/plugin.php'; if (!function_exists('request_filesystem_credentials')) require_once ABSPATH . 'wp-admin/includes/file.php'; $all_plugins = get_plugins(); $active_plugins = get_option('active_plugins', []); $inactive = array_diff(array_keys($all_plugins), $active_plugins); if (empty($inactive)) return ['ok' => false, 'error' => 'No inactive plugins found (they may have been removed already).']; $result = delete_plugins($inactive); if (is_wp_error($result)) { return ['ok' => false, 'error' => $result->get_error_message()]; } $wpdb->update($wpdb->prefix . self::TABLE, ['status' => 'resolved'], ['id' => $id]); if (class_exists('WPMM_Activity_Log')) { WPMM_Activity_Log::log('attack_surface_fixed', 'plugins', 'Deleted ' . count($inactive) . ' inactive plugin(s): ' . implode(', ', $inactive)); } return ['ok' => true]; } return ['ok' => false, 'error' => 'This finding does not have an automatic fix available - please review it manually.']; } public static function handle_fix() { if (!current_user_can('manage_options')) wp_die('You do not have permission to do this.'); check_admin_referer('wpmm_attack_surface_fix'); $id = isset($_POST['id']) ? (int) $_POST['id'] : 0; $result = $id ? self::fix_finding($id) : ['ok' => false, 'error' => 'Missing finding.']; $redirect = admin_url('admin.php?page=wpmm-security-hub&tab=attack-surface'); $redirect = $result['ok'] ? add_query_arg('fixed', '1', $redirect) : add_query_arg('wpmm_error', rawurlencode($result['error']), $redirect); wp_safe_redirect($redirect); exit; } }