如何在 Linux 上为 SSH 启用 MFA(Google Authenticator 方式)
这里以 Google Authenticator 作为示例,配置 SSH 登录时启用 MFA。
1. 安装 Google Authenticator
sudo apt update
sudo apt install libpam-google-authenticator
(CentOS / RHEL)
sudo yum install google-authenticator
2. 配置 Google Authenticator
为每个用户启用 Google Authenticator:
google-authenticator
回答问题(推荐选项):
✅ "Do you want authentication tokens to be time-based?" → Yes(Y)
✅ 记录 密钥和二维码(可用 Google Authenticator 扫描)
✅ "Do you want me to update your “.google_authenticator” file?" → Yes(Y)
✅ "Do you want to enable rate-limiting?" → Yes(Y)(防止暴力破解)
3. 配置 PAM 让 SSH 需要 MFA
编辑 /etc/pam.d/sshd
,添加:
auth required pam_google_authenticator.so
4. 配置 SSH 服务器支持 MFA
编辑 /etc/ssh/sshd_config
,确保:
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,password publickey,keyboard-interactive
UsePAM yes
- 这表示 SSH 既需要密码,也需要 MFA
- 如果使用 SSH Key + MFA,请启用
publickey,keyboard-interactive
保存并重启 SSH 服务:
sudo systemctl restart sshd
5. 测试 SSH MFA
从另一台机器尝试 SSH 登录:
ssh your-user@your-server
系统会: ✅ 先要求密码
✅ 再要求 Google Authenticator MFA(输入 App 里的 6 位验证码)
6.是否必须使用 MFA?(可选绕过 MFA 的情况)
A.仅对某些用户启用 MFA
- 在
/etc/pam.d/sshd
前面加一行:
auth [success=1 default=ignore] pam_succeed_if.so user in group mfausers
auth required pam_google_authenticator.so
- 这表示 仅属于
mfausers
组的用户需要 MFA - 创建
mfausers
组:
sudo groupadd mfausers
sudo usermod -aG mfausers your-user
B.对 SSH Key 认证免除 MFA
- 在
/etc/ssh/sshd_config
里,确保:
AuthenticationMethods publickey password,keyboard-interactive
- 这意味着 使用 SSH Key 登录时,不需要 MFA,但密码登录仍然需要 MFA。
总结
方案 | 是否需要 MFA |
---|---|
默认 SSH 密码登录 | ✅ 需要 MFA |
SSH 密钥登录(默认) | ❌ 不需要 MFA |
密码 + SSH Key 登录 | ✅ 需要 MFA |
仅特定用户需要 MFA | ⚠️ 可配置 |
仅密码登录需要 MFA,SSH Key 免 MFA | ⚠️ 可配置 |
建议配置:
- 使用 SSH Key 登录(安全性更高),可跳过 MFA
- 对密码登录强制启用 MFA,增强安全性
- 仅让特定用户需要 MFA,适用于运维环境
如果你想 SSH 100% 强制 MFA,确保 AuthenticationMethods publickey,keyboard-interactive
,这样 SSH Key 也需要 MFA!🔐