SSH双因素认证需PAM与SSH协同配置:密钥或密码为第一因子,Google Authenticator TOTP为第二因子,两者缺一不可;须校准系统时间、安装PAM模块、为用户生成TOTP密钥、在/etc/pam.d/sshd中前置添加校验规则,并在sshd_config中启用ChallengeResponseAuthentication、UsePAM及AuthenticationMethods。

要让 SSH 登录真正强制执行双因素认证(2FA),不能只靠“密码 + 验证码”这种松散组合,必须通过 PAM 和 SSH 配置协同控制认证流程,确保两个因子都通过才允许登录。核心是:密钥或密码作为第一因子,Google Authenticator 的 TOTP 作为第二因子,且两者缺一不可。
同步系统时间并安装必要组件
TOTP 动态码依赖时间严格同步,误差超过 30 秒即失效。先校准服务器时间:
- 运行
sudo timedatectl set-ntp true启用 systemd-timesyncd(推荐);或使用sudo ntpdate -s time.google.com - 验证时间偏差:
timedatectl status | grep "System clock",确保显示 “synchronized: yes” - 安装 Google Authenticator PAM 模块:
• Ubuntu/Debian:sudo apt update && sudo apt install libpam-google-authenticator -y
• CentOS/RHEL/AlmaLinux:sudo dnf install epel-release google-authenticator -y
为用户生成并绑定 TOTP 密钥
切换到目标用户(如 sudo su - alice),运行:
google-authenticator- 按提示选择:
• Time-based tokens? →y(必须选 y,否则不兼容主流验证器)
• Disallow multiple uses? →y(防重放)
• Increase time window? →n(保持默认 30 秒窗口,提升安全性)
• Enable rate-limiting? →y(默认 3 次/30 秒,防暴力尝试) - 保存好显示的 16 位密钥、5 个应急码(建议打印离线保存),并用 Authy / Microsoft Authenticator 扫描二维码完成绑定
配置 PAM 强制校验第二因子
编辑 /etc/pam.d/sshd,在文件最上方添加一行(顺序关键):
-
auth [success=done default=ignore] pam_google_authenticator.so nullok
•nullok允许未配置 2FA 的用户暂时登录(适合灰度迁移);若要全员强制,改为auth [success=ok default=die] pam_google_authenticator.so - 确保该行位于其他
auth规则之前,保证 TOTP 校验优先触发
启用 SSH 双因子认证模式
编辑 /etc/ssh/sshd_config,确认以下三项已设置并取消注释:
ChallengeResponseAuthentication yesUsePAM yes-
AuthenticationMethods publickey,keyboard-interactive
• 若仅用密码登录,改为password,keyboard-interactive
• 注意:keyboard-interactive是触发 PAM 中 TOTP 输入的关键机制 - 保留
PubkeyAuthentication yes(如使用密钥),但不要单独设为唯一方式
修改后执行 sudo systemctl restart sshd 生效。测试前建议保留一个未关闭的 root 会话,以防配置错误锁死。


















