宝塔面板安全加固与漏洞防护实战指南

本文深度解析宝塔面板的安全风险与防护策略,涵盖安全配置、漏洞防护、入侵检测和应急响应,通过完整的实战案例展示如何构建安全可靠的宝塔面板管理环境。

图片[1]-宝塔面板安全加固与漏洞防护实战指南

一、宝塔面板安全架构深度解析

1.1 宝塔面板安全风险分析与攻击面评估

#!/bin/bash
# 宝塔面板安全加固自动化脚本
# 涵盖身份认证、网络防护、服务安全等全方位加固
set -e
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# 日志函数
log() {
echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] INFO: $1${NC}"
}
warn() {
echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING: $1${NC}"
}
error() {
echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR: $1${NC}"
}
info() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')] INFO: $1${NC}"
}
# 权限检查
check_privileges() {
if [[ $EUID -ne 0 ]]; then
error "此脚本需要root权限运行"
exit 1
fi
}
# 宝塔面板安全状态检测
check_bt_security_status() {
log "开始宝塔面板安全状态检测..."
# 检查面板端口
local panel_port=$(cat /www/server/panel/data/port.pl 2>/dev/null || echo "8888")
info "面板端口: $panel_port"
# 检查默认入口
local panel_entry=$(cat /www/server/panel/data/admin_path.pl 2>/dev/null || echo "未设置")
info "面板入口: $panel_entry"
# 检查登录日志
local failed_logins=$(grep "登录失败" /www/server/panel/logs/request.log 2>/dev/null | wc -l || echo "0")
info "近期登录失败次数: $failed_logins"
# 检查面板版本
local panel_version=$(cat /www/server/panel/class/common.py 2>/dev/null | grep "version = " | cut -d'"' -f2 || echo "未知")
info "面板版本: $panel_version"
}
# 修改默认面板端口
change_default_port() {
log "修改默认面板端口..."
local current_port=$(cat /www/server/panel/data/port.pl 2>/dev/null || echo "8888")
local new_port=$((10000 + RANDOM % 20000))
# 生成随机端口(8888-28888之间)
while [[ $new_port -eq 8888 ]] || [[ $new_port -lt 10000 ]]; do
new_port=$((10000 + RANDOM % 20000))
done
echo "$new_port" > /www/server/panel/data/port.pl
# 重启面板服务
/etc/init.d/bt restart
info "面板端口已从 $current_port 修改为 $new_port"
echo "请使用新端口访问: http://your_server_ip:$new_port"
}
# 设置安全访问入口
set_security_entry() {
log "设置安全访问入口..."
local entry_path="bt_$(openssl rand -hex 8)"
echo "$entry_path" > /www/server/panel/data/admin_path.pl
# 重启面板服务
/etc/init.d/bt restart
info "安全入口已设置: /$entry_path"
echo "请使用新入口访问: http://your_server_ip:端口/$entry_path"
}
# 配置防火墙规则
configure_firewall() {
log "配置防火墙规则..."
local panel_port=$(cat /www/server/panel/data/port.pl 2>/dev/null || echo "8888")
# 检查防火墙状态
if command -v ufw >/dev/null 2>&1; then
# Ubuntu UFW
ufw allow ssh
ufw allow 80,443
ufw allow $panel_port
ufw --force enable
info "UFW防火墙已配置"
elif command -v firewall-cmd >/dev/null 2>&1; then
# CentOS Firewalld
systemctl enable firewalld
systemctl start firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-port=$panel_port/tcp
firewall-cmd --reload
info "Firewalld已配置"
elif command -v iptables >/dev/null 2>&1; then
# iptables
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp --dport $panel_port -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -P INPUT DROP
# 保存iptables规则
if command -v iptables-save >/dev/null 2>&1; then
iptables-save > /etc/iptables/rules.v4
fi
info "iptables已配置"
fi
}
# 强化SSH安全
harden_ssh() {
log "强化SSH安全配置..."
local ssh_config="/etc/ssh/sshd_config"
local backup_file="${ssh_config}.backup.$(date +%Y%m%d_%H%M%S)"
# 备份原配置
cp "$ssh_config" "$backup_file"
# 应用安全配置
cat > /tmp/sshd_security.conf << 'EOF'
# 安全加固配置
Protocol 2
Port 57222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers btadmin
EOF
# 合并配置
python3 - << EOF
import re
with open("$ssh_config", "r") as f:
content = f.read()
# 移除重复配置
lines = content.split('\n')
new_lines = []
for line in lines:
if not any(line.strip().startswith(keyword) for keyword in [
'Protocol', 'Port', 'PermitRootLogin', 'PasswordAuthentication',
'PubkeyAuthentication', 'PermitEmptyPasswords', 'ChallengeResponseAuthentication',
'UsePAM', 'X11Forwarding', 'MaxAuthTries', 'ClientAliveInterval',
'ClientAliveCountMax', 'AllowUsers'
]):
new_lines.append(line)
# 添加新配置
with open("/tmp/sshd_security.conf", "r") as f:
security_config = f.read()
new_content = '\n'.join(new_lines) + '\n' + security_config
with open("$ssh_config", "w") as f:
f.write(new_content)
EOF
# 创建SSH密钥用户
if ! id "btadmin" &>/dev/null; then
useradd -m -s /bin/bash btadmin
mkdir -p /home/btadmin/.ssh
chmod 700 /home/btadmin/.ssh
# 生成SSH密钥对(如果不存在)
if [ ! -f /home/btadmin/.ssh/id_rsa ]; then
ssh-keygen -t rsa -b 4096 -f /home/btadmin/.ssh/id_rsa -N "" -q
fi
# 设置公钥
cat /home/btadmin/.ssh/id_rsa.pub > /home/btadmin/.ssh/authorized_keys
chmod 600 /home/btadmin/.ssh/authorized_keys
chown -R btadmin:btadmin /home/btadmin/.ssh
info "SSH用户 btadmin 已创建,私钥位置: /home/btadmin/.ssh/id_rsa"
warn "请妥善保存私钥文件,这是唯一登录方式!"
fi
# 重启SSH服务
systemctl restart sshd
info "SSH安全加固完成,新端口: 57222"
warn "请使用SSH密钥登录,root登录已禁用"
}
# 配置Fail2ban防护
setup_fail2ban() {
log "配置Fail2ban入侵防护..."
if command -v apt-get >/dev/null 2>&1; then
apt-get update
apt-get install -y fail2ban
elif command -v yum >/dev/null 2>&1; then
yum install -y epel-release
yum install -y fail2ban
fi
# 配置宝塔面板防护
cat > /etc/fail2ban/jail.d/bt-panel.conf << 'EOF'
[bt-panel]
enabled = true
port = http,https,8888
filter = bt-panel
logpath = /www/server/panel/logs/request.log
maxretry = 3
bantime = 3600
findtime = 600
[sshd]
enabled = true
port = 57222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
EOF
# 创建宝塔面板过滤器
cat > /etc/fail2ban/filter.d/bt-panel.conf << 'EOF'
[Definition]
failregex = ^.*\s-\s.*\s\-\s.*POST.*/login.* 200.*$
^.*ERROR.*登录失败.*$
ignoreregex =
EOF
systemctl enable fail2ban
systemctl start fail2ban
info "Fail2ban防护已启用"
}
# Web服务器安全加固
harden_webserver() {
log "加固Web服务器配置..."
# Nginx安全配置
if [ -f /www/server/nginx/conf/nginx.conf ]; then
# 备份原配置
cp /www/server/nginx/conf/nginx.conf /www/server/nginx/conf/nginx.conf.backup.$(date +%Y%m%d_%H%M%S)
# 应用安全配置
cat >> /www/server/nginx/conf/nginx.conf << 'EOF'
# 安全加固配置
server_tokens off;
client_max_body_size 50m;
client_body_buffer_size 128k;
# 安全头配置
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# 限制请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444;
}
EOF
fi
# Apache安全配置
if [ -f /www/server/apache/conf/httpd.conf ]; then
cp /www/server/apache/conf/httpd.conf /www/server/apache/conf/httpd.conf.backup.$(date +%Y%m%d_%H%M%S)
cat >> /www/server/apache/conf/httpd.conf << 'EOF'
# 安全加固配置
ServerTokens Prod
ServerSignature Off
TraceEnable Off
FileETag None
# 安全头配置
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options "nosniff"
Header always set Referrer-Policy "no-referrer-when-downgrade"
EOF
fi
# 重启Web服务
if systemctl is-active --quiet nginx; then
systemctl restart nginx
info "Nginx安全加固完成"
fi
if systemctl is-active --quiet httpd; then
systemctl restart httpd
info "Apache安全加固完成"
fi
}
# 数据库安全加固
harden_database() {
log "加固数据库安全..."
# MySQL安全配置
if [ -f /etc/my.cnf ]; then
cp /etc/my.cnf /etc/my.cnf.backup.$(date +%Y%m%d_%H%M%S)
cat >> /etc/my.cnf << 'EOF'
# 安全加固配置
[mysqld]
local_infile=0
symbolic-links=0
skip-symbolic-links
secure-file-priv=/tmp
EOF
# 重启MySQL
if systemctl is-active --quiet mysqld; then
systemctl restart mysqld
info "MySQL安全加固完成"
fi
fi
}
# 文件权限加固
harden_file_permissions() {
log "加固文件权限..."
# 宝塔面板目录权限
chmod 600 /www/server/panel/data/port.pl
chmod 600 /www/server/panel/data/admin_path.pl
chmod 600 /www/server/panel/data/ssl.pl 2>/dev/null || true
chmod 700 /www/server/panel/data
# 敏感配置文件
find /www/server/panel -name "*.py" -exec chmod 600 {} \;
find /www/server/panel -name "*.conf" -exec chmod 600 {} \;
# 日志文件权限
find /www/server/panel/logs -type f -exec chmod 600 {} \;
info "文件权限加固完成"
}
# 配置安全审计
setup_security_audit() {
log "配置安全审计..."
# 安装auditd
if command -v apt-get >/dev/null 2>&1; then
apt-get install -y auditd
elif command -v yum >/dev/null 2>&1; then
yum install -y audit
fi
# 配置审计规则
cat > /etc/audit/rules.d/bt-security.rules << 'EOF'
# 监控宝塔面板目录
-w /www/server/panel -p wa -k bt_panel
-w /www/server/panel/data -p wa -k bt_data
-w /www/server/panel/logs -p wa -k bt_logs
# 监控系统关键文件
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/sudoers -p wa -k identity
# 监控SSH配置
-w /etc/ssh/sshd_config -p wa -k ssh_config
# 监控Web服务器配置
-w /www/server/nginx/conf/nginx.conf -p wa -k nginx_config
-w /www/server/apache/conf/httpd.conf -p wa -k apache_config
# 监控数据库配置
-w /etc/my.cnf -p wa -k mysql_config
EOF
systemctl enable auditd
systemctl restart auditd
info "安全审计已配置"
}
# 创建安全监控脚本
create_security_monitor() {
log "创建安全监控脚本..."
cat > /root/bt_security_monitor.sh << 'EOF'
#!/bin/bash
# 宝塔面板安全监控脚本
# 定期检查安全状态和异常活动
LOG_FILE="/var/log/bt_security.log"
ALERT_EMAIL="admin@yourdomain.com"
# 日志函数
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> $LOG_FILE
}
# 检查失败登录
check_failed_logins() {
local failed_count=$(grep "登录失败" /www/server/panel/logs/request.log 2>/dev/null | tail -100 | wc -l)
if [ $failed_count -gt 10 ]; then
log "警告: 检测到大量登录失败尝试: $failed_count"
# 可以添加邮件通知
# echo "宝塔面板登录失败次数异常: $failed_count" | mail -s "安全警告" $ALERT_EMAIL
fi
}
# 检查文件完整性
check_file_integrity() {
local critical_files=(
"/www/server/panel/data/port.pl"
"/www/server/panel/data/admin_path.pl"
"/www/server/panel/class/common.py"
"/www/server/panel/config/config.json"
)
for file in "${critical_files[@]}"; do
if [ ! -f "$file" ]; then
log "警告: 关键文件不存在: $file"
fi
done
}
# 检查服务状态
check_services() {
local services=("bt" "nginx" "mysqld" "php-fpm")
for service in "${services[@]}"; do
if systemctl is-active --quiet "$service"; then
: # 服务正常运行
else
log "警告: 服务异常: $service"
systemctl restart "$service" 2>/dev/null && log "已重启服务: $service"
fi
done
}
# 检查资源使用
check_resources() {
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
local mem_usage=$(free | awk '/Mem:/ {printf("%.2f"), $3/$2 * 100}')
if (( $(echo "$cpu_usage > 80" | bc -l) )); then
log "警告: CPU使用率过高: ${cpu_usage}%"
fi
if (( $(echo "$mem_usage > 85" | bc -l) )); then
log "警告: 内存使用率过高: ${mem_usage}%"
fi
}
# 主监控函数
main_monitor() {
log "开始安全监控检查..."
check_failed_logins
check_file_integrity
check_services
check_resources
log "安全监控检查完成"
}
# 执行监控
main_monitor
EOF
chmod +x /root/bt_security_monitor.sh
# 添加定时任务
(crontab -l 2>/dev/null; echo "*/5 * * * * /root/bt_security_monitor.sh") | crontab -
info "安全监控脚本已部署"
}
# 生成安全报告
generate_security_report() {
log "生成安全加固报告..."
local report_file="/root/bt_security_report_$(date +%Y%m%d_%H%M%S).txt"
cat > "$report_file" << EOF
宝塔面板安全加固报告
生成时间: $(date)
==================== 安全配置摘要 ====================
1. 面板访问信息:
- 端口: $(cat /www/server/panel/data/port.pl 2>/dev/null || echo "未知")
- 安全入口: $(cat /www/server/panel/data/admin_path.pl 2>/dev/null || echo "未设置")
2. SSH安全配置:
- SSH端口: 57222
- Root登录: 已禁用
- 密钥认证: 已启用
- 授权用户: btadmin
3. 防护系统:
- Fail2ban: $(systemctl is-active fail2ban 2>/dev/null && echo "运行中" || echo "未运行")
- 安全审计: $(systemctl is-active auditd 2>/dev/null && echo "运行中" || echo "未运行")
4. 网络防护:
- 防火墙: $(command -v ufw >/dev/null && echo "UFW" || command -v firewall-cmd >/dev/null && echo "Firewalld" || echo "iptables")
5. 监控系统:
- 安全监控脚本: 已部署
- 定时任务: 已配置
==================== 重要提醒 ====================
1. 请妥善保存SSH私钥: /home/btadmin/.ssh/id_rsa
2. 新的面板访问地址: http://服务器IP:$(cat /www/server/panel/data/port.pl)/$(cat /www/server/panel/data/admin_path.pl)
3. SSH使用命令: ssh -p 57222 btadmin@服务器IP -i /path/to/private_key
==================== 后续维护 ====================
1. 定期检查安全日志: /var/log/bt_security.log
2. 监控系统资源使用情况
3. 及时更新系统和面板版本
4. 定期审查fail2ban日志
EOF
info "安全加固报告已生成: $report_file"
cat "$report_file"
}
# 主函数
main() {
log "开始宝塔面板安全加固..."
check_privileges
check_bt_security_status
change_default_port
set_security_entry
configure_firewall
harden_ssh
setup_fail2ban
harden_webserver
harden_database
harden_file_permissions
setup_security_audit
create_security_monitor
generate_security_report
log "宝塔面板安全加固完成!"
warn "请立即保存生成的安全报告,并测试新的访问方式!"
}
# 执行主函数
main "$@"

