Hugh's Blog

SSH 添加两步验证

为了服务器安全,一般都会使用密钥登录,但是有时候换到其他的电脑上进行登录就不方便了,有个简单的做法是在 SSH 登录时多加一层验证:Two-factor authentication (2FA),配置过程很简单,作个记录。

安装 Google’s PAM

sudo apt-get update
sudo apt-get install libpam-google-authenticator

PAM 设置

# 开始设置

# 询问,是否启用基于时间的一次性密码验证,选择 y
Do you want authentication tokens to be time-based (y/n)

# 询问,是否在用户目录下更新验证文件,选择 y
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)

# 询问,是否延长口令验证时间,避免客户端与服务器时间误差,除非时间同步很差,否则选择 n
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)

# 询问,是否限制尝试次数,防止暴力攻击,选择 y
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)

# 设置完成,接下来用户目录下会多出一个文件 ~/.google_authenticator

SSH 配置

sudo vim /etc/pam.d/sshd
# 添加到文件最后
auth required

sudo vim /etc/ssh/sshd_config
# 修改 no 为 yes
ChallengeResponseAuthentication yes
# 注意,下面两行非必需
# 允许公钥或者 2FA 登录
AuthenticationMethods publickey keyboard-interactive:pam
# 必须要公钥以及 2FA 验证通过才能登录
AuthenticationMethods publickey,keyboard-interactive:pam

# 重启服务
sudo service ssh restart


How To Set Up Multi-Factor Authentication for SSH on Ubuntu 16.04