google authenticator服务端需安装pam_google_authenticator模块:centos/rhel启用epel后yum install google-authenticator,debian/ubuntu执行apt install libpam-google-authenticator;用户须自行运行google-authenticator生成600权限的~/.google_authenticator文件,ssh需配置pam与sshd_config并同步系统时间。

Google Authenticator 服务端组件必须装 pam_google_authenticator
Linux 上启用 Google Authenticator 并不是装个手机 App 就完事——服务端要靠 pam_google_authenticator 这个 PAM 模块来验证动态码。它不包含在系统默认 PAM 包里,CentOS/RHEL 需先启用 EPEL 仓库再装:yum install google-authenticator(注意包名是 google-authenticator,但实际提供的是 pam_google_authenticator.so);Debian/Ubuntu 则直接 apt install libpam-google-authenticator。
常见错误现象:ssh 登录时提示 Authentication failure 但密码正确,或 pam_google_authenticator.so: cannot open shared object file——基本就是模块没装、路径不对,或 SELinux 拦截了(RHEL 系统需确认 /usr/lib64/security/pam_google_authenticator.so 权限是否被限制)。
用户级配置文件 ~/.google_authenticator 必须由本人生成且权限严格
每个用户得自己运行 google-authenticator 命令生成密钥和配置文件,不能 root 代劳再复制过去。生成后立刻检查:ls -l ~/.google_authenticator 必须是 -rw-------(600),且属主是该用户。否则 PAM 会静默拒绝读取,日志里只留一句 open("/home/user/.google_authenticator") failed: Permission denied。
使用场景:SSH 登录、sudo 提权、Gnome 图形登录都依赖这个文件。若用 sudo -u user google-authenticator 生成,容易漏掉环境变量导致 QR 码乱码;更稳妥的是切到目标用户 shell 再执行。
- 生成时建议选
y启用时间戳同步(TOTP),别选基于计数器的 HOTP - 勾选
y允许 30 秒内重复使用码——避免因系统时间微偏导致连续失败 - 备份好生成的密钥和恢复码,
.google_authenticator文件一旦损坏,没有恢复码就锁死账户
SSH 登录启用双因素需改两处 PAM 配置,顺序不能错
仅修改 /etc/pam.d/sshd 不够,还要确保 /etc/ssh/sshd_config 开启挑战响应:ChallengeResponseAuthentication yes,并重启 sshd。PAM 行推荐加在 auth [success=done new_authtok_reqd=done default=ignore] 类型下:
auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so nullok secret=/home/$USER/.google_authenticator
参数差异:nullok 允许未配置的用户跳过验证(上线初期过渡用),上线后应删掉;secret=... 路径里的 $USER 是 PAM 变量,不能写死成具体用户名;enforce 会强制所有用户启用,没配置就拒绝登录——慎用。
性能影响几乎为零,但若服务器时间不准(偏差 > 90 秒),TOTP 验证必失败。建议配 chronyd 或 ntpd 同步时间,别只靠手机校准。
sudo 提权加双因素容易触发循环验证
想在 sudo 时也输验证码?别直接往 /etc/pam.d/sudo 加 pam_google_authenticator.so。因为 sudo 默认复用 session,而 Google Authenticator 的 TOTP 验证是一次性的,第二次输同一码会失败,导致反复提示输入、卡住。
解决办法是单独建一条 auth 规则,用 auth [success=ok default=ignore] + try_first_pass 参数:
auth [success=ok default=ignore] pam_google_authenticator.so try_first_pass
这样它会先尝试用已输入的密码(或之前缓存的验证结果)跳过,只有真正需要时才弹验证码。另外,务必确认 sudoers 里没设 Defaults env_reset 过度清理环境——某些发行版默认开启,会导致 PAM 找不到用户家目录变量,进而读不到 .google_authenticator。
最易被忽略的一点:手机端 App 添加账号时,手动输入密钥比扫 QR 码更可靠。有些终端显示的 QR 码含换行或空格,扫码后密钥错一位,后续所有码全无效,但错误表现和时间不同步一模一样,排查起来特别绕。










