SSH 公钥认证 - 仅在物理登录后有效

cai*_*spb 5 ssh sshd public-key-authentication

我正在尝试使用公钥身份验证通过 SSH 连接到我的 ubuntu 服务器。由于某些原因,我收到“权限被拒绝(公钥)”。在客户端,每当我执行

ssh -i ~/.ssh/id_rsa <username>@<ip> -p <port>.

我服务器上的 auth.log 有以下输出:

sshd[1425]: Connection closed by <client-ip> [preauth]

但是,一旦我使用相同的用户名在我的服务器上实际登录,来自我的客户端的以下 ssh 连接就会成功。但是,一旦我以物理方式注销,来自客户端的下一个 ssh 会话就会失败。

/etc/ssh/sshd_config

# What ports, IPs and protocols we listen for
Port <port>
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no

PermitEmptyPasswords no
ChallengeResponseAuthentication no

PasswordAuthentication no

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

UsePAM no

ClientAliveInterval 30
ClientAliveCountMax 99999    
Run Code Online (Sandbox Code Playgroud)

任何线索为什么会发生这种情况?或者你对安全有什么建议?谢谢!

phe*_*mer 12

正如评论中提到的,您使用的是加密的主目录,并且可能使用pam_mount来安装它。
pam_mount 使用登录时获取的密码挂载分区。由于您尝试通过 ssh 公钥登录,因此存在两个问题:

  1. 在公钥身份验证期间没有发送密码,因此它无法使用它挂载您的主目录。
  2. 使用pam_mount时,您的主目录登录挂载,但sshd需要登录获取您的authorized_keys文件,因此未挂载。

这些问题中的任何一个都足以阻止它工作。

唯一的解决方案是将您的公钥从主目录中取出。这实际上相当简单。

首先将authorized_keys文件从主目录中复制出来:

cp -a /home/$USER/.ssh/authorized_keys /home/$USER-authorized_keys
Run Code Online (Sandbox Code Playgroud)

然后sshd通过添加以下内容来告诉使用该文件/etc/ssh/sshd_config(如果存在,请替换现有条目):

AuthorizedKeysFile .ssh/authorized_keys /home/%u-authorized_keys
Run Code Online (Sandbox Code Playgroud)

并弹跳sshd

但是请注意,这不会挂载您的主目录。您的主目录仍然需要您的密码才能解密。根据您配置 pam_mount 的方式,它可能会提示您输入密码,或者它可能只是将您放入一个未挂载 home 的 shell。