本文由社区 AI 助手整理,参考 OpenSSH 官方 man page 与发布说明;不同发行版的默认值与 Include 顺序不同,请以
sshd -T输出为准。
结论
ssh-keygen 生成密钥只解决了「不用密码」,没有解决「谁能用、用到什么程度、私钥泄露后怎么办」。生产环境至少要确认四件事:关掉密码登录;密钥权限不被 StrictModes 拒绝;私钥有口令且不出本机;边界用 from=、command= 或证书收窄。

四个口径
- 密钥类型。
ed25519是 OpenSSH 当前常用的默认选择;RSA 至少 3072 位;需要硬件保护时用ed25519-sk或ecdsa-sk。 -a是 KDF 轮数,默认 16;提高轮数不会把弱口令变强。- 文件权限。
~/.ssh700,authorized_keys600,私钥 600。StrictModes yes时,home 或.ssh可被组或其他用户写,公钥认证会被拒绝。 - 证书。CA 私钥签用户公钥,服务端只信任 CA(
TrustedUserCAKeys),不用逐台分发authorized_keys。
操作步骤
1. 生成与保护私钥
ssh-keygen -t ed25519 -a 100 -C "laptop-2026" -f ~/.ssh/id_ed25519
ssh-keygen -lf ~/.ssh/id_ed25519.pub
私钥不要放进网盘、聊天记录或 Git。需要硬件保护时:
ssh-keygen -t ed25519-sk -O resident -O verify-required -C "yubikey-2026"
verify-required 要求 PIN;resident 把凭据存进认证器。设备丢失后要在服务端移除公钥。
2. 管住 agent
ssh-add -t 3600设置有效期,ssh-add -c每次使用需确认。- 不要在不可信主机上
ssh -A:agent 转发暴露本机 agent socket,远端 root 可借用你的密钥签名。
3. 收窄 authorized_keys
from="10.20.0.0/16",no-agent-forwarding,no-port-forwarding,no-pty,command="/usr/local/bin/backup.sh" ssh-ed25519 AAAA...
只允许备份的密钥只给备份命令,不要给交互 shell;注释写清用途与到期时间。
4. 证书与 sshd
ssh-keygen -s ca_user -I alice-2026 -n alice -V +52w alice.pub
ssh-keygen -L -f alice-cert.pub
服务端关键项:
TrustedUserCAKeys /etc/ssh/user_ca.pub
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication no
PermitRootLogin prohibit-password
-n 是 principals,必须与登录名匹配;-V 控制有效期。证书过期后客户端会看到「certificate has expired」,不会回退到密码。

四道验证
- 有效配置:
sudo sshd -T | grep -E 'pubkeyauthentication|passwordauthentication|permitrootlogin|strictmodes',确认没有被 Include 覆盖。 - 实际认证:
ssh -vv user@host 2>&1 | grep -E 'Offering|Server accepts|Authenticated',能看到公钥被接受。 - 密码回退:
ssh -o PubkeyAuthentication=no -o PreferredAuthentications=password user@host应当失败。 - 日志与边界:
journalctl -u ssh --since -10m或/var/log/auth.log查Accepted publickey;用from=的密钥从允许网段外连接应被拒。
清单
- 私钥有口令,权限 600,未进版本库。
- 服务端
PasswordAuthentication no,root 只允许密钥。 - 每把密钥有用途、负责人、到期时间;离职或换机时删除或吊销。
- 高价值主机用证书加短有效期。
来源说明
OpenSSH ssh-keygen(1)、sshd_config(5)、authorized_keys(5) man page;OpenSSH 9.x 发布说明;NIST SP 800-57。默认值与 Include 顺序以 sshd -T 为准。