二、Web应用防火墙与入侵防护

2.1 Nginx高级安全配置

# /www/server/panel/vhost/nginx/security.conf
# 宝塔面板Nginx安全增强配置
# 基础安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# CSP安全策略
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; img-src 'self' data: https:; font-src 'self' https://cdn.jsdelivr.net; connect-src 'self';" always;
# 防止点击劫持
add_header X-Frame-Options "DENY" always;
# 请求限制
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/m;
limit_req_zone $binary_remote_addr zone=login:10m rate=3r/m;
# 宝塔面板位置块安全配置
location ~ ^/.*(login|api) {
limit_req zone=login burst=5 nodelay;
limit_req zone=api burst=10 nodelay;
# 禁止敏感路径外部访问
allow 127.0.0.1;
allow 10.0.0.0/8;
allow 172.16.0.0/12;
allow 192.168.0.0/16;
deny all;
}
# 阻止常见攻击路径
location ~* \.(git|svn|htaccess|htpasswd|env)$ {
deny all;
return 404;
}
location ~ /\. {
deny all;
return 404;
}
# 阻止SQL注入和XSS攻击
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
set $block_sql_injections 1;
}
if ($query_string ~ "union.*all.*select.*") {
set $block_sql_injections 1;
}
if ($query_string ~ "concat.*\(") {
set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
return 403;
}
set $block_xss 0;
if ($query_string ~ "<script.*>") {
set $block_xss 1;
}
if ($query_string ~ "javascript:") {
set $block_xss 1;
}
if ($block_xss = 1) {
return 403;
}
# 文件上传限制
client_max_body_size 50m;
client_body_buffer_size 128k;
client_body_timeout 60;
client_header_timeout 60;
# 隐藏服务器信息
server_tokens off;
more_clear_headers 'Server';
more_clear_headers 'X-Powered-By';
# Gzip压缩安全配置
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

