服务器多因素认证需四环节严丝合缝:pam模块正确安装、用户独立生成并保护密钥文件、/etc/pam.d/sshd中精准添加auth规则、/etc/ssh/sshd_config启用usepam、challengeresponseauthentication及authenticationmethods组合;任一缺失则mfa不触发。

服务器多因素认证通过 PAM 模块将 SSH 登录绑定二次认证,本质是让 OpenSSH 在完成首层验证(密钥或密码)后,再调用 Google Authenticator 的 TOTP 动态码做第二道校验。这需要四个环节严丝合缝:模块就位、用户密钥生成、PAM 规则生效、SSH 服务明确启用挑战响应流程。漏掉任一环,MFA 都不会触发。
安装并验证 pam_google_authenticator 模块
模块必须正确安装且系统能加载,否则后续全无效:
- Ubuntu/Debian:运行 sudo apt update && sudo apt install libpam-google-authenticator,然后检查 /lib/security/pam_google_authenticator.so 是否存在
- RHEL/CentOS/Rocky 8+:先启用 EPEL(sudo dnf install epel-release),再装 google-authenticator,确认 /usr/lib64/security/pam_google_authenticator.so 可访问
- 执行 ldd /path/to/pam_google_authenticator.so | grep "not found",确保无缺失依赖;若报 cannot open shared object file,重点排查 EPEL 状态、SELinux 干预(临时 setenforce 0 测试)
为每个用户独立生成并保护密钥文件
root 不能代劳,也不能复制密钥。必须以目标用户身份操作,且权限控制极严格:
- 切换用户用 su - username(不是 sudo -u,避免环境变量不全)
- 运行 google-authenticator -t -d -f -r 3 -R 30:启用 TOTP、禁用重用、保存配置、30 秒内最多 3 次失败
- 按提示选 y 启用时间令牌、禁用重用、开启速率限制、保存配置、生成恢复码——5 个应急码务必离线保存
- 立即执行:chmod 600 ~/.google_authenticator、chmod 700 ~、chmod 700 ~/.ssh
- 同步时间:sudo timedatectl set-ntp true;TOTP 对时差敏感,超 ±30 秒即失效
在 /etc/pam.d/sshd 中精准添加 auth 规则
PAM 行的位置和参数决定 MFA 是否真正介入认证链:
- 编辑 /etc/pam.d/sshd,在文件最上方插入一行(不是末尾,也不是中间):
auth [success=ok default=die] pam_google_authenticator.so secret=/home/$USER/.google_authenticator - 该行必须出现在 auth [success=done] pam_unix.so 之后、auth required pam_deny.so 之前
- 调试阶段可加 nullok 允许未配用户登录,但上线前必须删除,否则无法强制启用
- 避免混入 debug 或 verbose 选项,它们会拖慢登录并暴露日志
修改 /etc/ssh/sshd_config 强制触发挑战响应流程
仅启用 UsePAM 或 ChallengeResponseAuthentication 不够,关键在 AuthenticationMethods 的组合逻辑:
- 确保以下三项同时存在且未被注释:
UsePAM yes
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive - 如果只希望特定用户(如 admin)强制 MFA,可用 Match 块覆盖:
Match User admin
AuthenticationMethods publickey,keyboard-interactive
PermitRootLogin no
注意:所有 Match 块必须放在 sshd_config 末尾,且前面不能有全局 AuthenticationMethods - 改完后执行 sudo systemctl restart sshd,并用非 root 账户测试登录
整个过程不复杂但容易忽略细节:时间不同步、密钥文件权限过宽、PAM 行位置错误、sshd_config 缺少 AuthenticationMethods —— 这四类问题占了实际部署失败的九成以上。











