如何在 Ubuntu 16.04 LTS 上使用两因素身份验证来保护 SSH

在本教程中,我们将向您展示如何在 Ubuntu 16.04 LTS 上使用双重身份验证来保护 SSH。 对于那些不知道的人,使用 Google Authenticator 使用双因素身份验证保护 SSH 两步验证(也称为双因素身份验证,缩写为 TFA)是一个涉及两个阶段来验证实体身份的过程试图访问计算机或网络中的服务。 这是多因素身份验证的一种特殊情况,可能只涉及两个步骤的三个身份验证因素(知识因素、拥有因素和继承因素)中的一个。

本文假设您至少具备 Linux 的基本知识,知道如何使用 shell,最重要的是,您将网站托管在自己的 VPS 上。 安装非常简单,假设您在 root 帐户下运行,如果不是,您可能需要添加 ‘sudo‘ 到命令以获取 root 权限。 我将向您展示在 Ubuntu 16.04 (Xenial Xerus) 服务器上使用双因素身份验证的分步安全 SSH。

先决条件

  • 运行以下操作系统之一的服务器:Ubuntu 16.04,以及任何其他基于 Debian 的发行版,如 Linux Mint。
  • 建议您使用全新的操作系统安装来防止任何潜在问题。
  • 对服务器的 SSH 访问(或者如果您在桌面上,则只需打开终端)。
  • 一种 non-root sudo user或访问 root user. 我们建议充当 non-root sudo user,但是,如果您在充当 root 时不小心,可能会损害您的系统。

在 Ubuntu 16.04 LTS 上使用两因素身份验证保护 SSH

步骤 1. 首先,通过运行以下命令确保所有系统包都是最新的 apt-get 终端中的命令。

sudo apt-get update sudo apt-get upgrade

步骤 2. 安装 Google Authenticator。

要在 Ubuntu 上安装该软件包,请运行以下命令:

apt-get install libpam-google-authenticator

下一步是获取验证码。 这是一个非常简单的命令,只需回答他会问你的服务器的简单问题,即可获取验证码和暂存码。 您可以通过运行以下命令来执行该步骤:

google-authenticator

系统将提示您回答几个问题; 用是 (y) 回答前两个问题:

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

一个大二维码将在您的终端中生成。 您可以使用 Android/iOS/Windows 手机或平板电脑上的验证器应用程序扫描代码或输入屏幕上生成的密钥。

还将生成紧急刮码。 如果您丢失了移动设备,您可以使用这些代码进行身份验证:

Your emergency scratch codes are: 80461001 68335920 89765548 12485672 11145603

Save 通过对下一个问题回答“是”来设置 root 用户的身份验证设置:

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

接下来,您可以配置身份验证器以生成一次性密码。 在最后 30 秒内,所有生成的密码都可以使用一次。 回答 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

恭喜! 您已完成生成密钥并将其添加到客户端,但在这些设置生效之前需要进行一些额外的配置。

下一步是在 openSSH 中配置身份验证设置。 为此,请打开“/etc/pam.d/sshd”文件并在文件末尾添加以下行:

### nano /etc/pam.d/sshd auth required pam_google_authenticator.so

Save 更改,打开“/etc/ssh/sshd_config”文件并启用质询-响应身份验证:

### nano /etc/ssh/sshd_config ChallengeResponseAuthentication yes

最后,保存文件并重新启动 SSH 服务器以使更改生效:

systemctl restart ssh

恭喜! 您已成功保护 SSH。 感谢您使用本教程在 Ubuntu 16.04 LTS (Xenial Xerus) 系统上使用两因素身份验证来实现安全 SSH。 如需其他帮助或有用信息,我们建议您查看 SSH 官方网站.

Save

Save