最近一开发同事找我帮忙,说他在一台服务器上添加了自己电脑的ssh公钥,但是登录服务器的时候仍然要求输入密码。刚开始我以为是他添加ssh公钥的时候粘贴有问题,比如,ssh公钥本来应该是一行,结果粘贴成了多行,或者是粘贴出现了其他问题。经过我重新添加一次公钥后,仍然让输入密码,我就开始怀疑是~/.ssh/authorized_keys文件权限的问题。再通过/var/log/secure查看日志,提示authorized_keys的权限不是600。然后我再查看authorized_keys这个文件的权限被修改成了664,再查看/etc/ssh/sshd_config文件中设置有strictmodes yes 难怪添加了公钥仍然被要求输入密码。这里提一点,如果自己能够看懂英文说明的话,出了问题,可以首先看看相关服务的man手册,软件自身的说明文档才是最权威,最原始的,其他的资料都只是参考而已,参杂着各种片面的理解。
通过man ssh查看ssh相关的说明
the file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. when the user logs in, the ssh program tells the server which key pair it would like to use for authentication. the client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account.
~/.ssh/authorized_keys
lists the public keys (rsa/dsa) that can be used for logging in as this user. the format of this file is described in the sshd(8) manual page. this file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others。if this file, the ~/.ssh directory, or the user’s home directory are writable by other users,then the file could be modified or replaced by unauthorized users. in this case, sshd will not allow it to be used unless the strictmodes option has been set to “no”.
查看man sshd_config
strictmodes
specifies whether sshd(8) should check file modes and ownership of the user’s files and home directory before accepting login. this is normally desirable because novices sometimes accidentally leave their directory or files world-writable. the default is “yes”.
通过man手册可以知道系统默认~/.ssh/authorized_keys这个文件的权限应该是owner具有读写权限,其他的都不能读写,即权限应该是600.如果在/etc/ssh/sshd_config 中设置了strictmodes yes 则sshd会去检查~/.ssh/authorized_keys这个文件的文件权限。如果~/.ssh目录和owner的home目录可以被其他用户写,那也会出现问题。