Linux 服务器安全加固指南

一、前言

服务器安全是运维工作的重中之重。本文档提供一套完整的 Linux 服务器安全加固方案,涵盖系统配置、网络防护、访问控制、审计监控等多个维度,适用于生产环境的 CentOS/Ubuntu 服务器。

二、系统更新与补丁管理

2.1 更新系统包

1
2
3
4
5
6
7
8
9
# Ubuntu/Debian
apt-get update && apt-get upgrade -y

# CentOS/RHEL
yum update -y

# 启用自动安全更新
apt-get install -y unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades

2.2 配置自动更新

1
2
3
4
5
# /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";

2.3 定期安全扫描

1
2
3
4
5
6
# 安装 lynis 进行安全审计
apt-get install -y lynis
lynis audit system

# 检查漏洞包
apt-get install -y apt-listchanges

三、用户与权限管理

3.1 禁用 root 远程登录

1
2
3
4
5
6
# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 60

3.2 创建普通用户并授权 sudo

1
2
3
4
5
6
7
8
9
10
11
# 创建用户
adduser admin
passwd admin

# 添加 sudo 权限
usermod -aG sudo admin # Ubuntu
usermod -aG wheel admin # CentOS

# 配置 sudo 免密(可选)
echo "admin ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/admin
chmod 440 /etc/sudoers.d/admin

3.3 设置密码策略

1
2
3
4
5
6
# /etc/pam.d/common-password (Ubuntu) 或 /etc/pam.d/system-auth (CentOS)
password requisite pam_pwquality.so retry=3 minlen=12 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
password required pam_unix.so sha512 shadow remember=5

# 设置密码过期策略
chage -M 90 -m 7 -W 14 admin

3.4 锁定系统账户

1
2
3
4
5
6
7
# 锁定不需要的系统账户
for user in games ftp news uucp proxy www-data backup list irc gnats; do
usermod -L $user 2>/dev/null
done

# 检查空密码账户
awk -F: '($2 == "") {print $1}' /etc/shadow

四、SSH 安全加固

4.1 修改 SSH 端口

1
2
3
4
# /etc/ssh/sshd_config
Port 2222
AddressFamily inet
ListenAddress 0.0.0.0

4.2 限制 SSH 访问用户

1
2
3
# /etc/ssh/sshd_config
AllowUsers admin deploy
AllowGroups sudo wheel

4.3 配置 SSH 密钥认证

1
2
3
4
5
6
7
8
9
# 生成密钥对(客户端)
ssh-keygen -t ed25519 -C "admin@server"

# 上传公钥
ssh-copy-id -p 2222 admin@server

# 设置权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

4.4 启用双因素认证(可选)

1
2
3
4
5
6
7
8
9
10
11
# 安装 Google Authenticator
apt-get install -y libpam-google-authenticator

# 配置用户
google-authenticator -t -d -f -r 3 -R 30 -w 3

# /etc/pam.d/sshd
auth required pam_google_authenticator.so

# /etc/ssh/sshd_config
AuthenticationMethods publickey,keyboard-interactive

4.5 安装 Fail2Ban

1
2
3
4
5
6
7
8
9
10
11
12
13
14
apt-get install -y fail2ban

# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600

systemctl enable fail2ban
systemctl restart fail2ban

五、防火墙配置

5.1 UFW 配置(Ubuntu)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 安装并启用
apt-get install -y ufw
ufw --force enable

# 默认策略
ufw default deny incoming
ufw default allow outgoing

# 允许必要端口
ufw allow 2222/tcp # SSH
ufw allow 80/tcp # HTTP
ufw allow 443/tcp # HTTPS
ufw allow from 10.0.0.0/8 # 内网访问

# 查看状态
ufw status verbose

5.2 Firewalld 配置(CentOS)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 启用 firewalld
systemctl enable firewalld
systemctl start firewalld

# 配置区域
firewall-cmd --set-default-zone=drop

# 添加服务
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https

# 添加端口
firewall-cmd --permanent --add-port=2222/tcp

# 富规则限制 IP
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" accept'

firewall-cmd --reload

5.3 iptables 基础规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 清除现有规则
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 OUTPUT -o lo -j ACCEPT

# 允许已建立的连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 允许 SSH
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT

# 防止 SYN 洪水
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT

# 保存规则
iptables-save > /etc/iptables/rules.v4

六、内核安全加固

6.1 配置 sysctl 安全参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# /etc/sysctl.d/99-security.conf

# 禁用 IP 转发(非路由服务器)
net.ipv4.ip_forward = 0

# 禁用 ICMP 重定向
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0

# 启用 SYN Cookie 防护
net.ipv4.tcp_syncookies = 1

# 忽略 ICMP 广播
net.ipv4.icmp_echo_ignore_broadcasts = 1

# 启用反向路径过滤
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# 限制核心转储
fs.suid_dumpable = 0

# 随机化虚拟地址空间
kernel.randomize_va_space = 2

# 应用配置
sysctl -p /etc/sysctl.d/99-security.conf

6.2 禁用不需要的内核模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# /etc/modprobe.d/blacklist.conf
blacklist cramfs
blacklist freevxfs
blacklist jffs2
blacklist hfs
blacklist hfsplus
blacklist squashfs
blacklist udf
blacklist bluetooth
blacklist bnep
blacklist btusb

# 更新 initramfs
update-initramfs -u

七、服务与端口加固

7.1 禁用不必要的服务

1
2
3
4
5
6
7
8
9
# 查看运行的服务
systemctl list-units --type=service --state=running

# 禁用不需要的服务
systemctl disable --now cups
systemctl disable --now bluetooth
systemctl disable --now avahi-daemon
systemctl disable --now nfs-server
systemctl disable --now rpcbind

7.2 检查监听端口

1
2
3
4
5
6
7
8
# 查看监听端口
ss -tlnp
netstat -tlnp

# 只保留必要端口
# SSH: 2222
# Web: 80, 443
# DB: 3306 (仅内网)

7.3 隐藏服务版本信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Nginx
# /etc/nginx/nginx.conf
http {
server_tokens off;
}

# Apache
# /etc/apache2/conf-available/security.conf
ServerTokens Prod
ServerSignature Off

# SSH
# /etc/ssh/sshd_config
DebianBanner no

八、日志与审计

8.1 配置 rsyslog 远程日志

1
2
3
4
5
6
7
8
9
10
11
12
# /etc/rsyslog.conf
# 客户端配置
*.* @@192.168.1.100:514

# 服务端配置
module(load="imtcp")
input(type="imtcp" port="514")

$template RemoteLog,"/var/log/remote/%HOSTNAME%/%PROGRAMNAME%.log"
*.* ?RemoteLog

systemctl restart rsyslog

8.2 安装审计工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 安装 auditd
apt-get install -y auditd audispd-plugins

# 配置审计规则
# /etc/audit/rules.d/audit.rules
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k sudoers
-w /etc/ssh/sshd_config -p wa -k sshd
-w /var/log/ -p wa -k logfiles

# 查看审计日志
ausearch -k identity
aureport --file

8.3 日志轮转配置

1
2
3
4
5
6
7
8
9
10
11
12
# /etc/logrotate.d/syslog
/var/log/syslog
/var/log/auth.log
{
rotate 12
weekly
compress
delaycompress
missingok
notifempty
create 640 syslog adm
}

九、文件与目录权限

9.1 关键文件权限检查

1
2
3
4
5
6
7
8
9
10
11
12
13
# 设置关键文件权限
chmod 644 /etc/passwd
chmod 644 /etc/group
chmod 600 /etc/shadow
chmod 600 /etc/gshadow
chmod 644 /etc/hosts.allow
chmod 644 /etc/hosts.deny
chmod 600 /etc/ssh/sshd_config
chmod 600 ~/.ssh/authorized_keys

# 查找 SUID/SGID 文件
find / -perm -4000 -type f 2>/dev/null
find / -perm -2000 -type f 2>/dev/null

9.2 限制用户访问

1
2
3
4
5
6
7
8
# 设置 umask
echo "umask 027" >> /etc/profile

