Enable 2-fator-authentication for SSH

服务器系统为 Ubuntu server 16.04,服务器密码使用 Keepass 管理,每次登录都要复制粘贴觉得挺麻烦的,而且云服务器 SSH 超时时间很短,稍微溜号就要重新连接。

今天参照 DO 的教程给服务器的 SSH 开启双因素验证,然后把密码修改成了自己能记住的常用密码,这下登录方便多了。

Step 1 — Installing Google's PAM

安装谷歌 pam 验证库:

$ sudo apt-get install libpam-google-authenticator


$ google-authenticator

接下来是一系列交互式问题,首先询问验证令牌是否是 基于时间 的?

Do you want authentication tokens to be time-based (y/n) y

紧接着,终端会显示一个大大的二维码以及相关的秘钥和验证码信息,用手机端的谷歌验证 APP 扫描二维码即可。



Do you want me to update your "~/.google_authenticator" file (y/n) y


Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y


By default, tokens are good for 30 seconds and in order to compensate for
possible time-skew between the client and the server, we allow an extra
token before and after the current time. If you experience problems with poor
time synchronization, you can increase the window from its default
size of 1:30min to about 4min. Do you want to do so (y/n) n

询问是否启用错误尝试次数限制?启用的话,每 30 秒仅允许尝试登录 3 次。

If the computer that you are logging into isn't hardened against brute-force
login attempts, you can enable rate-limiting for the authentication module.
By default, this limits attackers to no more than 3 login attempts every 30s.
Do you want to enable rate-limiting (y/n) y

提示:完成上述设置后,最好备份一下 ~/.google_authenticator 配置文件,以便于二次部署和故障恢复。

Step 2 — Configuring OpenSSH


$ sudo nano /etc/pam.d/sshd

在配置文件的最下面添加一行 auth required pam_google_authenticator.so nullok

. . .
# Standard Un*x password updating.
@include common-password
auth required pam_google_authenticator.so nullok

The nullok word at the end of the last line tells the PAM that this authentication method is optional. This allows users without a OATH-TOTP token to still log in using their SSH key. Once all users have an OATH-TOTP token, you can remove nullok from this line to make MFA mandatory.


$ sudo nano /etc/ssh/sshd_config

找到 ChallengeResponseAuthentication 设置为 yes

重启 SSH 服务即可。