0%

MacOS设置sshd服务免密登录

MacOS设置sshd服务免密登录

本篇将介绍如何使用免密证书的方式登录 MacOS 系统。

生成证书

1
ssh-keygen -t rsa -b 4096 -c "codezm@163.com"

安装证书

将公钥证书安装到 192.168.36.47 MacOS 机器。

1
ssh-copy-id -i ~/.ssh/id_rsa.pub codezm@192.168.36.47

确认免密登录

1
2
3
4
5
6
7
8
9
10
11
# 若私钥文件名是 id_rsa,那么 -i ~/.ssh/id_rsa 参数可省略。
ssh -i ~/.ssh/id_rsa codezm@192.168.36.47

# 若私钥文件名不是 id_rsa,今后登录时也不想指定证书文件。
# 有以下两种方式:
# 1. 可以将私钥添加到身份验证密钥管理工具:ssh-add。之后登录就不需要指定私钥路径了。
ssh-add -K id_rsa
# 2.编辑文件: ~/.ssh/config
Host 192.168.36.47
HostName 192.168.36.47
IdentityFile ~/.ssh/id_rsa

关闭账号密码登录

1
vim /etc/ssh/sshd_config

向文件尾部追加以下内容:

1
2
3
4
5
6
7
8
9
10
11
# 禁用密码认证
PasswordAuthentication no

# 禁用键盘交互认证
KbdInteractiveAuthentication no

# 确保启用公钥认证
PubkeyAuthentication yes

# 禁用挑战-响应认证
ChallengeResponseAuthentication no

重启 sshd 服务,使配置生效。

1
2
sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist

记录免密登录失败分析思路

1
2
3
4
5
6
$ log show --predicate 'process == "sshd"' --info --last 10

Filtering the log data using "process == "sshd""
Skipping debug messages, pass --debug to include.
Timestamp Thread Type Activity PID TTL
2024-05-28 09:59:33.732102+0800 0x7ff0 Info 0x0 6224 0 sshd: Authentication refused: bad ownership or modes for directory /Volumes/work

问题原因是由软链引起的。

初衷是想将 .ssh 目录放到 dotfile 中由 Git 统一管理维护,但万万没想到竟然造成 sshd 无法实现免密证书登录。

1
2
ln -s /Users/codezm/.config/dotfile/.ssh ~/.ssh
ln -s /Volumes/work/envconfig ~/.config