# 限制 su 访问
echo "auth required pam_wheel.so use_uid" >> /etc/pam.d/su

# 配置 secure_path
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

十、安全监控与告警

10.1 安装入侵检测系统

1
2
3
4
5
6
7
8
9
# 安装 AIDE
apt-get install -y aide

# 初始化数据库
aide --init
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# 配置定时检查
echo "0 5 * * * root /usr/bin/aide --check" >> /etc/crontab

10.2 配置登录监控

1
2
3
4
5
6
7
# /etc/profile.d/login-monitor.sh
#!/bin/bash
if [ -n "$SSH_CONNECTION" ]; then
echo "Login: $(whoami) from $(echo $SSH_CONNECTION | awk '{print $1}') at $(date)" >> /var/log/login-monitor.log
fi

chmod +x /etc/profile.d/login-monitor.sh

10.3 文件完整性监控

1
2
3
4
5
6
7
8
# 使用 tripwire
apt-get install -y tripwire

# 初始化策略
twprint --print-policy --txt

# 更新数据库
tripwire --init

十一、备份与恢复

11.1 配置关键数据备份

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# /etc/cron.daily/backup-security
#!/bin/bash
BACKUP_DIR="/backup/security"
DATE=$(date +%Y%m%d)

mkdir -p $BACKUP_DIR

# 备份关键配置
tar czf $BACKUP_DIR/etc-config-$DATE.tar.gz /etc/ssh /etc/sudoers.d /etc/passwd /etc/shadow /etc/group

# 备份 iptables 规则
iptables-save > $BACKUP_DIR/iptables-$DATE.rules

# 保留最近 7 天
find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete

# 加密备份(可选)
# gpg --symmetric --cipher-algo AES256 $BACKUP_DIR/etc-config-$DATE.tar.gz

11.2 测试恢复流程

1
2
3
4
5
# 定期测试恢复
# 1. 创建测试环境
# 2. 恢复备份
# 3. 验证服务正常
# 4. 记录恢复时间

十二、安全检查清单

12.1 日常检查项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# security-check.sh

echo "=== 安全检查报告 ==="
echo "日期:$(date)"

echo -e "\n[1] 检查失败登录"
grep "Failed password" /var/log/auth.log | tail -10

echo -e "\n[2] 检查 sudo 使用"
grep "sudo:" /var/log/auth.log | tail -10

echo -e "\n[3] 检查异常连接"
ss -tunap | grep ESTABLISHED

echo -e "\n[4] 检查磁盘使用"
df -h

echo -e "\n[5] 检查系统负载"
uptime

12.2 定期审计项目

检查项 频率 工具
系统更新 每周 apt/yum
日志审计 每日 logwatch
漏洞扫描 每月 lynis
权限审查 每月 find
备份验证 每周 手动测试

十三、应急响应

13.1 发现入侵后的处理流程

  1. 隔离系统:断开网络连接或防火墙隔离
  2. 保存证据:备份日志、内存镜像、进程信息
  3. 分析入侵:检查日志、查找后门、确定入侵途径
  4. 清除威胁:删除恶意文件、重置密码、修复漏洞
  5. 恢复系统:从干净备份恢复或重建系统
  6. 复盘总结:记录事件、更新安全策略

13.2 应急命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 查看当前登录用户
who
w
last

# 查看进程
ps auxf
top

# 查看网络连接
netstat -tunap
lsof -i

# 查看定时任务
crontab -l
cat /etc/crontab
ls -la /etc/cron.*

# 检查启动项
systemctl list-unit-files --state=enabled

十四、总结

服务器安全加固是一个持续的过程,需要:

  1. 定期更新:保持系统和软件最新
  2. 最小权限:只开放必要的服务和端口
  3. 多层防护:防火墙 + 入侵检测 + 审计日志
  4. 备份验证:定期测试备份恢复流程
  5. 安全意识:培训运维人员,建立安全规范

文档版本: v1.0
最后更新: 2026-03-06
适用系统: Ubuntu 22.04 / CentOS 7.9+