Oamc

SSH 安全加固

本页目录

场景

服务器要放到内网以外,或者安全扫描报了「SSH 允许密码登录 / 允许 root 登录」。

前置条件

  • 已经能用密钥登录,并且确认密钥可用
  • 有带外或控制台兜底(改错就进不去)
  • 记下当前会话别断

配置

# 1. 客户端生成密钥(在你自己电脑上做)
ssh-keygen -t ed25519 -C "ops@laptop"
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# 2. 服务端配置
cat >/etc/ssh/sshd_config.d/99-hardening.conf <<'EOF'
Port 22
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
PermitEmptyPasswords no
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers deploy ops
EOF

# 3. 检查并重启
sshd -t
systemctl restart sshd

先保持一个已登录的会话不要退出,新开一个窗口验证能连上再关旧的。

验证

ssh -p 22 deploy@server        # 新窗口
ss -lntp | grep sshd
journalctl -u sshd -n 50 --no-pager

回滚

连不上时用控制台 / 带外进去:

rm /etc/ssh/sshd_config.d/99-hardening.conf
systemctl restart sshd

坑

  • 改完直接重启 sshd 又没验证,是把自己锁在门外最常见的方式。
  • 家目录权限太松(777)会导致密钥登录失败,chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys。
  • SELinux 开启时,authorized_keys 的上下文不对也会失败,restorecon -Rv ~/.ssh。
  • 改端口后记得同步防火墙和云安全组。
  • AllowUsers 写错用户名,全员被拒。
  • 用 sshd -t 先测语法,别等 restart 失败才发现。