CentOS上用Google Authenticator实现SSH双因子认证需四步:装EPEL源及google-authenticator包;用户执行google-authenticator生成密钥并绑定手机App;在/etc/pam.d/sshd中添加pam_google_authenticator.so行且顺序正确;修改/etc/ssh/sshd_config启用ChallengeResponseAuthentication和UsePAM,禁用PasswordAuthentication后重启sshd。

在CentOS上用Google Authenticator实现SSH双因子认证,核心是“系统密码 + 手机App动态验证码”组合,符合等保对“两种不同鉴别因子”的要求。整个过程分四步:装模块、配用户、改PAM、调SSH,不复杂但关键细节容易出错。
安装Google Authenticator PAM模块
先确保EPEL源已启用(CentOS 7/8默认未开):
-
CentOS 7:
yum install epel-release -y -
CentOS 8/9:
dnf install epel-release -y - 然后安装主包:
yum install google-authenticator -y(或dnf install google-authenticator)
注意:无需手动编译,官方仓库版本已包含pam_google_authenticator.so,自动部署到/lib64/security/目录。
为每个用户生成并绑定密钥
切勿用root直接配置。切换到目标用户(如john),执行:
su - johngoogle-authenticator
按提示选5次y(推荐全选):
- 启用基于时间的令牌(TOTP)——必须选
y - 更新
~/.google_authenticator文件——必须选y - 禁止同一令牌重复使用——防中间人攻击,选
y - 允许时钟偏差(默认±30秒)——建议选
y,避免因服务器/手机时间不同步导致失败 - 启用登录失败限制(30秒内最多3次尝试)——增强暴力防护,选
y
执行后会显示二维码、密钥(如G5RR2IJG2X74MI4ADW622R6PUA)和5个应急备用码。用手机Google Authenticator、Microsoft Authenticator或Authy扫码或手动输入密钥即可绑定。备用码务必离线保存,每用一次即失效。
配置PAM让SSH调用验证器
编辑/etc/pam.d/sshd:
- 在文件最上方添加一行:
auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so nullok -
nullok表示允许尚未配置GA的用户暂时跳过(调试阶段可用);上线前应改为secret=/home/$USER/.google_authenticator并删掉nullok,实现强制启用 - 确保该行在
auth [success=done] pam_unix.so之后、auth required pam_deny.so之前,顺序错误会导致认证失败
调整SSH服务支持挑战响应模式
编辑/etc/ssh/sshd_config,确认以下三行已取消注释且值为yes:
-
ChallengeResponseAuthentication yes(启用交互式挑战) -
UsePAM yes(允许PAM介入认证流程) -
PasswordAuthentication no(可选,禁用纯密码登录,仅保留密钥+GA组合更安全)
保存后重启服务:systemctl restart sshd。操作前务必保留一个已登录的终端窗口,防止配置错误锁死自己。


















