来访~105152 文章~106 评论~25
2023年6月16日 作者 张临志

ubuntu22.04 服务器 SSH 密钥登录失败

1. 背景介绍

SSH密钥登录,是将SSH公钥写入服务端的 ~/.ssh/authorized_keys文件中。

今天装了ubuntu22.04的系统,按照以往操作,在服务端配置了SSH公钥之后,发现竟然无法登录。

2. 问题定位

首先查看OpenSSH版本:

$ ssh -V
OpenSSH_8.9p1 Ubuntu-3ubuntu0.1, OpenSSL 3.0.2 15 Mar 2022

查看 /var/log/auth.log 文件,发现有如下错误信息:

sshd[2648]: userauth_pubkey: key type ssh-rsa not in PubkeyAcceptedAlgorithms [preauth]

通过错误信息来看,填入authorized_keys文件的SSH公钥类型是 ssh-rsa 类型,属于不支持的公钥类型。应该是SSH版本高版本中增加该限制。

查看支持的公钥类型:

$ sudo sshd -T | egrep "pubkey"
pubkeyauthentication yes
pubkeyacceptedalgorithms ssh-ed25519-cert-v01@openssh.com,ecdsa-sha2-nistp256-cert-v01@openssh.com,ecdsa-sha2-nistp384-cert-v01@openssh.com,ecdsa-sha2-nistp521-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,sk-ecdsa-sha2-nistp256-cert-v01@openssh.com,rsa-sha2-512-cert-v01@openssh.com,rsa-sha2-256-cert-v01@openssh.com,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,sk-ssh-ed25519@openssh.com,sk-ecdsa-sha2-nistp256@openssh.com,rsa-sha2-512,rsa-sha2-256
pubkeyauthoptions none

3. 解决方法

知道了问题原因,问题就好解决了。

3.1 方案1

使用受支持的公钥类型,重新生成OpenSSH公私钥,比如使用ed25519

使用ssh-keygen命令生成ed25519公私钥方法如下:

$ ssh-keygen -t ed25519 # 默认生成到~/.ssh/ 目录下,默认文件名为:id_ed25519 和 id_ed25519.pub
$ ssh-keygen -t ed25519 -f test # 生成文件到当前目录,文件名为:test 和 test.pub

3.2 方案2

修改sshd配置文件/etc/ssh/sshd_config,使得pubkeyacceptedalgorithms支持ssh-rsa公钥类型。

修改方法:在/etc/ssh/sshd_config文件末尾增加一行PubkeyAcceptedAlgorithms +ssh-rsa

修改完/etc/ssh/sshd_config配置文件后,需要重启sshd服务,执行 service sshd restart