提交工单

香港服务器安全加固终极指南:CIS Benchmark实施 + 自动化合规检查完整方案

文档更新于

安全加固不应该是「感觉差不多了」,而应该有明确的评分标准。CIS Benchmark(互联网安全中心基准)是行业最权威的 Linux 安全配置指南,每一条建议都有明确的理由和检查方法。本文将 CIS Ubuntu 22.04 Benchmark 的核心要求转化为可直接执行的操作,并用 Lynis 自动化扫描工具评估当前安全评分,让香港服务器的安全状态清晰可量化。


一、Lynis 安全评分(了解当前状态)

<code"># 安装 Lynis(开源安全审计工具)
apt install -y lynis

# 执行完整安全审计(约5分钟)
lynis audit system

# 查看审计摘要
grep -E "Hardening index|Warning|Suggestion" /var/log/lynis.log | tail -30

# 典型输出:
# Hardening index : 62 [############        ]
# Tests performed : 258
# Plugins enabled : 2
#
# 建议加固项(Suggestions):
# * Consider disabling IPv6 [NETW-3015]
# * Enable audit logging [ACCT-9634]
# * Configure password hashing method [AUTH-9230]

# 目标:将 Hardening index 提升到 80+

二、用户账号安全(CIS Section 5)

<code"># ── 密码策略 ──
# /etc/login.defs

# 密码有效期
PASS_MAX_DAYS   90      # 最长90天必须更换
PASS_MIN_DAYS   7       # 更换后至少7天才能再次更换
PASS_WARN_AGE   14      # 到期前14天开始提醒

# 修改已有用户的密码有效期
chage --maxdays 90 --mindays 7 --warndays 14 alice
chage -l alice   # 查看密码策略
<code"># ── 密码复杂度(PAM 模块)──
apt install -y libpam-pwquality

# /etc/security/pwquality.conf
minlen = 14           # 最短14字符
minclass = 4          # 必须包含大写/小写/数字/特殊字符
maxrepeat = 3         # 连续相同字符不超过3个
maxclassrepeat = 3    # 同类字符连续不超过3个
dcredit = -1          # 至少1个数字
ucredit = -1          # 至少1个大写字母
lcredit = -1          # 至少1个小写字母
ocredit = -1          # 至少1个特殊字符
difok = 5             # 与旧密码至少有5个字符不同
<code"># ── 锁定策略(连续失败后锁定)──
# /etc/pam.d/common-auth 添加(在 pam_unix.so 之前)
auth required pam_tally2.so audit silent deny=5 unlock_time=900
# 5次失败锁定15分钟

# 查看锁定状态
pam_tally2 --user alice

# 手动解锁
pam_tally2 --user alice --reset
<code"># ── 禁用不必要的系统账号 ──
# 检查所有可登录账号
awk -F: '$7 != "/sbin/nologin" && $7 != "/bin/false" && $7 != "" {print $1, $7}' /etc/passwd

# 禁用系统服务账号(不应该有 shell)
usermod -s /sbin/nologin daemon
usermod -s /sbin/nologin bin
usermod -s /sbin/nologin games
usermod -s /sbin/nologin lp
usermod -s /sbin/nologin news
usermod -s /sbin/nologin uucp

# 锁定 root 密码登录(只允许 SSH Key 登录)
passwd -l root

三、文件系统安全(CIS Section 1)

<code"># ── 关键文件权限加固 ──

# /etc/passwd 应只有 root 可写
chmod 644 /etc/passwd
chown root:root /etc/passwd

# /etc/shadow 只有 root 可读(存储密码哈希,极其敏感)
chmod 000 /etc/shadow
chown root:shadow /etc/shadow

# /etc/group
chmod 644 /etc/group
chown root:root /etc/group

# SSH 配置文件
chmod 600 /etc/ssh/sshd_config
chown root:root /etc/ssh/sshd_config

# 检查 SUID/SGID 文件(潜在提权路径)
find / -type f \( -perm -4000 -o -perm -2000 \) -ls 2>/dev/null | \
  grep -v proc | tee /var/log/suid-files.txt

# 对比上次检查(发现新增 SUID 文件)
diff /var/log/suid-files-baseline.txt /var/log/suid-files.txt
<code"># ── /tmp 目录挂载选项(nodev/nosuid/noexec)──
# 防止 /tmp 被用于执行恶意代码

# /etc/fstab 添加(如果 /tmp 是单独分区)
# tmpfs /tmp tmpfs defaults,rw,nosuid,nodev,noexec,relatime 0 0

# 如果 /tmp 不是单独分区(更常见的 VPS 场景)
# 创建内存文件系统绑定挂载
cat >> /etc/fstab << 'EOF'
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0
tmpfs /var/tmp tmpfs defaults,noexec,nosuid,nodev 0 0
EOF

mount -o remount /tmp
mount -o remount /var/tmp

四、网络安全加固(CIS Section 3)

<code"># /etc/sysctl.d/99-security.conf
# 网络层安全参数

# ── 禁止 IP 欺骗 ──
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# ── 禁止接受 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
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0

# ── 禁止发送 ICMP 重定向(不转发路由)──
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# ── 禁止转发数据包(非路由器)──
net.ipv4.ip_forward = 0     # 如果不需要 Docker/WireGuard 等设置为0
net.ipv6.conf.all.forwarding = 0

# ── 开启 SYN Flood 防护 ──
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 4096

# ── 记录可疑数据包 ──
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# ── 忽略广播 ping(防止 Smurf 攻击)──
net.ipv4.icmp_echo_ignore_broadcasts = 1

# ── 禁止接受源路由数据包 ──
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0

sysctl -p /etc/sysctl.d/99-security.conf

五、服务最小化(CIS Section 2)

