解决 Win11 的 OpenSSH 无法用密钥登录的问题

2022-06-16 14:37:53 +08:00
 zx900930

这个问题有一阵了, 一直不知道啥原因

检查了配置文件

%PROGRAMDATA%/ssh/sshd_config

里面

PubkeyAuthentication yes
AuthorizedKeysFile	.ssh/authorized_keys

检查了在.ssh/authorized_keys 里面确实有我添加的公钥

用 debug 模式运行 sshd, output 如下:

debug1: trying public key file C:\\ProgramData\\ssh\\administrators_authorized_keys
Failed publickey for xxxxxxx

经检查, 根本就没有 C:\ProgramData\ssh\administrators_authorized_keys 这么个文件 我的公钥都在 .ssh/authorized_keys 里面.

那么是什么导致 OpenSSH 去 administrators_authorized_keys 里面找公钥呢?

翻到 sshd_config 这个配置文件的最下面, 发现有这么两行:

Match Group administrators
       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

直接注释掉:

#Match Group administrators
#       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

重启 sshd 服务 再试试 ssh, 这次没有提示要输 password 而是直接用密钥登录了, 问题解决.

PS: openssh 默认连进去是 cmd 而不是 powershell 可以把 default shell 改成 powershell 方便之后的操作 powershell 下运行:

New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force

重启 sshd 服务, 这下直接连进去就是 powershell 了

2081 次点击
所在节点    Windows
4 条回复
Mitt
2022-06-16 15:23:20 +08:00
所以你是本地 adminstrator 账户吗
zx900930
2022-06-16 15:39:45 +08:00
@Mitt 是的, 是在 administrators 那个组里.
xyfan
2022-06-16 19:36:11 +08:00
管理员账户的 key 就应该放在 administrators_authorized_keys 文件里,至少微软官方文档是这样说明的

“Note that if the user belongs to the administrator group, %programdata%/ssh/administrators_authorized_keys is used instead.”
https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_server_configuration#authorizedkeysfile

“The contents of your public key (~\.ssh\id_ed25519.pub) needs to be placed on the server into a text file called administrators_authorized_keys in C:\ProgramData\ssh\.”
https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_keymanagement#administrative-user
zx900930
2022-06-16 20:54:28 +08:00
@xyfan 这个设计出发点可以理解, 是为了安全性.
但是却和 ssh-copy-id 这样的 linux 命令行工具不兼容
默认 openssh 的公钥也是存在~/.ssh/authorized_keys 里的.

如果是防止普通用户越权连接
管理员的 profile/.ssh/authorized_keys 普通用户本来就无法访问, 也不能添加 key 进去.
普通用户的~/.ssh/authorized_keys 在它自己的 profile 里, 也无权限连接对应的 WSL 的管理员账户.

这个放在另外一个文件里的设计就是徒增麻烦, 实际并没有增加安全性.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/860032

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX