SSH 安全加固

SSH 服务端安全配置最佳实践,防止暴力破解和未授权访问

语法

# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
Port 2222

参数

参数说明示例级别
PermitRootLogin 是否允许 root 直接登录 PermitRootLogin no 常用
PasswordAuthentication 是否允许密码认证 PasswordAuthentication no 常用
Port SSH 监听端口 Port 2222 常用
AllowUsers 允许登录的用户白名单 AllowUsers deploy admin 常用
MaxAuthTries 最大认证尝试次数 MaxAuthTries 3 常用
LoginGraceTime 认证超时时间 LoginGraceTime 30 进阶

示例

基本安全加固配置

# /etc/ssh/sshd_config
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 30
AllowUsers deploy admin
修改后执行 systemctl restart sshd 生效

限制 SSH 访问来源

# /etc/ssh/sshd_config
AllowUsers deploy@192.168.1.*
AllowUsers admin@10.0.0.0/24
只允许特定 IP 段的用户登录

禁用不安全的认证方式

# /etc/ssh/sshd_config
ChallengeResponseAuthentication no
KerberosAuthentication no
GSSAPIAuthentication no
X11Forwarding no
关闭不需要的认证方式和功能减少攻击面

配合 fail2ban 防暴力破解

# /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 3600
findtime = 600
10 分钟内失败 3 次则封禁 IP 1 小时

常见错误

修改配置后无法登录 修改前保持一个已有连接不断开,用它来回滚配置。确保至少有一个用户和密钥可以登录
sshd: no hostkeys available 主机密钥丢失,用 ssh-keygen -A 重新生成所有类型的主机密钥

技巧

相关命令