启用服务器双因素认证需完成四步:安装PAM模块、用户生成密钥、配置PAM规则、调整SSH设置;必须同步时间、严格权限、SELinux放行,否则静默失败。

启用服务器双因素认证(2FA)使用 Google Authenticator,本质是让 SSH 登录同时验证“密码”和“动态验证码”,不是只装手机 App 就行,服务端必须完成模块安装、用户配置、PAM 集成和 SSH 调整四步闭环。
安装 Google Authenticator PAM 模块
不同系统命令不同,但目标一致:把 pam_google_authenticator.so 安装到系统 PAM 模块目录。
- Ubuntu/Debian:
sudo apt update && sudo apt install libpam-google-authenticator - CentOS 7/RHEL 7:先开 EPEL(
sudo yum install epel-release),再运行sudo yum install google-authenticator - CentOS 8+/Rocky/AlmaLinux:用
sudo dnf install google-authenticator - 安装后检查文件是否存在:
• Debian/Ubuntu:ls /lib/security/pam_google_authenticator.so
• RHEL 系列:ls /usr/lib64/security/pam_google_authenticator.so
为每个用户生成并绑定密钥
必须以目标用户身份操作,root 不能代劳。密钥文件 ~/.google_authenticator 生成后自动设为 600 权限,若被修改会导致静默失败。
- 切换用户,例如:
su - john - 执行:
google-authenticator - 按提示选(推荐全选 y):
✓ 启用基于时间的令牌(TOTP,必须)
✓ 更新配置文件
✓ 禁止同一令牌重复使用(防重放)
✓ 允许 ±30 秒时钟偏差(避免因时间不同步失效)
✓ 启用速率限制(30 秒内最多 3 次尝试)
✓ 生成 5–10 个应急备用码(务必离线保存,每用一次即作废) - 扫描终端显示的二维码,或手动输入密钥到 Google Authenticator、Authy 或 Microsoft Authenticator 中
配置 PAM 让 SSH 调用验证器
编辑 /etc/pam.d/sshd,添加规则行——位置和写法直接影响是否生效。
- 在文件最上方插入一行(不要放在
auth include password-auth后面):auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so nullok -
nullok表示未配置 GA 的用户仍可登录(调试阶段可用),上线前应改为:auth [success=ok default=die] pam_google_authenticator.so secret=/home/${USER}/.google_authenticator - 切勿使用
required或requisite;顺序错误、权限不对、SELinux 未放行都可能导致认证失败且无明确日志
调整 SSH 配置并重启服务
PAM 只管验证逻辑,SSH 必须开启对应交互模式才能触发二次输入。
- 编辑
/etc/ssh/sshd_config,确认以下三行已取消注释且值为 yes:ChallengeResponseAuthentication yesUsePAM yesPasswordAuthentication yes(若用密钥登录,可设为no,但需确保PubkeyAuthentication yes) - 保存后重启服务:
• Ubuntu/Debian:sudo systemctl restart ssh
• RHEL/CentOS:sudo systemctl restart sshd - 测试登录时,先输密码,再立即输入 Authenticator App 显示的 6 位数字(中间无空格)
关键细节常被忽略:系统时间必须同步(NTP)、家目录与 .google_authenticator 权限必须严格(chmod 700 ~ 和 chmod 600 ~/.google_authenticator)、SELinux 若启用需放行(setsebool -P authlogin_nis_enabled 1)。不复杂但容易卡在某一步。











