安装依赖环境

yum install gcc wget pam-devel libpng-devel libtool

安装git及二维码工具

yum install -y git qrencode

安装google-authenticator

git clone https://github.com/google/google-authenticator.git
cd google-authenticator/libpam
./bootstrap.sh
./configure
make && make install
cp /usr/local/lib/security/pam_google_authenticator.so /lib64/security/

修改PAM,SSH登录时调用google-authenticator模块

编辑/etc/pam.d/sshd文件,在第一行添加如下代码

auth       required     pam_google_authenticator.so

编辑 /etc/ssh/sshd_config 文件,修改如下内容

ChallengeResponseAuthentication yes    \\启用其它认证
UsePAM yes                             \\启用UsePAM模块

重启 sshd

/etc/init.d/sshd restart

配置google authentication 生成基于计数的认证token(可以忽略时间错误)

参数:
   -c, --counter-based  基于计数器生成动态码(可以忽略时间差错误)
   -t, --time-based基于时间生成动态码
   -R, --rate-time=M设置登录频率限制的时间间隔
   -w, --window-size=W  设置时间窗的大小,主要在移动设备的时间不是准确同步的情况下比较有用

交互式命令 google-authenticator 生成token,可以一直按y,如果特殊需要可以自行修改

google-authenticator
Do you want authentication tokens to be time-based (y/n): n   
是否基于时间生成动态码,n是基于计数器
此时会生成一个很大的二维码,和手机客户端登录的密钥和5个应急码,手机客户端扫描二维码就可以直接自动添加当前账户

Google Authenticator安全配置ssh二次验证登录_google-authenticator

Google Authenticator安全配置ssh二次验证登录_google_02

Do you want me to update your "/root/.google_authenticator" file (y/n):y  
应急码的保存路径

Google Authenticator安全配置ssh二次验证登录_二次验证_03

increased from its default size of 3 to 17. Do you want to do so  (y/n):y

Google Authenticator安全配置ssh二次验证登录_google-authenticator_04

Do you want to enable rate-limiting (y/n):y    
登录次数限制,30s内只允许3次错误

Google Authenticator安全配置ssh二次验证登录_google-authenticator_05

/root/.google_authenticator       手机密钥和应急码保存路径
Your verification code is 582849  手机客户端登录的密钥
Your emergency scratch codes are: 一些生成的5个应急码,每个应急码只能使用一次


此时再登录服务器,按照提示选择“keyboard Interactive”

Google Authenticator安全配置ssh二次验证登录_google_06

根据提示需要verification code,输入手机客户端对应的6位数字(注意:动态码的有效时间为5s,so动作要快)

Google Authenticator安全配置ssh二次验证登录_google_07

然后再输入服务器密码即可登录

Google Authenticator安全配置ssh二次验证登录_verification_08


本文附件有Android版本的 google_authenticator的身份验证器,请自行下载!