SSH 安全加固
SSH 密钥认证
生成密钥对
# Ed25519(推荐,更短更安全)
ssh-keygen -t ed25519 -C "user@example.com"
# RSA(兼容老系统,4096 位起步)
ssh-keygen -t rsa -b 4096
# 复制公钥到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
sshd 加固配置
/etc/ssh/sshd_config
# 禁用密码登录(仅允许密钥)
PasswordAuthentication no
PubkeyAuthentication yes
# 禁止 root 远程登录
PermitRootLogin no
# 修改默认端口
Port 22222
# 限制登录用户
AllowUsers deploy admin
# 或限制用户组
AllowGroups ssh-users
# 限制认证尝试次数
MaxAuthTries 3
LoginGraceTime 30
# 禁用空密码
PermitEmptyPasswords no
# 禁用 X11 转发
X11Forwarding no
# 空闲超时断开(300 秒无活动 × 3 次 = 15 分钟)
ClientAliveInterval 300
ClientAliveCountMax 3
# 仅允许 SSH 协议 2
Protocol 2
# 重载配置
systemctl reload sshd
危险
修改 SSH 配置前,确保有另一个终端保持连接或有带外管理(IPMI/控制台),避免配置错误导致锁定。
fail2ban 防暴力破解
/etc/fail2ban/jail.local
[sshd]
enabled = true
port = 22222
filter = sshd
logpath = /var/log/auth.log
maxretry = 5 # 5 次失败后封禁
bantime = 3600 # 封禁 1 小时
findtime = 600 # 10 分钟内超过阈值
systemctl enable --now fail2ban
fail2ban-client status sshd # 查看封禁状态
fail2ban-client set sshd unbanip 1.2.3.4 # 解封
常见面试问题
Q1: SSH 安全加固的关键步骤?
答案:
- 密钥替代密码:
PasswordAuthentication no - 禁止 root 登录:
PermitRootLogin no - 修改默认端口:减少自动化扫描攻击
- fail2ban:自动封禁暴力破解 IP
- 限制来源 IP:防火墙或
AllowUsers user@10.0.0.0/8 - MFA 双因子:pam_google_authenticator