<code"># 禁用不必要的服务(攻击面最小化)
# 检查所有正在运行的服务
systemctl list-units --type=service --state=running

# 禁用常见的不必要服务
DISABLE_SERVICES=(
    "cups"           # 打印服务(服务器不需要)
    "avahi-daemon"   # mDNS/Bonjour(服务器不需要)
    "bluetooth"      # 蓝牙(服务器不需要)
    "rsync"          # 如果不用 rsync 服务端模式
    "rpcbind"        # NFS 相关(如果不用 NFS)
    "nfs-server"     # NFS 服务器
    "smbd"           # Samba(如果不用)
    "snapd"          # Snap 包管理(可选)
)

for service in "${DISABLE_SERVICES[@]}"; do
    if systemctl is-active --quiet "$service"; then
        systemctl disable --now "$service"
        echo "已禁用: $service"
    fi
done

六、SSH 加固(CIS Section 5.2,补充前面 SSH 文章)

<code"># /etc/ssh/sshd_config 安全加固(完整版)

# 禁用旧的、不安全的功能
Protocol 2
IgnoreRhosts yes
HostbasedAuthentication no
PermitEmptyPasswords no
PermitUserEnvironment no      # 禁止用户通过 ~/.ssh/environment 设置环境变量
Compression delayed           # 仅在认证后允许压缩

# 登录超时
LoginGraceTime 60             # 60秒内必须完成认证
ClientAliveInterval 300
ClientAliveCountMax 0         # 不发送心跳(0次后断开 = 不依赖心跳)

# X11 转发
X11Forwarding no              # 服务器不需要 X11

# 允许的认证方式(严格模式:只允许公钥)
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no

# 允许的加密套件(仅安全算法)
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256

sshd -t    # 测试配置
systemctl reload sshd

七、内核加固(CIS Section 1.5)

<code"># 内核模块黑名单(禁用不需要的内核模块)
# /etc/modprobe.d/blacklist-security.conf

# 禁用文件系统(不使用的文件系统类型是攻击面)
install cramfs /bin/true
install freevxfs /bin/true
install jffs2 /bin/true
install hfs /bin/true
install hfsplus /bin/true
install squashfs /bin/true
install udf /bin/true

# 禁用网络协议(只需要 IPv4/IPv6)
install dccp /bin/true      # 数据报拥塞控制协议(很少用)
install sctp /bin/true      # 流控制传输协议
install rds /bin/true       # 可靠数据报套接字
install tipc /bin/true      # 透明进程间通信

# 应用黑名单
depmod -a
modprobe -r cramfs freevxfs 2>/dev/null || true

八、自动化合规检查脚本

<code"># /usr/local/bin/security-audit.sh
#!/bin/bash
# 定期安全合规检查脚本

FEISHU="https://open.feishu.cn/open-apis/bot/v2/hook/your_webhook"
REPORT="/tmp/security-audit-$(date +%Y%m%d).txt"

echo "=== 安全合规检查报告 $(date) ===" > "$REPORT"
echo "服务器:$(hostname)" >> "$REPORT"

# Lynis 评分
echo "" >> "$REPORT"
echo "--- Lynis 安全评分 ---" >> "$REPORT"
lynis audit system --quick 2>/dev/null | grep "Hardening index" >> "$REPORT"

# 检查关键配置
echo "" >> "$REPORT"
echo "--- 关键配置检查 ---" >> "$REPORT"

# SSH 密码认证
SSH_PASS=$(sshd -T | grep "passwordauthentication" | awk '{print $2}')
echo "SSH密码认证:$SSH_PASS(应为no)" >> "$REPORT"

# Root 密码
ROOT_PASS=$(passwd -S root | awk '{print $2}')
echo "Root密码状态:$ROOT_PASS(应为L=锁定)" >> "$REPORT"

# 开放端口
echo "开放端口:" >> "$REPORT"
ss -tlnp | grep LISTEN >> "$REPORT"

# 发送飞书报告
LYNIS_SCORE=$(lynis audit system --quick 2>/dev/null | grep "Hardening index" | grep -oP '\d+')
COLOR="green"
[[ "$LYNIS_SCORE" -lt 70 ]] && COLOR="yellow"
[[ "$LYNIS_SCORE" -lt 60 ]] && COLOR="red"

curl -s -X POST "$FEISHU" \
  -H "Content-Type: application/json" \
  -d "{\"msg_type\":\"text\",\"content\":{\"text\":\"🔐 安全审计报告\n服务器:$(hostname)\n安全评分:$LYNIS_SCORE/100\n时间:$(date)\n\n$(cat $REPORT | head -30)\"}}"

chmod +x /usr/local/bin/security-audit.sh

# 每周一早8点执行
echo "0 8 * * 1 root /usr/local/bin/security-audit.sh" >> /etc/crontab

九、加固后的安全评分变化

加固项 加固前分值 加固后分值 提升
密码策略(minlen/复杂度) 45 78 +33
SSH 加固(密钥认证/算法) 52 88 +36
网络参数(sysctl 加固) 50 85 +35
服务最小化 60 82 +22
auditd 审计(上一篇文章) 30 80 +50
综合 Lynis 评分 52 81 +29

十、总结

CIS Benchmark 不是一次性工作,而是持续的安全维护流程:Lynis 定期评分让安全状态可量化可追踪,每次系统更新或配置变更后重新评估,确保安全基线不退化。香港服务器的网络暴露面比内网服务器更大,将 Lynis 评分维持在 80 分以上,配合本文章系列中的 Fail2ban、auditd、AIDE 等多层防御,构建真正的纵深防御体系。

需要服务器?

香港 / 美国 / 日本服务器与 VPS,工程师 7×24 在线,工单平均 10 分钟内响应。