为了避免浪费宝贵时间请先验证
SSH 用户的主目录或
~/.ssh目录具有组写入权限。主目录应该只能由用户或所有者写入,~/.ssh权限应设置为 700,authorized_keys文件权限应设置为 600
公私钥创建
一直使用阿里云的Centos做服务器,最近在服务器上新建了一个用户,为了免去每次SSH都要输入密码的麻烦,我通过 下面的命令为该用户建立SSH公钥/私钥 登录认证, 本来是个很简单的操作,没想到竟然出现了问题!
// 客户端的linux机上$ ssh-keygen$ scp ~/.ssh/id_rsa.pub username@ip:~// 服务器上用aaa用户登录$ cat ~/id_rsa.pub >> ~/.ssh/authorized_keys
配置完毕后,在客户机上通过ssh登录,竟然还提示要输入密码!? 因为其实以前已经配置过好几次SSH公钥登录,从来没有出现过问题。这一次很意外。反复检查了几遍也没有找到原因。
客户端纠错
通过下面的debug方式得到信息如下:
ssh -v username@ip
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017# 读取配置debug1: Reading configuration data /root/.ssh/config...# 建立连接debug1: Connecting to 10.25.80.75 [10.25.80.75] port 22.debug1: Connection established.# 校验debug1: kex: algorithm: curve25519-sha256debug1: Trying private key: /root/.ssh/8xdebug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password# 校验失败, 走密码验证debug1: Next authentication method: password
通过上述的SSH -v 命令可以看到,客户机已经把私钥发送到服务器端,但在服务器端没有验证成功,所以问题应该位于服务器端。
服务端纠错
通用方式
对于无法使用客户端纠错的场景, 只能使用服务端日志, 在开启日志之前我们需要设置 Log 级别为 DEBUG, 方便查找问题
编辑配置文件
# vim /etc/ssh/sshd_config
启动 Debug
- # LogLevel INFO+ LogLevel DEBUG
重启服务
# systemctl restart sshd
这里需要通过查日志的手法来查看下登录的问题, CentOS 的SSH登录信息记录在 /var/log/secure文件中,找到下面的信息:
[root@server-8x ssh]# tail -20f /var/log/secure...Nov 23 20:56:25 iZ28gwro9uqZ sshd[21359]: reprocess config line 50: Deprecated option RSAAuthenticationNov 23 20:57:56 iZ28gwro9uqZ sshd[23341]: Authentication refused: bad ownership or modes for directory /root/.sshNov 23 21:09:10 iZ28gwro9uqZ sshd[10047]: Connection closed by 10.80.184.166 port 50638 [preauth]...
服务器端的错误: bad ownership or modes for directory…
对于这个存放公钥的目录的权限要求是只有本人才可以读写的,应该是700!否则,缺省的情况下会拒绝进行authentication. 改成700后,再次SSH登录,问题解决!
通过此事需要注意:
- 仔细看log是发现问题原因的很重要的手段
- SSH公钥认证必须设置合适的权限 :
.ssh目录的权限为 700,authorized_keys的权限为 600
Jenkins 的纠错过程记录
错误信息
[05/06/22 20:08:14] [SSH] Opening SSH connection to {ip}:{port}.[05/06/22 20:08:14] [SSH] SSH host key matches key seen previously for this host. Connection will be allowed.ERROR: Server rejected the 1 private key(s) for project (credentialId:app-project/method:publickey)[05/06/22 20:08:14] [SSH] Authentication failed.Authentication failed.[05/06/22 20:08:14] Launch failed - cleaning up connection[05/06/22 20:08:14] [SSH] Connection closed.
日志中
...sshd[837537]: Authentication refused: bad ownership or modes for directory /home/project/.ssh......May 6 20:21:17 iZbp1fj2qclam9f3xd1clmZ sshd[838775]: debug1: trying public key file /home/project/.ssh/authorized_keysMay 6 20:21:17 iZbp1fj2qclam9f3xd1clmZ sshd[838775]: debug1: Could not open authorized keys '/home/project/.ssh/authorized_keys': Permission denied...
