【安全与故障排查】02-SSH安全最佳实践:禁密码+密钥+端口+防暴破
SSH 安全最佳实践:禁密码 + 密钥 + 端口 + 防暴破
专栏:安全 & 故障排查
难度:入门
标签:SSH安全密钥登录fail2ban服务器安全
前言
SSH 是服务器的大门,是攻击者最常盯着的目标。本文从密钥配置到 fail2ban 防暴破,建立一套完整的 SSH 安全防护体系。
一、生成并配置 SSH 密钥对
# 本地生成ED25519密钥对(比RSA更安全,更短)ssh-keygen-ted25519-C"your_email@example.com"# 保存到:~/.ssh/id_ed25519(私钥)和 ~/.ssh/id_ed25519.pub(公钥)# 将公钥上传到服务器ssh-copy-id-i~/.ssh/id_ed25519.pub user@server_ip# 或手动复制cat~/.ssh/id_ed25519.pub>>~/.ssh/authorized_keyschmod600~/.ssh/authorized_keyschmod700~/.ssh二、sshd_config 完整安全配置
cat>/etc/ssh/sshd_config<<'EOF' # 监听端口(改掉22) Port 22022 # 只监听IPv4(视环境调整) AddressFamily inet # 认证配置 PermitRootLogin no # 禁止root登录 PasswordAuthentication no # 禁止密码登录 PubkeyAuthentication yes # 启用密钥登录 AuthorizedKeysFile .ssh/authorized_keys # 只允许特定用户SSH AllowUsers appuser devuser # 白名单,只允许这些用户 # 安全加固 MaxAuthTries 3 # 最多3次认证尝试 MaxSessions 10 # 最多10个会话 LoginGraceTime 30 # 30秒内必须完成认证 ClientAliveInterval 300 # 空闲300秒发送keepalive ClientAliveCountMax 2 # 2次无响应后断开 TCPKeepAlive yes # 禁用危险功能 X11Forwarding no AllowAgentForwarding no AllowTcpForwarding no PermitTunnel no # 加密套件(只用强加密) KexAlgorithms curve25519-sha256,diffie-hellman-group16-sha512 Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com MACs hmac-sha2-512,hmac-sha2-256 # 日志级别 LogLevel VERBOSE # Banner Banner /etc/ssh/banner.txt EOF# 重启SSH(务必先测试配置!)sshd-t&&systemctl restart sshd三、SSH 多因素认证(2FA)
# 安装Google Authenticatoryuminstall-ygoogle-authenticator# CentOSaptinstall-ylibpam-google-authenticator# Ubuntu# 为用户配置2FAgoogle-authenticator# 按提示扫描二维码# 编辑 /etc/pam.d/sshd,添加auth required pam_google_authenticator.so# sshd_config中开启ChallengeResponseAuthenticationyes四、Fail2ban 防暴力破解
# 安装yuminstall-yfail2ban# CentOSaptinstall-yfail2ban# Ubuntu# 配置 /etc/fail2ban/jail.localcat>/etc/fail2ban/jail.local<<'EOF' [DEFAULT] bantime = 3600 # 封禁1小时 findtime = 600 # 10分钟内 maxretry = 3 # 失败3次触发封禁 [sshd] enabled = true port = 22022 # 和SSH端口一致 logpath = %(sshd_log)s backend = %(sshd_backend)s # 永久封禁IP(需要白名单) [sshd-permanent] enabled = true filter = sshd bantime = -1 # -1 = 永久 maxretry = 5 EOFsystemctlenable--nowfail2ban# 查看封禁列表fail2ban-client status sshd# 手动解封fail2ban-clientsetsshd unbanip1.2.3.4五、SSH 跳板机配置(最佳实践)
外网 → 跳板机(Bastion Host)→ 内网服务器 好处: 1. 内网服务器不对外暴露SSH端口 2. 所有登录行为集中审计 3. 密钥只需要维护一份# ~/.ssh/config(本地配置,透明跳板)Host bastion HostName bastion.example.com Port22022User devuser IdentityFile ~/.ssh/id_ed25519 Host10.0.0.* User appuser IdentityFile ~/.ssh/id_ed25519 ProxyJump bastion# 通过bastion跳转结语:SSH 安全的核心三件套:密钥替换密码、fail2ban 防暴破、跳板机控制入口。三个全上,SSH 入侵风险降低99%。
