ssh密钥登陆

ssh密钥登陆

创建密钥对

使用命令ssh-keygen

┌──(kali㉿kali)-[~]
└─$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/kali/.ssh/id_rsa):  
Created directory '/home/kali/.ssh'.
//这里提示是否要口令,直接回车就不需要密码验证
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/kali/.ssh/id_rsa
Your public key has been saved in /home/kali/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:r1yPaIzk0ez5IY8HKKAawT43hVX7fqZkArJf9geezOc kali@kali
The key's randomart image is:
+---[RSA 3072]----+
|      ..         |
|     .  .        |
|.   o  .         |
|.... .  .        |
|.o o.. +S.       |
|oo o+ = =o       |
|..o..+ O=**o     |
|.   . =.X%=*     |
|     . .==BE.    |
+----[SHA256]-----+

之后密钥对就生成在home目录对应用户目录下了

┌──(kali㉿kali)-[~/.ssh]
└─$ ls
id_rsa  id_rsa.pub

将公钥放到要登陆的机子上

这对密钥是可以作为任意两台机子的验证密钥,而不是单单这一台

所以明确自己要登陆的是哪台机子,把公钥传到远程机子上

私钥保留在自己操作的机子上

这里我要登陆的是kali机,公钥本来就在这里生成的所以不用碰

要做就是将公钥添加到authorized_keys

┌──(kali㉿kali)-[~/.ssh]
└─$ cat id_rsa.pub >> ~/.ssh/authorized_keys
                                                                                   
┌──(kali㉿kali)-[~/.ssh]
└─$ ls
authorized_keys  id_rsa  id_rsa.pub

赋予权限

chmod 600 ~/.ssh/authorized_keys

启用公钥认证机制

查看kali机配置sshd_config

┌──(kali㉿kali)-[~/.ssh]
└─$ sudo vi /etc/ssh/sshd_config

启用下面这一项

PubkeyAuthentication yes       # 公钥登录 

保存退出,重启ssh

┌──(kali㉿kali)-[~/.ssh]
└─$ /usr/sbin/sshd restart
Extra argument restart.

成功登陆

Xshell

把私钥下载到本地

下载后要保存好不能让别人知道

登陆的时候就用这个私钥文件

image-20220908090752050

成功登陆

image-20220908090928183

Linux terminal

还是把私钥下载到本地

ssh -i path/id_rsa root@172.20.10.11

注意

安全起见就不能给id_rsa太大的权限,不然别的用户就可以随意看私钥

连接时会被提醒

“Permissions 0644 for ‘/root/.ssh/id_rsa’ are too open”
要你输密码验证之类的

权限太大就会触发ssh的保护机制

更改权限为600即可

成功登陆

┌──(rootkali)-[~]
└─# ssh -i id_rsa kali@172.20.10.11
Linux kali 5.10.0-kali9-amd64 #1 SMP Debian 5.10.46-4kali1 (2021-08-09) x86_64

The programs included with the Kali GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Kali GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Sep  7 21:11:56 2022 from 172.20.10.12
┏━(Message from Kali developers)
┃
┃ We have kept /usr/bin/python pointing to Python 2 for backwards
┃ compatibility. Learn how to change this and avoid this message:
┃ ⇒ https://www.kali.org/docs/general-use/python3-transition/
┃
┗━(Run: “touch ~/.hushlogin” to hide this message)
┌──(kali㉿kali)-[~]
└─$ 

拓展

linux主机通过ssh每连接一个新的机子,就会在~/.ssh/known_hosts 文件下添加该新机子的公钥,在下一次连接该机子时会核对公钥。如果公钥不同,OpenSSH会发出警告, 避免你受到DNS Hijack之类的攻击

posted @ 2022-09-09 11:47  DAMOXILAI  阅读(693)  评论(0编辑  收藏  举报