SSH启用多因素认证需服务端装模块、用户生成密钥、PAM与sshd_config同步配置三者缺一不可;常见问题包括pam_google_authenticator.so未安装或路径错误、权限/SELinux拦截、恢复码未备份及服务器时间偏差超30秒。

ssh 登录启用多因素认证不是加个 App 就能用的,必须服务端装对模块、用户自己生成密钥、PAM 和 sshd_config 同步改好——三者缺一不可,否则登录时只会静默失败或报 Authentication failure。
确认 PAM 模块已正确安装并可加载
很多故障根源是 pam_google_authenticator.so 根本没装上,或路径不对,或被 SELinux/权限拦截。
- Debian/Ubuntu:检查
ls /lib/security/pam_google_authenticator.so是否存在;若无,运行sudo apt install libpam-google-authenticator - RHEL/CentOS/Rocky 8+:先启用 EPEL(
sudo dnf install epel-release),再装sudo dnf install google-authenticator;验证文件在/usr/lib64/security/pam_google_authenticator.so - 常见错误:
pam_google_authenticator.so: cannot open shared object file→ 检查包名是否拼错(CentOS 不是libpam-google-authenticator)、是否漏装 EPEL、是否 SELinux 阻断(临时setenforce 0测试)
用户必须亲自运行 google-authenticator 生成密钥
root 不能代劳,也不能复制 ~/.google_authenticator 文件过去——PAM 会因权限或属主不符直接跳过验证。
- 切到目标用户执行:
su - username,再运行google-authenticator - 关键选项必须选
y:启用 TOTP(时间型)、禁用重复使用码、启用速率限制(30 秒最多 3 次)、保存配置、生成恢复码 - 生成后立刻检查:
ls -l ~/.google_authenticator必须是-rw-------(600),且属主为该用户;否则日志里只有open(...) failed: Permission denied - 恢复码务必离线保存——文件损坏或手机丢失时,这是唯一解锁账户的途径
/etc/pam.d/sshd 的配置顺序和参数很关键
加错位置或参数不匹配会导致验证跳过、仅密码生效,或所有用户强制 MFA(包括未初始化的用户)。
- 备份原文件:
sudo cp /etc/pam.d/sshd /etc/pam.d/sshd.bak - 在文件**顶部**添加(Debian/Ubuntu 推荐):
auth [success=ok default=die] pam_google_authenticator.so nullok secret=/home/${USER}/.google_authenticator - RHEL/CentOS 更稳妥写法:
auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so nullok secret=/home/%u/.google_authenticator -
nullok表示:该用户没生成.google_authenticator文件时仍允许仅密码登录(避免锁死);去掉它则所有用户都必须配好才能登录 - 别用
required——它会在后续模块失败时仍继续执行,可能绕过验证
/etc/ssh/sshd_config 必须启用 ChallengeResponseAuthentication
即使 PAM 配置全对,ChallengeResponseAuthentication no(默认值)也会让 SSH 直接忽略动态码输入环节。
- 确保以下三项均为
yes:ChallengeResponseAuthentication yes、UsePAM yes、PasswordAuthentication yes(若禁用密码,需配合公钥 + MFA,逻辑更复杂) - 改完必须重启服务:
sudo systemctl restart sshd(Ubuntu/Debian)或sudo systemctl restart sshd(RHEL 系列) - 测试前先开一个保留的 root 会话——防止配置错误导致自己登不上
- 系统时间偏差 > 30 秒会导致 TOTP 失效,务必先同步时间:
sudo chronyd -q 'server pool.ntp.org iburst'或sudo ntpdate -s pool.ntp.org
真正容易被忽略的是恢复码保管和时间同步。服务器时间漂移、用户删了 .google_authenticator、又没存恢复码——账户就彻底不可登录。别等出事才想起备份。


















