SSH 密钥

SSH 密钥基于公钥加密,我们将生成一个包含公钥和私钥的密钥对。
公钥存储在我们希望访问的目标服务器上,并且只允许相应的私钥访问。

因此保护私钥非常重要,如果攻击者能够访问此密钥,那么他们将能够以用户身份登录。
最佳实践规定私钥使用密码加密,我们可以在创建密钥对时配置该密码。
同样重要的是,私钥文件只能由拥有密钥的用户读取和写入,这将是权限 0600,并在创建时设置为默认值。

要创建密钥对,请以要为其生成密钥对的用户身份运行“ssh-keygen”命令,例如,作为 root 用户,我们可以通过首先使用“su bob”更改为 bob 来为 bob 生成密钥,然后运行 'ssh-keygen' 如下。
-t 标志指定要创建的密钥类型,这里我们使用 rsa 版本 2.

[jack@onitroad ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/bob/.ssh/id_rsa):
Created directory '/home/bob/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/bob/.ssh/id_rsa.
Your public key has been saved in /home/bob/.ssh/id_rsa.pub.
The key fingerprint is:
8e:dc:08:bb:8d:0e:12:04:22:ae:5e:f5:0a:21:3e:b0 jack@onitroad
The key's randomart image is:
+--[ RSA 2048]----+
|+                |
|=                |
|.+ . .           |
|=.. o .          |
|Eo o.  .S        |
|..o .+.=         |
|... ..+ o        |
| . . +           |
|   .+ .          |
+-----------------+
[jack@onitroad ~]$ ls -la /home/bob/.ssh/
-rw-------. 1 bob bob 1766 Aug 19 16:41 id_rsa
-rw-r--r--. 1 bob bob  398 Aug 19 16:41 id_rsa.pub

在上面的例子中,我们创建了 id_rsa 私钥文件和对应的 id_rsa.pub 公钥文件。

接下来将公钥上传到我们要访问的远程服务器,这可以手动完成,也可以使用 ssh-copy-id 命令完成,如下所示。
请注意, ssh-copy-id 命令将要求我们上传公钥的帐户已经具有对目标服务器的 SSH 访问权限。

[jack@onitroad .ssh]$ ssh-copy-id jack@onitroad
The authenticity of host '1.2.3.4' can't be established.
ECDSA key fingerprint is 97:b6:fc:11:49:20:3c:10:ac:16:49:46:e5:56:03:30.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
jack@onitroad's password:
Number of key(s) added: 1
Now try logging into the machine, with:   "ssh 'jack@onitroad'"
and check to make sure that only the key(s) you wanted were added.

这会将 id_rsa.pub 公钥文件放置在目标服务器上,在本例中 位于“1.2.3.4”上的 ~/.ssh/authorized_keys 文件中,然后我们只需运行“ssh jack@onitroad”即可通过 SSH 连接到目标服务器如果我们设置了私钥,系统会提示我们输入私钥的密码。

如果我们为其创建公钥的用户没有对目标服务器的 SSH 访问权限,则另一个用户需要将其放置在 ~/.ssh/authorized_keys 文件中所需的用户主目录中,ssh-copy-id 只是一个通过 SSH 为我们执行此操作的脚本。

设置帐户以使用 SSH 密钥而不是密码后,我们可以选择通过 /etc/ssh/sshd_config 禁用密码身份验证以提高安全性,如下所示。

PasswordAuthentication no
PubkeyAuthentication yes

要应用这些更改,请确保重新启动 sshd 服务。

systemctl restart sshd
如何为 SSH 配置基于密钥的身份验证

SSH 密钥可用于提高用户通过 SSH 远程验证 Linux 服务器的安全级别。
与密码相比,SSH 密钥在安全性方面通常更可取,因为它们更不容易受到蛮力攻击,密钥中的熵比密码大得多。

在这里,我们将介绍如何在 Linux 中为 SSH 配置和使用基于密钥的身份验证。
本示例中的测试服务器运行的是 CentOS 7.

日期:2020-07-07 20:54:37 来源:oir作者:oir