三、安全监控与应急响应

3.1 实时安全监控仪表板

<strong>#!/bin/bash</strong>
# 宝塔面板安全监控仪表板
# 实时显示安全状态和威胁情报
display_security_dashboard() {
clear
echo "================================================"
echo "          宝塔面板安全监控仪表板"
echo "================================================"
echo "更新时间: $(date)"
echo ""
# 系统安全状态
echo "=== 系统安全状态 ==="
local fail2ban_status=$(systemctl is-active fail2ban)
local audit_status=$(systemctl is-active auditd)
local firewall_status=$(check_firewall_status)
echo "Fail2ban: $([ "$fail2ban_status" = "active" ] && echo "✅ 运行中" || echo "❌ 异常")"
echo "安全审计: $([ "$audit_status" = "active" ] && echo "✅ 运行中" || echo "❌ 异常")"
echo "防火墙: $firewall_status"
echo ""
# 登录安全统计
echo "=== 登录安全统计 ==="
local failed_logins=$(grep "登录失败" /www/server/panel/logs/request.log <strong>2</strong>>/dev/null | tail -50 | wc -l)
local banned_ips=$(fail2ban-client status sshd <strong>2</strong>>/dev/null | grep "Currently banned" | awk '{print $4}' || echo "0")
echo "最近登录失败: $failed_logins 次"
echo "当前封禁IP: $banned_ips 个"
echo ""
# 系统资源监控
echo "=== 系统资源监控 ==="
local cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
local mem_usage=$(free | awk '/Mem:/ {printf("%.2f"), $3/$2 * 100}')
local disk_usage=$(df -h / | awk 'NR==2 {print $5}')
echo "CPU使用率: ${cpu_usage}%"
echo "内存使用率: ${mem_usage}%"
echo "磁盘使用率: $disk_usage"
echo ""
# 最近安全事件
echo "=== 最近安全事件 ==="
tail -10 /var/log/bt_security.log <strong>2</strong>>/dev/null | while read line; do
echo "  $line"
done
echo ""
echo "输入 'q' 退出,回车刷新..."
}
check_firewall_status() {
if command -v ufw >/dev/null <strong>2</strong>><strong>&1</strong>; then
ufw status | grep -q "Status: active" && echo "✅ UFW运行中" || echo "❌ UFW未运行"
elif command -v firewall-cmd >/dev/null <strong>2</strong>><strong>&1</strong>; then
firewall-cmd --state >/dev/null <strong>2</strong>><strong>&1</strong> && echo "✅ Firewalld运行中" || echo "❌ Firewalld未运行"
else
iptables -L >/dev/null <strong>2</strong>><strong>&1</strong> && echo "✅ iptables运行中" || echo "❌ iptables异常"
fi
}
# 实时监控循环
start_realtime_monitor() {
while true; do
display_security_dashboard
read -t 10 -n 1 input
if [[ $input = "q" ]]; then
break
fi
done
}
# 主菜单
show_main_menu() {
while true; do
clear
echo "================================================"
echo "          宝塔面板安全管理中心"
echo "================================================"
echo "1. 实时安全监控"
echo "2. 查看安全日志"
echo "3. 检查系统状态"
echo "4. 管理封禁IP"
echo "5. 更新安全规则"
echo "6. 退出"
echo ""
read -p "请选择操作 [1-6]: " choice
case $choice in
1)
start_realtime_monitor
;;
2)
view_security_logs
;;
3)
check_system_status
;;
4)
manage_banned_ips
;;
5)
update_security_rules
;;
6)
exit 0
;;
*)
echo "无效选择,请重新输入"
sleep 2
;;
esac
done
}
view_security_logs() {
clear
echo "=== 安全日志查看 ==="
echo "1. 面板访问日志"
echo "2. 失败登录日志"
echo "3. Fail2ban日志"
echo "4. 系统审计日志"
echo "5. 返回主菜单"
echo ""
read -p "请选择: " log_choice
case $log_choice in
1)
tail -f /www/server/panel/logs/request.log
;;
2)
grep "登录失败" /www/server/panel/logs/request.log | tail -20
read -p "按回车继续..."
;;
3)
tail -f /var/log/fail2ban.log
;;
4)
ausearch -k bt_panel | tail -20
read -p "按回车继续..."
;;
5)
return
;;
*)
echo "无效选择"
;;
esac
}
check_system_status() {
clear
echo "=== 系统安全检查 ==="
# 检查关键服务
echo "服务状态检查:"
local services=("bt" "nginx" "mysqld" "php-fpm" "fail2ban" "auditd")
for service in "${services[@]}"; do
if systemctl is-active --quiet "$service"; then
echo "✅ $service: 运行正常"
else
echo "❌ $service: 服务异常"
fi
done
echo ""
# 检查文件完整性
echo "文件完整性检查:"
local critical_files=(
"/www/server/panel/data/port.pl"
"/www/server/panel/data/admin_path.pl"
"/etc/ssh/sshd_config"
)
for file in "${critical_files[@]}"; do
if [ -f "$file" ]; then
local perms=$(stat -c "%a" "$file")
if [ "$perms" = "600" ]; then
echo "✅ $file: 权限正常"
else
echo "⚠️  $file: 权限异常 ($perms)"
fi
else
echo "❌ $file: 文件不存在"
fi
done
read -p "按回车继续..."
}
manage_banned_ips() {
clear
echo "=== IP封禁管理 ==="
echo "1. 查看封禁IP"
echo "2. 解封IP"
echo "3. 手动封禁IP"
echo "4. 返回"
echo ""
read -p "请选择: " ip_choice
case $ip_choice in
1)
echo "当前封禁的IP:"
fail2ban-client status sshd | grep "Banned IP list" -A 100
read -p "按回车继续..."
;;
2)
read -p "请输入要解封的IP: " ip_addr
fail2ban-client set sshd unbanip "$ip_addr"
echo "IP $ip_addr 已解封"
sleep 2
;;
3)
read -p "请输入要封禁的IP: " ip_addr
fail2ban-client set sshd banip "$ip_addr"
echo "IP $ip_addr 已封禁"
sleep 2
;;
4)
return
;;
*)
echo "无效选择"
;;
esac
}
update_security_rules() {
clear
echo "=== 更新安全规则 ==="
# 更新Fail2ban规则
fail2ban-client reload
echo "Fail2ban规则已更新"
# 更新审计规则
auditctl -R /etc/audit/rules.d/bt-security.rules
echo "审计规则已更新"
# 重新加载防火墙
if command -v ufw >/dev/null <strong>2</strong>><strong>&1</strong>; then
ufw reload
elif command -v firewall-cmd >/dev/null <strong>2</strong>><strong>&1</strong>; then
firewall-cmd --reload
fi
echo "防火墙规则已更新"
read -p "安全规则更新完成,按回车继续..."
}
# 启动管理界面
show_main_menu

