必须完成PAM模块加载、用户密钥独立生成、认证流程顺序控制三者协同:先同步系统时间,再安装对应发行版的google-authenticator包,验证模块路径,为每个用户单独生成权限为600的密钥文件,PAM配置插入auth行于password-auth上方并启用nullok,SSH端配置启用UsePAM、ChallengeResponseAuthentication及AuthenticationMethods为publickey,keyboard-interactive,最后语法检查并重载服务。

要让SSH登录必须同时输入私钥和手机上动态生成的6位验证码,防止攻击者仅靠窃取密钥或密码就直接登录服务器,必须完成PAM模块加载、用户密钥独立生成、认证流程顺序控制三者协同。
安装并验证Google Authenticator模块
先确认系统时间已同步,TOTP对时差极其敏感,偏差超30秒即验证失败:sudo timedatectl set-ntp true。
Debian/Ubuntu执行:【sudo apt install libpam-google-authenticator】;RHEL/CentOS/Rocky需先启用EPEL:sudo dnf install epel-release && sudo dnf install google-authenticator。
验证模块是否存在:Debian系运行ls /lib/security/pam_google_authenticator.so,RHEL系运行ls /usr/lib64/security/pam_google_authenticator.so。若提示“cannot open shared object file”,大概率是包名装错(CentOS不叫libpam-google-authenticator)或SELinux拦截,可临时setenforce 0测试。
为每个目标用户生成独立密钥文件
切到该用户执行:【su - deploy】 → 【google-authenticator -t -d -f -r 3 -R 30】。
这一步root不能代劳——PAM会严格校验~/.google_authenticator属主和权限,root生成的文件会被跳过验证,登录时静默失败。
回答提示时:第1项(启用TOTP)必须选y;第3项(禁用重复使用码)必须选y;第4项(启用速率限制)建议选y;其余按需。生成后立即检查:ls -l ~/.google_authenticator应显示-rw-------(600),否则执行chmod 600 ~/.google_authenticator。
务必离线保存屏幕显示的5个应急恢复码——手机丢失或配置损坏时,这是唯一能登上去的路。
配置PAM规则强制触发二次验证
编辑/etc/pam.d/sshd,在auth include password-auth这一行的正上方插入:
【auth [success=ok new_authtok_reqd=ok default=bad] pam_google_authenticator.so nullok secret=/home/%u/.google_authenticator】
注意:不能加在password-auth下方,否则规则被跳过;不能用auth required,否则未初始化密钥的用户将彻底无法登录;nullok参数允许分批启用,上线稳定后应删除。
确保/etc/ssh/sshd_config中存在且未注释:UsePAM yes(必须开启,否则整段PAM不加载)。
设置SSH认证链并重启服务
第一步:确认OpenSSH版本,运行ssh -V。若为8.8及以上,编辑/etc/ssh/sshd_config,确保以下三行存在且生效:
ChallengeResponseAuthentication yes
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive
第二步:执行sudo sshd -t检查配置语法是否正确。
第三步:用新终端窗口测试登录,确认能弹出6位验证码输入提示且验证通过后才进入shell,再执行【sudo systemctl reload sshd】使配置永久生效。


















