Linux服务器安全是每个站长的必修课。一台暴露在公网上的服务器,每天会遭受数千次自动化扫描和攻击尝试。如果不做基本的安全加固,被入侵只是时间问题。本文将系统性地介绍Linux服务器的安全加固措施,从SSH安全到防火墙配置,从入侵检测到日志审计,帮你构建多层次的安全防线。
一、SSH安全加固
SSH是服务器管理的入口,也是攻击者最常尝试的突破点。

1. 修改默认端口
# /etc/ssh/sshd_config Port 2222 # 替换默认22端口
这能挡掉90%的自动化扫描脚本——它们默认只扫描22端口。修改后记得更新防火墙规则和你的SSH客户端配置。
2. 禁止root远程登录
# 先创建普通用户 useradd deploy passwd deploy usermod -aG wheel deploy # CentOS usermod -aG sudo deploy # Ubuntu # 修改SSH配置 PermitRootLogin no
使用普通用户登录后通过sudo提权,即使密码泄露,攻击者也无法直接获得root权限。
3. 使用密钥认证替代密码
# 本地生成密钥对 ssh-keygen -t ed25519 -C "your_comment" # 上传公钥到服务器 ssh-copy-id -p 2222 deploy@your_server_ip # 禁用密码登录 PasswordAuthentication no PubkeyAuthentication yes
ed25519密钥比RSA更安全更短。禁用密码登录后,暴力破解将完全无效。
4. 配置Fail2ban防暴力破解
# 安装 yum install fail2ban -y # CentOS apt install fail2ban -y # Ubuntu # /etc/fail2ban/jail.local [sshd] enabled = true port = 2222 filter = sshd logpath = /var/log/secure maxretry = 3 findtime = 600 bantime = 86400
3次登录失败即封禁IP 24小时。这对自动化暴力破解非常有效。
二、防火墙配置
1. iptables最小化规则集
# 清空默认规则 iptables -F iptables -X # 默认策略:拒绝所有入站,允许所有出站 iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT ACCEPT # 允许本地回环 iptables -A INPUT -i lo -j ACCEPT # 允许已建立的连接 iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # 开放必要端口 iptables -A INPUT -p tcp --dport 2222 -j ACCEPT # SSH iptables -A INPUT -p tcp --dport 80 -j ACCEPT # HTTP iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS iptables -A INPUT -p tcp --dport 8888 -j ACCEPT # 宝塔面板 # 允许ping iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT # 保存规则 service iptables save # CentOS iptables-save > /etc/iptables/rules.v4 # Ubuntu
2. 地理IP封锁(可选)
如果你的网站只面向国内用户,可以直接封锁海外IP段,从源头减少攻击面。可以使用ipset配合iptables实现:
# 安装ipset yum install ipset -y # 创建中国IP白名单 ipset create cn_ips hash:net # 导入中国IP段(从APNIC获取) curl https://raw.githubusercontent.com/17mon/china_ip_list/master/china_ip_list.txt | while read ip; do ipset add cn_ips $ip done # 只允许中国IP访问 iptables -A INPUT -m set --match-set cn_ips src -j ACCEPT
三、系统安全加固
1. 关闭不必要的服务
# 查看运行中的服务 systemctl list-units --type=service --state=running # 关闭不需要的服务 systemctl disable postfix # 邮件服务(如不需要) systemctl disable rpcbind # RPC服务 systemctl disable avahi-daemon # mDNS发现服务
2. 文件权限与umask
# 关键目录权限 chmod 700 /root chmod 600 /etc/shadow chmod 644 /etc/passwd # 设置安全umask # /etc/profile umask 027 # 新文件默认640,新目录默认750
3. 内核参数加固
# /etc/sysctl.conf # 禁止IP转发 net.ipv4.ip_forward = 0 # 禁止源路由 net.ipv4.conf.all.accept_source_route = 0 # 启用反向路径过滤 net.ipv4.conf.all.rp_filter = 1 # 禁止ICMP重定向 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.all.send_redirects = 0 # SYN Flood防护 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_max_syn_backlog = 2048 net.ipv4.tcp_synack_retries = 2 # 生效 sysctl -p
四、入侵检测与审计
1. 文件完整性检查(AIDE)
yum install aide -y aide --init # 初始化数据库 cp /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz aide --check # 检查文件变更
AIDE会记录关键文件的哈希值,任何篡改都会被检测到。建议每天运行一次并通过cron邮件通知。
2. Rootkit检测
# 安装rkhunter和chkrootkit yum install rkhunter chkrootkit -y # 更新数据库并扫描 rkhunter --update rkhunter --check --skip-keypress chkrootkit
3. 登录审计
# 查看登录记录
last -20 # 最近20次登录
lastb -20 # 最近20次失败登录
who # 当前登录用户
# 查看sudo使用记录
cat /var/log/secure | grep sudo
# 设置登录告警(/etc/profile)
readonly LOGIN_ALERT_EMAIL="admin@yoursite.com"
echo "$(whoami) logged in from $(echo $SSH_CLIENT | awk '{print $1}') at $(date)" | mail -s "Server Login Alert" $LOGIN_ALERT_EMAIL
五、Web应用安全
1. Nginx安全头
add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header Content-Security-Policy "default-src 'self'" always; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
2. PHP安全加固
# php.ini安全配置 expose_php = Off display_errors = Off log_errors = On disable_functions = exec,passthru,shell_exec,system,proc_open,popen,show_source,phpinfo open_basedir = /www/wwwroot/:/tmp/ allow_url_fopen = Off allow_url_include = Off
3. 防SQL注入
// PDO预处理(PHP)
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $userId]);
// WordPress
$wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $postId);
永远不要拼接SQL字符串,这是最基本的防线。
六、自动化安全巡检脚本
#!/bin/bash
# /root/security_check.sh
REPORT="/var/log/security_report_$(date +%Y%m%d).txt"
echo "=== 安全巡检报告 $(date) ===" > $REPORT
# 1. 检查异常进程
echo -e "\n[异常进程]" >> $REPORT
ps aux | awk '{if($3 > 50) print $0}' >> $REPORT
# 2. 检查异常网络连接
echo -e "\n[异常连接]" >> $REPORT
netstat -tnp | grep ESTABLISHED | awk '{if($4 !~ /:80|:443|:2222/) print $0}' >> $REPORT
# 3. 检查sudoers变更
echo -e "\n[sudoers变更]" >> $REPORT
stat -c '%y' /etc/sudoers >> $REPORT
# 4. 检查新增用户
echo -e "\n[新增用户]" >> $REPORT
awk -F: '$3 >= 1000 && $3 < 65534 {print $1}' /etc/passwd >> $REPORT
# 5. 检查磁盘使用
echo -e "\n[磁盘使用]" >> $REPORT
df -h | awk 'NR>1 && int($5) > 80 {print $0}' >> $REPORT
# 发送报告
mail -s "Security Report $(date +%Y%m%d)" admin@yoursite.com < $REPORT
添加到crontab每天执行:0 6 * * * /root/security_check.sh
七、总结
服务器安全是一个持续的过程,不是一次性配置。核心原则:最小权限、纵深防御、持续监控。最重要的几件事:SSH密钥认证+改端口+禁root登录、防火墙最小化开放、Fail2ban防暴力破解、定期更新系统。做好这几项,你的服务器安全性已经超过90%的网站。
关注西数资源网,获取更多服务器安全、Linux运维和站长资源技术干货!
相关文章
发表评论
评论列表