可通过集成Google Authenticator实现SSH的TOTP多因素认证,步骤包括:安装PAM模块、为用户生成密钥并绑定验证器、配置PAM策略、启用SSH的ChallengeResponseAuthentication、测试登录并设置应急通道。

如果您希望增强Linux服务器SSH登录的安全性,防止仅依赖密码或密钥被破解的风险,则可以通过集成Google Authenticator实现基于时间的一次性密码(TOTP)多因素认证。以下是配置此功能的具体步骤:
一、安装Google Authenticator PAM模块
Google Authenticator以PAM(Pluggable Authentication Modules)模块形式工作,需在系统中安装对应软件包,使SSH服务能调用其验证逻辑。
1、以root用户执行更新软件源命令:apt update(Ubuntu/Debian)或yum update(CentOS 7)或dnf update(CentOS 8/RHEL 8/Fedora)。
2、安装google-authenticator-libpam包:apt install libpam-google-authenticator(Debian/Ubuntu)或yum install google-authenticator(CentOS 7)或dnf install google-authenticator(CentOS 8+)。
3、验证模块文件是否存在:ls /lib/security/pam_google_authenticator.so或ls /usr/lib64/security/pam_google_authenticator.so,确认路径下存在该文件。
二、为用户生成TOTP密钥并配置验证器
每个启用MFA的用户需独立运行初始化命令,生成唯一密钥、二维码及备用恢复码,该过程仅对当前shell用户生效,不涉及系统级密钥共享。
1、切换至目标用户(如ubuntu):su - ubuntu。
2、执行初始化命令:google-authenticator。
3、按提示依次选择:y(启用时间同步令牌)、y(禁用同一令牌多次使用)、y(启用速率限制,每30秒最多3次尝试)、y(保存设置到用户主目录的~/.google_authenticator文件)、y(生成并显示10个一次性应急恢复码)。
4、使用手机端Google Authenticator、Authy或Microsoft Authenticator扫描终端输出的QR码,或手动输入密钥完成绑定。
三、配置PAM策略启用MFA验证流程
PAM负责定义认证顺序与条件,需修改SSH专用PAM配置文件,将Google Authenticator设为必要验证环节,确保每次SSH登录均触发TOTP校验。
1、备份原始配置:cp /etc/pam.d/sshd /etc/pam.d/sshd.bak。
2、在/etc/pam.d/sshd文件顶部添加以下行(Debian/Ubuntu):auth [success=ok default=die] pam_google_authenticator.so nullok secret=/home/${USER}/.google_authenticator。
3、若系统为RHEL/CentOS且使用systemd-logind,还需添加:auth [success=done default=ignore] pam_google_authenticator.so nullok。
4、确保该行位于其他auth段指令之前,避免被skip规则绕过。
四、修改SSH守护进程配置启用键盘交互认证
OpenSSH必须启用ChallengeResponseAuthentication机制,才能在密码验证后继续请求TOTP输入;若关闭此选项,PAM中的Google Authenticator将不会被调用。
1、编辑SSH服务配置文件:nano /etc/ssh/sshd_config。
2、定位并修改以下三项参数值:ChallengeResponseAuthentication yes、PasswordAuthentication yes、UsePAM yes。
3、若同时启用公钥认证,保留PubkeyAuthentication yes,但需注意:当PasswordAuthentication设为no时,TOTP将无法触发,除非额外配置AuthenticationMethods。
4、保存退出后重载服务:systemctl restart sshd(或service ssh restart)。
五、测试MFA登录流程并设置备用访问路径
验证配置是否生效需模拟真实登录场景,同时预留紧急通道以防TOTP失效导致锁死,保障运维可持续性。
1、从另一终端使用SSH连接服务器:ssh username@server_ip。
2、输入用户密码后,等待提示输入“Verification code”:Enter verification code:,此时打开手机Auth应用查看6位动态码并输入。
3、若登录失败,检查/var/log/auth.log(Debian/Ubuntu)或/var/log/secure(RHEL/CentOS)中pam_google_authenticator相关错误条目。
4、为防手机丢失或应用损坏,提前将应急恢复码存于离线安全位置,并确保至少一个备用管理员账户未启用MFA或已配置SSH密钥免密登录。










