ssh集成google authenticator实现mfa需四步协同:安装pam_google_authenticator.so模块、为用户生成并保护~/.google_authenticator密钥文件、在/etc/pam.d/sshd顶部配置正确pam规则、启用sshd_config中challengeresponseauthentication与usepam并设authenticationmethods。

服务器多因素认证(MFA)在 SSH 登录中集成 Google Authenticator,核心是让登录流程分两步走:先验证“你知道的”凭证(密码或密钥),再验证“你拥有的”动态码。这不是装个 App 就能用的功能,而是需要服务端四方面协同生效——模块安装、用户配置、PAM 规则、SSH 服务设置,缺一不可。
安装 PAM 模块并确认可用
Google Authenticator 的验证逻辑由 PAM 模块 pam_google_authenticator.so 承担,必须先装好并确保路径正确:
- Ubuntu/Debian:
sudo apt update && sudo apt install libpam-google-authenticator,模块路径为/lib/security/pam_google_authenticator.so - CentOS/RHEL/Rocky 8+:
sudo dnf install google-authenticator(EPEL 已启用),模块路径通常为/usr/lib64/security/pam_google_authenticator.so - 安装后执行
ls /path/to/pam_google_authenticator.so确认文件存在;再运行ldd /path/to/pam_google_authenticator.so | grep "not found"排查依赖缺失
为每个用户生成并保护密钥文件
必须以目标用户身份操作,root 不能代劳,也不能复制密钥文件:
- 切换到用户:
su - username(不用sudo -u,避免环境变量异常) - 运行:
google-authenticator -t -f -r 3 -R 30 -w 17(-t启用 TOTP,-f强制覆盖旧配置,-r 3限 3 次错误,-w 17支持 ±8 个时间片,容错约 ±4 分钟) - 按提示全选
y:启用时间令牌、禁用重放、开启速率限制、保存配置、生成 5–10 个应急码(务必离线保存,每用一次即作废) - 立即加固权限:
chmod 600 ~/.google_authenticator && chmod 700 ~ && chmod 700 ~/.ssh
配置 PAM 规则,放在 /etc/pam.d/sshd 顶部
PAM 行的位置和参数决定第二步是否真正触发,加错等于没配:
- 在
/etc/pam.d/sshd文件最上方插入一行(不是末尾,也不是中间):auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so secret=/home/%u/.google_authenticator - 调试阶段可加
nullok允许未配置用户登录,上线前必须删除,否则部分用户绕过 MFA - 切勿使用
required或[success=done],前者易导致静默失败,后者可能跳过后续认证环节 - 若启用了 SELinux,需确认策略允许 PAM 调用该模块,否则无日志报错但验证不生效
调整 SSH 配置并重启服务
PAM 只管验证逻辑,SSH 必须明确启用挑战响应流程才能调用它:
- 编辑
/etc/ssh/sshd_config,确保以下四行同时存在且未被注释:ChallengeResponseAuthentication yesUsePAM yesPasswordAuthentication no(如用密码登录)或PubkeyAuthentication yes(如用密钥)AuthenticationMethods publickey,keyboard-interactive(密钥 + 动态码)或password,keyboard-interactive(密码 + 动态码) - 语法检查:
sudo sshd -t,无输出表示配置格式正确 - 重启服务:
sudo systemctl restart sshd(或sshd,依系统而定) - 实测验证:
ssh -v user@host,日志中必须出现Next authentication method: keyboard-interactive,否则说明第二步未触发,重点检查ChallengeResponseAuthentication和 PAM 行位置











