以下是一份详细的 Linux 服务器安全加固指南,涵盖基础到进阶的关键配置,建议系统管理员逐项检查实施:
禁用 root 远程登录
# 修改 /etc/ssh/sshd_config
PermitRootLogin no
重启 SSH 服务:systemctl restart sshd
创建特权用户
useradd admin && passwd admin
usermod -aG sudo admin # Ubuntu/Debian
usermod -aG wheel admin # CentOS/RHEL
强制密钥认证
# /etc/ssh/sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
用户需提前部署公钥到 ~/.ssh/authorized_keys
启用 firewalld/ufw
# RHEL/CentOS
systemctl enable --now firewalld
firewall-cmd --permanent --add-service=ssh
firewall-cmd --reload
# Ubuntu
ufw enable
ufw allow 22/tcp
限制 SSH 端口访问
# 仅允许特定IP访问SSH
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="x.x.x.x" port protocol="tcp" port="22" accept'
关闭无用服务
systemctl list-unit-files | grep enabled
systemctl disable <unused_service>
禁用 IPv6(如不需要)
# /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
生效:sysctl -p
SSH 强化
# /etc/ssh/sshd_config
Port 2222 # 修改默认端口
MaxAuthTries 3 # 限制尝试次数
ClientAliveInterval 300 # 会话超时
AllowUsers admin # 白名单用户
Fail2Ban 防暴力破解
apt install fail2ban -y # Ubuntu
yum install fail2ban -y # CentOS
systemctl enable --now fail2ban
配置示例:/etc/fail2ban/jail.local
启用 auditd
systemctl enable --now auditd
# 监控关键文件
auditctl -w /etc/passwd -p wa -k passwd_changes
日志集中管理
rsyslog
转发日志到中央服务器logrotate
)配置无人值守更新
# Ubuntu
apt install unattended-upgrades
dpkg-reconfigure unattended-upgrades
# CentOS
yum install yum-cron
systemctl enable --now yum-cron
# /etc/sysctl.conf
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
kernel.exec-shield = 1
生效:sysctl -p
关键目录权限
chmod 700 /etc/cron* /etc/ssh/ssh_host_*_key
chattr +i /etc/passwd /etc/shadow
禁用 SUID/SGID 危险程序
find / -perm /4000 -o -perm /2000 -type f -exec ls -ld {} \;
Rootkit 检测
# 安装 rkhunter
rkhunter --check --sk
漏洞扫描
yum install openscap-scanner # RHEL
oscap xccdf eval --profile standard \
/usr/share/xml/scap/ssg/content/ssg-rhel7-ds.xml
关键数据备份
# 每日定时任务(crontab)
0 3 * * * tar -zcvf /backup/etc_$(date +\%F).tar.gz /etc
配置版本控制
git init /etc
git add . && git commit -m "Initial config"
实施建议:
1. 测试环境验证后再上生产
2. 使用 visudo
而非直接编辑 /etc/sudoers
3. 定期审查 /var/log/auth.log
或 /var/log/secure
4. 推荐使用 CIS Benchmark 作为基准检查
通过以上措施可显著提升服务器安全性,但需注意安全是持续过程,建议结合监控告警系统(如 Prometheus + Grafana)实现实时防护。