【安全与故障排查】02-SSH安全最佳实践:禁密码+密钥+端口+防暴破
SSH 安全最佳实践禁密码 密钥 端口 防暴破专栏安全 故障排查难度入门标签SSH安全密钥登录fail2ban服务器安全前言SSH 是服务器的大门是攻击者最常盯着的目标。本文从密钥配置到 fail2ban 防暴破建立一套完整的 SSH 安全防护体系。一、生成并配置 SSH 密钥对# 本地生成ED25519密钥对比RSA更安全更短ssh-keygen-ted25519-Cyour_emailexample.com# 保存到~/.ssh/id_ed25519私钥和 ~/.ssh/id_ed25519.pub公钥# 将公钥上传到服务器ssh-copy-id-i~/.ssh/id_ed25519.pub userserver_ip# 或手动复制cat~/.ssh/id_ed25519.pub~/.ssh/authorized_keyschmod600~/.ssh/authorized_keyschmod700~/.ssh二、sshd_config 完整安全配置cat/etc/ssh/sshd_configEOF # 监听端口改掉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-gcmopenssh.com,aes128-gcmopenssh.com MACs hmac-sha2-512,hmac-sha2-256 # 日志级别 LogLevel VERBOSE # Banner Banner /etc/ssh/banner.txt EOF# 重启SSH务必先测试配置sshd-tsystemctl 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.localEOF [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%。