一、问题根源分析
常见原因:
- 恶意插件/主题注入
- 数据库被黑/挂马
- XML-RPC攻击
- REST API被滥用
- 用户权限漏洞
- 定时任务(cron)攻击
- Feed导入被利用
二、紧急处理步骤
1. 立即安全措施
// 临时禁止发布新文章(添加到主题functions.php)
function disable_post_creation() {
if (is_admin()) {
$user = wp_get_current_user();
if (!in_array('administrator', (array) $user->roles)) {
remove_menu_page('edit.php');
remove_menu_page('post-new.php');
}
}
}
add_action('admin_init', 'disable_post_creation');
// 禁用XML-RPC(临时)
add_filter('xmlrpc_enabled', '__return_false');
// 禁用REST API(临时)
add_filter('rest_authentication_errors', function($result) {
if (!is_user_logged_in() || !current_user_can('edit_posts')) {
return new WP_Error('rest_disabled', 'REST API已禁用', array('status' => 403));
}
return $result;
});
2. 快速清理恶意文章
-- 在phpMyAdmin中执行,清理英文文章
-- 注意:先备份数据库!
-- 1. 查找并删除特定作者的文章
DELETE posts, meta, term_relationships
FROM wp_posts posts
LEFT JOIN wp_postmeta meta ON posts.ID = meta.post_id
LEFT JOIN wp_term_relationships rel ON posts.ID = rel.object_id
WHERE posts.post_type = 'post'
AND posts.post_author NOT IN (SELECT ID FROM wp_users WHERE user_login = '你的管理员用户名')
AND (posts.post_status = 'publish' OR posts.post_status = 'draft');
-- 2. 查找并删除包含特定内容的文章
DELETE FROM wp_posts
WHERE (post_content LIKE '%spam_keyword%'
OR post_content LIKE '%casino%'
OR post_content LIKE '%viagra%'
OR post_title LIKE '%http://%'
OR post_title LIKE '%https://%')
AND post_type = 'post';
-- 3. 清理垃圾评论
DELETE FROM wp_comments
WHERE comment_approved = 0
OR comment_author LIKE '%spam%';
-- 4. 检查用户表
SELECT * FROM wp_users
WHERE user_registered > DATE_SUB(NOW(), INTERVAL 1 DAY)
AND user_login NOT IN ('你的管理员用户名');
-- 删除可疑用户
DELETE FROM wp_users WHERE ID IN (可疑用户ID);
DELETE FROM wp_usermeta WHERE user_id IN (可疑用户ID);
三、完整安全检查与修复方案
1. 安全扫描脚本
<?php
/**
* WordPress安全扫描工具
* 保存为scan-security.php上传到网站根目录,通过浏览器访问
*/
if (!defined('ABSPATH')) {
define('WP_USE_THEMES', false);
require_once('./wp-load.php');
}
if (!current_user_can('manage_options')) {
wp_die('需要管理员权限');
}
class WP_Security_Scanner {
public function __construct() {
$this->scan();
}
public function scan() {
$results = array();
echo '<h2>🔍 WordPress安全扫描报告</h2>';
echo '<style>body{font-family:monospace;padding:20px} .danger{color:red} .warning{color:orange} .safe{color:green}</style>';
// 1. 扫描可疑文件
$results[] = $this->scan_malicious_files();
// 2. 扫描数据库
$results[] = $this->scan_database();
// 3. 扫描用户
$results[] = $this->scan_users();
// 4. 扫描插件/主题
$results[] = $this->scan_plugins_themes();
// 5. 扫描定时任务
$results[] = $this->scan_cron();
// 6. 扫描.htaccess
$results[] = $this->scan_htaccess();
echo '<h3>📋 修复建议</h3>';
$this->suggest_fixes($results);
}
private function scan_malicious_files() {
echo '<h3>1. 文件系统扫描</h3>';
$suspicious_files = array();
$directories = array(
ABSPATH,
WP_CONTENT_DIR . '/uploads/',
WP_CONTENT_DIR . '/plugins/',
WP_CONTENT_DIR . '/themes/',
);
$malicious_patterns = array(
'/eval\(/i',
'/base64_decode\(/i',
'/gzinflate\(/i',
'/shell_exec\(/i',
'/system\(/i',
'/passthru\(/i',
'/exec\(/i',
'/wget\s+/i',
'/curl\s+/i',
'/iframe/i',
'/onmouseover/i',
'/onload=/i',
'/document\.write/i',
'/fromCharCode/i',
);
foreach ($directories as $dir) {
if (is_dir($dir)) {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($files as $file) {
if ($file->isFile() && in_array($file->getExtension(), array('php', 'js', 'txt'))) {
$content = file_get_contents($file->getPathname());
foreach ($malicious_patterns as $pattern) {
if (preg_match($pattern, $content)) {
$suspicious_files[] = array(
'file' => str_replace(ABSPATH, '', $file->getPathname()),
'pattern' => $pattern
);
break;
}
}
}
}
}
}
if (empty($suspicious_files)) {
echo '<p class="safe">✓ 未发现明显恶意文件</p>';
} else {
echo '<p class="danger">⚠ 发现可疑文件:</p><ul>';
foreach ($suspicious_files as $file) {
echo '<li>' . $file['file'] . ' - 匹配模式: ' . $file['pattern'] . '</li>';
}
echo '</ul>';
}
return $suspicious_files;
}
private function scan_database() {
echo '<h3>2. 数据库扫描</h3>';
global $wpdb;
$issues = array();
// 检查可疑文章
$suspicious_posts = $wpdb->get_results("
SELECT ID, post_author, post_title, post_date
FROM {$wpdb->posts}
WHERE post_type = 'post'
AND (post_content LIKE '%http://%'
OR post_content LIKE '%https://%'
OR post_content LIKE '%<script>%'
OR post_content LIKE '%eval(%'
OR post_content LIKE '%base64_decode(%')
AND post_status = 'publish'
LIMIT 50
");
if ($suspicious_posts) {
echo '<p class="danger">⚠ 发现可疑文章:</p><ul>';
foreach ($suspicious_posts as $post) {
echo '<li>ID: ' . $post->ID . ' - 标题: ' . esc_html($post->post_title) . ' - 时间: ' . $post->post_date . '</li>';
$issues[] = 'suspicious_post_' . $post->ID;
}
echo '</ul>';
} else {
echo '<p class="safe">✓ 未发现可疑文章</p>';
}
// 检查可疑用户元数据
$suspicious_meta = $wpdb->get_results("
SELECT user_id, meta_key, meta_value
FROM {$wpdb->usermeta}
WHERE meta_value LIKE '%<script>%'
OR meta_value LIKE '%eval(%'
OR meta_value LIKE '%http://%'
LIMIT 20
");
if ($suspicious_meta) {
echo '<p class="warning">⚠ 发现可疑用户元数据:</p><ul>';
foreach ($suspicious_meta as $meta) {
echo '<li>用户ID: ' . $meta->user_id . ' - 键: ' . $meta->meta_key . '</li>';
}
echo '</ul>';
}
return $issues;
}
private function scan_users() {
echo '<h3>3. 用户扫描</h3>';
global $wpdb;
$issues = array();
// 检查最近创建的管理员
$recent_admins = $wpdb->get_results("
SELECT u.ID, u.user_login, u.user_email, u.user_registered, um.meta_value as roles
FROM {$wpdb->users} u
INNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
WHERE um.meta_key = '{$wpdb->prefix}capabilities'
AND (um.meta_value LIKE '%administrator%' OR um.meta_value LIKE '%editor%')
AND u.user_registered > DATE_SUB(NOW(), INTERVAL 7 DAY)
");
if ($recent_admins) {
echo '<p class="danger">⚠ 发现最近创建的管理员/编辑:</p><ul>';
foreach ($recent_admins as $user) {
echo '<li>用户名: ' . $user->user_login . ' - 邮箱: ' . $user->user_email . ' - 注册时间: ' . $user->user_registered . '</li>';
$issues[] = 'recent_admin_' . $user->ID;
}
echo '</ul>';
} else {
echo '<p class="safe">✓ 未发现可疑新用户</p>';
}
return $issues;
}
private function scan_plugins_themes() {
echo '<h3>4. 插件和主题扫描</h3>';
$issues = array();
// 检查已安装插件
if (!function_exists('get_plugins')) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$all_plugins = get_plugins();
$active_plugins = get_option('active_plugins');
foreach ($all_plugins as $plugin_path => $plugin) {
$plugin_file = WP_PLUGIN_DIR . '/' . $plugin_path;
// 检查文件修改时间
$file_time = filemtime($plugin_file);
$week_ago = time() - (7 * 24 * 60 * 60);
if ($file_time > $week_ago) {
$status = in_array($plugin_path, $active_plugins) ? '(已启用)' : '(未启用)';
echo '<p class="warning">⚠ 最近修改的插件: ' . $plugin['Name'] . $status . ' - 修改时间: ' . date('Y-m-d H:i:s', $file_time) . '</p>';
$issues[] = 'recent_plugin_' . $plugin_path;
}
}
// 检查主题
$theme = wp_get_theme();
$theme_dir = $theme->get_stylesheet_directory();
if (is_dir($theme_dir)) {
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($theme_dir, RecursiveDirectoryIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$content = file_get_contents($file->getPathname());
if (strpos($content, 'eval(') !== false || strpos($content, 'base64_decode(') !== false) {
echo '<p class="danger">⚠ 主题中发现可疑代码: ' . str_replace($theme_dir, '', $file->getPathname()) . '</p>';
$issues[] = 'malicious_theme_file';
}
}
}
}
if (empty($issues)) {
echo '<p class="safe">✓ 插件和主题检查正常</p>';
}
return $issues;
}
private function scan_cron() {
echo '<h3>5. 定时任务扫描</h3>';
$crons = _get_cron_array();
$suspicious_crons = array();
$suspicious_hooks = array('wp_', 'init', 'admin_init', 'wp_head', 'wp_footer');
foreach ($crons as $timestamp => $cron) {
foreach ($cron as $hook => $events) {
foreach ($events as $event) {
if (strpos($event['schedule'], 'wp_') === 0 ||
in_array($hook, $suspicious_hooks) ||
strpos($hook, 'spam') !== false ||
strpos($hook, 'cron') !== false) {
$suspicious_crons[] = array(
'hook' => $hook,
'timestamp' => $timestamp,
'next_run' => date('Y-m-d H:i:s', $timestamp),
'schedule' => isset($event['schedule']) ? $event['schedule'] : 'single'
);
}
}
}
}
if (!empty($suspicious_crons)) {
echo '<p class="warning">⚠ 发现可疑定时任务:</p><ul>';
foreach ($suspicious_crons as $cron) {
echo '<li>钩子: ' . $cron['hook'] . ' - 下次执行: ' . $cron['next_run'] . ' - 计划: ' . $cron['schedule'] . '</li>';
}
echo '</ul>';
} else {
echo '<p class="safe">✓ 定时任务检查正常</p>';
}
return $suspicious_crons;
}
private function scan_htaccess() {
echo '<h3>6. .htaccess文件扫描</h3>';
$htaccess = ABSPATH . '.htaccess';
if (file_exists($htaccess)) {
$content = file_get_contents($htaccess);
$suspicious_rules = array(
'/RewriteCond.*\\[OR\\]/i',
'/RewriteRule.*php.*\\[L\\]/i',
'/<IfModule.*mod_rewrite.*>/i',
'/php_value.*auto_prepend_file/i',
'/php_flag.*display_errors/i',
'/SetHandler.*application/i',
'/AddType.*application/i',
);
$found = false;
foreach ($suspicious_rules as $pattern) {
if (preg_match($pattern, $content)) {
echo '<p class="danger">⚠ 发现可疑.htaccess规则: ' . htmlspecialchars($pattern) . '</p>';
$found = true;
}
}
if (!$found) {
echo '<p class="safe">✓ .htaccess文件正常</p>';
}
} else {
echo '<p class="safe">✓ 未找到.htaccess文件</p>';
}
}
private function suggest_fixes($results) {
echo '<ol>';
echo '<li><strong>立即更改所有密码:</strong>管理员、FTP、数据库、托管面板密码</li>';
echo '<li><strong>更新所有内容:</strong>WordPress核心、插件、主题到最新版本</li>';
echo '<li><strong>移除可疑插件/主题:</strong>特别是nulled或破解版</li>';
echo '<li><strong>安装安全插件:</strong>Wordfence、Sucuri Security、iThemes Security等</li>';
echo '<li><strong>检查文件权限:</strong>确保wp-content目录755,文件644</li>';
echo '<li><strong>添加安全密钥:</strong>更新wp-config.php中的安全密钥</li>';
echo '<li><strong>启用Web应用防火墙:</strong>如Cloudflare、Sucuri防火墙</li>';
echo '<li><strong>设置文件监控:</strong>监控核心文件修改</li>';
echo '<li><strong>定期备份:</strong>设置自动备份策略</li>';
echo '<li><strong>联系主机商:</strong>检查服务器层面的安全问题</li>';
echo '</ol>';
}
}
// 运行扫描
new WP_Security_Scanner();
2. 安全加固函数
// 添加到主题的functions.php中
class WP_Security_Hardening {
public function __construct() {
// 禁用文件编辑
define('DISALLOW_FILE_EDIT', true);
// 隐藏WordPress版本
remove_action('wp_head', 'wp_generator');
// 添加安全头
add_action('send_headers', array($this, 'add_security_headers'));
// 登录安全
add_action('login_head', array($this, 'login_security'));
// 禁用REST API用户端点
add_filter('rest_endpoints', array($this, 'disable_rest_api_users'));
// 文件上传安全
add_filter('upload_mimes', array($this, 'restrict_upload_mimes'));
// 监控新文章
add_action('save_post', array($this, 'monitor_new_posts'), 10, 3);
// 清理数据库
add_action('wp_scheduled_delete', array($this, 'clean_database'));
}
public function add_security_headers() {
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
}
public function login_security() {
// 限制登录尝试
if (!function_exists('get_login_attempts')) {
add_filter('authenticate', array($this, 'check_login_attempts'), 30, 3);
}
// 添加验证码
add_action('login_form', array($this, 'add_login_captcha'));
add_filter('wp_authenticate_user', array($this, 'validate_login_captcha'), 10, 2);
}
public function check_login_attempts($user, $username, $password) {
if (is_wp_error($user)) {
$transient_name = 'login_attempts_' . $_SERVER['REMOTE_ADDR'];
$attempts = get_transient($transient_name) ?: 0;
$attempts++;
if ($attempts > 5) {
$lockout_time = 30 * 60; // 30分钟
set_transient('login_lockout_' . $_SERVER['REMOTE_ADDR'], true, $lockout_time);
return new WP_Error('too_many_attempts', '登录尝试过多,请30分钟后再试。');
}
set_transient($transient_name, $attempts, 15 * 60); // 15分钟
}
return $user;
}
public function add_login_captcha() {
$num1 = rand(1, 10);
$num2 = rand(1, 10);
$_SESSION['login_captcha'] = $num1 + $num2;
echo '<p>
<label for="login_captcha">验证码:' . $num1 . ' + ' . $num2 . ' = ?<br>
<input type="text" name="login_captcha" class="input" value="" size="20" /></label>
</p>';
}
public function validate_login_captcha($user, $password) {
if (isset($_POST['login_captcha']) && isset($_SESSION['login_captcha'])) {
if ($_POST['login_captcha'] != $_SESSION['login_captcha']) {
return new WP_Error('captcha_error', '验证码错误');
}
}
return $user;
}
public function disable_rest_api_users($endpoints) {
if (isset($endpoints['/wp/v2/users'])) {
unset($endpoints['/wp/v2/users']);
}
if (isset($endpoints['/wp/v2/users/(?P<id>[\d]+)'])) {
unset($endpoints['/wp/v2/users/(?P<id>[\d]+)']);
}
return $endpoints;
}
public function restrict_upload_mimes($mimes) {
// 只允许安全的文件类型
$safe_mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'pdf' => 'application/pdf',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
);
return $safe_mimes;
}
public function monitor_new_posts($post_id, $post, $update) {
if ($update) {
return;
}
$user = wp_get_current_user();
$log_data = array(
'time' => current_time('mysql'),
'user_id' => $user->ID,
'user_login' => $user->user_login,
'post_id' => $post_id,
'post_title' => $post->post_title,
'ip_address' => $_SERVER['REMOTE_ADDR'],
'user_agent' => $_SERVER['HTTP_USER_AGENT']
);
$log_file = WP_CONTENT_DIR . '/post_creation_log.json';
$current_logs = file_exists($log_file) ? json_decode(file_get_contents($log_file), true) : array();
$current_logs[] = $log_data;
file_put_contents($log_file, json_encode($current_logs, JSON_PRETTY_PRINT));
// 检查可疑内容
$suspicious_keywords = array('casino', 'viagra', 'cialis', 'porn', 'xxx', 'http://', 'https://');
foreach ($suspicious_keywords as $keyword) {
if (stripos($post->post_content, $keyword) !== false || stripos($post->post_title, $keyword) !== false) {
// 发送邮件通知
wp_mail(
get_option('admin_email'),
'可疑文章发布警告',
'检测到可疑文章发布:' . $post->post_title . "\n用户:" . $user->user_login . "\nIP:" . $_SERVER['REMOTE_ADDR']
);
break;
}
}
}
public function clean_database() {
global $wpdb;
// 清理自动草稿
$wpdb->query("
DELETE FROM {$wpdb->posts}
WHERE post_status = 'auto-draft'
AND post_date < DATE_SUB(NOW(), INTERVAL 7 DAY)
");
// 清理回收站
$wpdb->query("
DELETE FROM {$wpdb->posts}
WHERE post_status = 'trash'
AND post_modified < DATE_SUB(NOW(), INTERVAL 30 DAY)
");
// 清理修订版本
$wpdb->query("
DELETE FROM {$wpdb->posts}
WHERE post_type = 'revision'
AND post_date < DATE_SUB(NOW(), INTERVAL 30 DAY)
");
}
}
// 初始化安全加固
new WP_Security_Hardening();
3. 防止未来攻击
// 安全防护综合方案
add_action('init', function() {
// 1. 禁用REST API(可选)
if (!is_user_logged_in()) {
add_filter('rest_authentication_errors', function($result) {
return new WP_Error('rest_disabled', 'REST API已禁用', array('status' => 403));
});
}
// 2. 禁用XML-RPC
add_filter('xmlrpc_enabled', '__return_false');
// 3. 隐藏登录错误信息
add_filter('login_errors', function($error) {
return '用户名或密码错误';
});
// 4. 重命名登录URL
if (isset($_GET['hidden_login']) && $_GET['hidden_login'] == '你的密钥') {
add_action('login_form_login', function() {
wp_redirect(wp_login_url());
exit;
});
}
// 5. 限制用户权限
add_action('admin_init', function() {
if (!current_user_can('manage_options')) {
// 限制非管理员
remove_menu_page('tools.php');
remove_menu_page('plugins.php');
remove_menu_page('users.php');
}
});
// 6. 监控文件修改
add_action('upgrader_process_complete', function($upgrader, $options) {
$log_file = WP_CONTENT_DIR . '/file_changes.log';
$log_data = date('Y-m-d H:i:s') . " - 文件更新: " . print_r($options, true) . "\n";
file_put_contents($log_file, $log_data, FILE_APPEND);
}, 10, 2);
// 7. 防止用户枚举
if (is_author()) {
if (isset($_GET['author'])) {
if (is_numeric($_GET['author'])) {
wp_redirect(home_url());
exit;
}
}
}
// 8. 防止目录浏览
if (!is_admin()) {
if (is_dir($_SERVER['REQUEST_URI'])) {
wp_redirect(home_url('404'));
exit;
}
}
});
// 9. 文件权限检查
add_action('admin_notices', function() {
$dangerous_files = array(
ABSPATH . 'wp-config.php' => 400,
ABSPATH . '.htaccess' => 404,
ABSPATH . 'xmlrpc.php' => 400
);
foreach ($dangerous_files as $file => $recommended_permission) {
if (file_exists($file)) {
$permission = substr(sprintf('%o', fileperms($file)), -4);
if ($permission != $recommended_permission) {
echo '<div class="notice notice-error">
<p>⚠ 安全警告:文件 <code>' . $file . '</code> 权限为 ' . $permission . ',建议设置为 ' . $recommended_permission . '</p>
</div>';
}
}
}
});
// 10. 数据库表前缀检查
if (!defined('TABLE_PREFIX_CHECK')) {
global $table_prefix;
if ($table_prefix === 'wp_') {
add_action('admin_notices', function() {
echo '<div class="notice notice-warning">
<p>⚠ 安全建议:建议修改数据库表前缀,默认的 wp_ 前缀不安全。</p>
</div>';
});
}
}
四、自动清理脚本
// 自动清理恶意内容的脚本
class WP_Auto_Cleaner {
public static function clean_malicious_content() {
global $wpdb;
// 1. 清理恶意文章
$malicious_posts = $wpdb->get_results("
SELECT ID FROM {$wpdb->posts}
WHERE post_type = 'post'
AND (
post_content LIKE '%<iframe%' OR
post_content LIKE '%<script%' OR
post_content LIKE '%eval(%' OR
post_content LIKE '%base64_decode%' OR
post_title REGEXP 'http[s]?://' OR
post_content REGEXP 'http[s]?://'
)
AND post_date > DATE_SUB(NOW(), INTERVAL 7 DAY)
");
foreach ($malicious_posts as $post) {
wp_delete_post($post->ID, true);
}
// 2. 清理垃圾用户
$spam_users = $wpdb->get_results("
SELECT ID FROM {$wpdb->users}
WHERE user_registered > DATE_SUB(NOW(), INTERVAL 1 DAY)
AND user_login REGEXP '[0-9]{10}'
AND user_email REGEXP '@qq\.com|@163\.com|@gmail\.com'
");
foreach ($spam_users as $user) {
if (!user_can($user->ID, 'administrator')) {
wp_delete_user($user->ID);
}
}
// 3. 清理可疑用户元数据
$wpdb->query("
DELETE FROM {$wpdb->usermeta}
WHERE meta_key LIKE '%spam%'
OR meta_value LIKE '%http://%'
OR meta_value LIKE '%<script>%'
");
// 4. 清理可疑选项
$suspicious_options = $wpdb->get_results("
SELECT option_name FROM {$wpdb->options}
WHERE option_name LIKE '%cron%'
AND option_value LIKE '%eval%'
");
foreach ($suspicious_options as $option) {
delete_option($option->option_name);
}
// 记录清理日志
$log = date('Y-m-d H:i:s') . " - 清理了 " . count($malicious_posts) . " 篇恶意文章和 " . count($spam_users) . " 个垃圾用户\n";
file_put_contents(WP_CONTENT_DIR . '/clean_log.txt', $log, FILE_APPEND);
return array(
'posts' => count($malicious_posts),
'users' => count($spam_users)
);
}
// 每小时运行一次
public static function schedule_cleanup() {
if (!wp_next_scheduled('hourly_cleanup')) {
wp_schedule_event(time(), 'hourly', 'hourly_cleanup');
}
}
add_action('init', 'schedule_cleanup');
add_action('hourly_cleanup', array(__CLASS__, 'clean_malicious_content'));
}
// 运行清理
WP_Auto_Cleaner::schedule_cleanup();
五、预防措施
1. 安全插件推荐
- Wordfence Security – 全面的安全套件
- Sucuri Security – 专业的安全防护
- iThemes Security – 多层面保护
- All In One WP Security – 免费但功能强大
2. 服务器配置
# .htaccess 安全配置
<IfModule mod_rewrite.c>
RewriteEngine On
# 保护 wp-config.php
<Files wp-config.php>
Order Allow,Deny
Deny from all
</Files>
# 保护 .htaccess
<Files .htaccess>
Order Allow,Deny
Deny from all
</Files>
# 禁止目录浏览
Options -Indexes
# 防止脚本执行
<FilesMatch "\.(php|php5|phtml|pl)$">
Order Deny,Allow
Deny from all
</FilesMatch>
# 保护上传目录
<Directory wp-content/uploads>
<FilesMatch "\.php$">
Order Allow,Deny
Deny from all
</FilesMatch>
</Directory>
</IfModule>
# 安全头
<IfModule mod_headers.c>
Header set X-Content-Type-Options nosniff
Header set X-Frame-Options SAMEORIGIN
Header set X-XSS-Protection "1; mode=block"
</IfModule>
3. wp-config.php 安全设置
// 限制管理员IP
define('WP_ALLOWED_IPS', 'your_ip_address');
if (!defined('WP_CLI') && WP_ALLOWED_IPS && $_SERVER['REMOTE_ADDR'] !== WP_ALLOWED_IPS) {
if (strpos($_SERVER['REQUEST_URI'], '/wp-admin') !== false ||
strpos($_SERVER['REQUEST_URI'], '/wp-login') !== false) {
wp_die('访问被拒绝');
}
}
// 强制SSL
define('FORCE_SSL_ADMIN', true);
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$_SERVER['HTTPS'] = 'on';
}
// 禁用文件编辑
define('DISALLOW_FILE_EDIT', true);
define('DISALLOW_FILE_MODS', true);
// 增加安全密钥
define('AUTH_KEY', 'put your unique phrase here');
define('SECURE_AUTH_KEY', 'put your unique phrase here');
define('LOGGED_IN_KEY', 'put your unique phrase here');
define('NONCE_KEY', 'put your unique phrase here');
define('AUTH_SALT', 'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT', 'put your unique phrase here');
define('NONCE_SALT', 'put your unique phrase here');
六、应急响应清单
- 立即行动:
- 启用维护模式
- 更改所有密码
- 扫描并清理恶意文件
- 清理数据库恶意内容
- 中期修复:
- 更新所有软件
- 安装安全插件
- 配置防火墙
- 设置文件监控
- 长期防护:
- 定期安全审计
- 自动备份策略
- 员工安全培训
- 应急响应计划
- 监控预警:
- 设置异常登录报警
- 监控文件修改
- 数据库变更监控
- 流量异常检测
重要提醒
- 立即备份:在清理前务必备份网站和数据库
- 逐项检查:不要一次性执行所有清理操作
- 联系专业:如无法解决,立即联系专业安全人员
- 保持更新:定期更新WordPress核心、插件和主题
- 使用正版:避免使用nulled或破解版主题/插件
这个方案提供了从检测、清理到防护的完整解决方案。请根据实际情况选择适合的方法,并按照步骤顺序执行。


湘公网安备43020002000238