四、应急响应与恢复

4.1 安全事件应急响应流程

<strong>#!/bin/bash</strong>
# 宝塔面板安全事件应急响应脚本
# 用于检测和响应安全事件
# 事件响应主函数
emergency_response() {
local incident_type=$1
case $incident_type in
"brute_force")
respond_to_brute_force
;;
"malware")
respond_to_malware
;;
"unauthorized_access")
respond_to_unauthorized_access
;;
"data_breach")
respond_to_data_breach
;;
*)
echo "未知事件类型"
;;
esac
}
# 暴力破解响应
respond_to_brute_force() {
log "检测到暴力破解攻击,启动应急响应..."
# 立即封禁攻击IP段
local attacker_ips=$(grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | head -10)
echo "封禁频繁攻击IP:"
echo "$attacker_ips" | while read count ip; do
if [ $count -gt 10 ]; then
fail2ban-client set sshd banip "$ip"
echo "已封禁IP: $ip (尝试次数: $count)"
fi
done
# 增强防护规则
fail2ban-client set sshd addignoreip 127.0.0.1
fail2ban-client set sshd bantime 7200
fail2ban-client set sshd findtime 600
fail2ban-client set sshd maxretry 3
# 发送警报
send_alert "暴力破解攻击检测" "检测到SSH暴力破解攻击,已自动封禁可疑IP"
log "暴力破解攻击响应完成"
}
# 恶意软件响应
respond_to_malware() {
log "检测到恶意软件,启动清除程序..."
# 停止Web服务
systemctl stop nginx
systemctl stop apache2
systemctl stop php-fpm
# 扫描恶意文件
scan_malicious_files
# 检查后门
check_backdoors
# 恢复清洁备份
restore_clean_backup
# 重启服务
systemctl start nginx
systemctl start php-fpm
log "恶意软件清除完成"
}
# 未授权访问响应
respond_to_unauthorized_access() {
log "检测到未授权访问,启动调查..."
# 检查当前登录用户
local current_users=$(who)
echo "当前登录用户:"
echo "$current_users"
# 检查最近登录
local recent_logins=$(last -n 20)
echo "最近登录记录:"
echo "$recent_logins"
# 检查进程
local suspicious_processes=$(ps aux | grep -E "(wget|curl|nc|netcat|bash -i)" | grep -v grep)
if [ -n "$suspicious_processes" ]; then
echo "发现可疑进程:"
echo "$suspicious_processes"
# 终止可疑进程
echo "$suspicious_processes" | awk '{print $2}' | xargs kill -9
fi
# 检查计划任务
local suspicious_cron=$(crontab -l | grep -E "(wget|curl|bash -i|sh -i)")
if [ -n "$suspicious_cron" ]; then
echo "发现可疑计划任务:"
echo "$suspicious_cron"
crontab -r
fi
send_alert "未授权访问检测" "检测到系统未授权访问,已启动安全响应"
log "未授权访问调查完成"
}
# 数据泄露响应
respond_to_data_breach() {
log "检测到数据泄露,启动应急措施..."
# 立即更改所有数据库密码
change_database_passwords
# 重置面板密码
reset_panel_password
# 检查数据导出记录
check_data_exports
# 封锁外部访问
block_external_access
send_alert "数据泄露事件" "检测到潜在数据泄露,已启动紧急响应"
log "数据泄露响应完成"
}
# 辅助函数
scan_malicious_files() {
log "扫描恶意文件..."
# 使用ClamAV扫描
if command -v clamscan >/dev/null <strong>2</strong>><strong>&1</strong>; then
clamscan -r -i /www/wwwroot/
clamscan -r -i /www/server/
else
# 基础恶意文件检测
find /www/wwwroot -name "*.php" -exec grep -l "base64_decode\|eval(\|system(\|shell_exec" {} \; > /tmp/suspicious_files.txt
find /www/wwwroot -name "*.jpg" -size +100k -exec file {} \; | grep "PHP" | cut -d: -f1 >> /tmp/suspicious_files.txt
fi
if [ -s /tmp/suspicious_files.txt ]; then
echo "发现可疑文件:"
cat /tmp/suspicious_files.txt
# 隔离可疑文件
mkdir -p /root/quarantine/
cat /tmp/suspicious_files.txt | xargs -I {} mv {} /root/quarantine/
fi
}
check_backdoors() {
log "检查后门程序..."
# 检查异常网络连接
local suspicious_connections=$(netstat -tunap | grep -E "(:1337|:31337|:54321)" | grep -v ESTABLISHED)
if [ -n "$suspicious_connections" ]; then
echo "发现可疑网络连接:"
echo "$suspicious_connections"
fi
# 检查隐藏进程
local hidden_processes=$(ps aux | awk '{print $2}' | sort -n | uniq -d)
if [ -n "$hidden_processes" ]; then
echo "发现重复PID(可能隐藏进程):"
echo "$hidden_processes"
fi
}
change_database_passwords() {
log "更改数据库密码..."
# 生成新密码
local new_password=$(openssl rand -base64 16)
# 更改MySQL root密码
mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED BY '$new_password';"
mysql -e "FLUSH PRIVILEGES;"
# 更新面板数据库配置
sed -i "s/\"mysql_root\":\".*\"/\"mysql_root\":\"$new_password\"/" /www/server/panel/data/default.db
echo "数据库密码已更改"
}
reset_panel_password() {
log "重置面板密码..."
# 生成新密码
local new_password=$(openssl rand -base64 12)
# 使用宝塔命令重置密码
cd /www/server/panel && python tools.py panel "$new_password"
echo "面板密码已重置为: $new_password"
}
block_external_access() {
log "封锁外部访问..."
# 只允许本地访问
iptables -F
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -s 127.0.0.1 -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -P INPUT DROP
echo "外部访问已封锁,仅允许本地连接"
}
send_alert() {
local subject=$1
local message=$2
# 这里可以集成邮件、短信、Webhook等通知方式
echo "警报: $subject"
echo "内容: $message"
echo "时间: $(date)"
# 示例:发送到syslog
logger -t "BT_SECURITY_ALERT" "$subject - $message"
}
# 主响应流程
main_response() {
echo "请选择安全事件类型:"
echo "1. 暴力破解攻击"
echo "2. 恶意软件感染"
echo "3. 未授权访问"
echo "4. 数据泄露"
echo "5. 自定义调查"
read -p "请输入选择 [1-5]: " choice
case $choice in
1) emergency_response "brute_force" ;;
2) emergency_response "malware" ;;
3) emergency_response "unauthorized_access" ;;
4) emergency_response "data_breach" ;;
5) start_forensic_investigation ;;
*) echo "无效选择" ;;
esac
}
start_forensic_investigation() {
log "启动取证调查..."
# 创建取证目录
local investigation_dir="/root/forensic_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$investigation_dir"
# 收集系统信息
collect_evidence "$investigation_dir"
# 分析时间线
analyze_timeline "$investigation_dir"
# 生成调查报告
generate_forensic_report "$investigation_dir"
log "取证调查完成,结果保存在: $investigation_dir"
}
collect_evidence() {
local dir=$1
log "收集证据数据..."
# 系统信息
uname -a > "$dir/system_info.txt"
ps aux > "$dir/processes.txt"
netstat -tunap > "$dir/network_connections.txt"
# 用户信息
last > "$dir/login_history.txt"
cat /etc/passwd > "$dir/passwd.txt"
cat /etc/shadow > "$dir/shadow.txt"
# 文件系统
find /www -type f -name "*.php" -exec ls -la {} \; > "$dir/php_files.txt"
find /tmp -type f -mtime -7 > "$dir/recent_tmp_files.txt"
# 日志文件
cp /var/log/auth.log "$dir/"
cp /var/log/syslog "$dir/"
cp /www/server/panel/logs/request.log "$dir/"
}
# 启动应急响应
main_response

总结

通过本文的深度安全加固方案,宝塔面板可以获得企业级的安全防护能力:

  1. 基础安全加固 – 端口修改、安全入口、防火墙配置
  2. 身份认证强化 – SSH密钥登录、多因素认证
  3. 入侵检测防护 – Fail2ban、安全审计、实时监控
  4. Web应用安全 – WAF规则、安全头、请求限制
  5. 应急响应体系 – 事件检测、自动响应、取证调查

这些措施共同构建了纵深防御体系,能够有效防护宝塔面板面临的各类安全威胁。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容