本文最初發表于我的個人站點
SSH 是什么
SSH 為 Secure Shell 的縮寫,由IETF的網絡工作小組(Network Working Group)所制定;SSH為建立在應用層和傳輸層基礎上的安全協議。SSH是目前較可靠,專為遠程登錄會話和其他網絡服務提供安全性的協議。利用SSH協議可以有效防止遠程管理過程中的信息泄露問題。SSH最初是UNIX系統上的一個程序,后來又迅速擴展到其他操作平臺。SSH在正確使用時可彌補網絡中的漏洞。SSH客戶端適用于多種平臺。幾乎所有UNIX平臺—包括HP-UX、Linux、AIX、Solaris、Digital UNIX、Irix,以及其他平臺,都可運行SSH。
更詳細的解釋可以參考 SSH百度百科
簡單來理解,就是我擁有一臺服務器,我現在想要登錄上去做一些事情,那就得使用ssh登錄到遠程的服務器上,才能在上面進行操作。
SSH 服務端以及客戶端配置
啟動 sshd 服務
一開始在遠程服務器上面,需要查看一下他的sshd服務啟動了沒有,如果沒有啟動,任何客戶端主機是連接不上來的,一般如果是自己在云廠商處購買了主機,主機啟動的時候就會把sshd服務啟動起來。但有可能自己在測試環境搭建機器的時候,是沒有默認啟動的,這時候就需要在測試機器的終端看一下,命令如下
wzy@wzt-dev2-PC:~$ ps -ef| grep sshd
root 861 1 0 7月03 ? 00:00:00 /usr/sbin/sshd -D
root 12838 861 0 18:42 ? 00:00:00 sshd: wzy [priv]
wzy 12866 12838 0 18:42 ? 00:00:00 sshd: wzy@pts/9
wzy 13158 13125 0 19:06 pts/9 00:00:00 grep --color=auto sshd
這里看到第一行,sshd已經啟動起來了,進程號是 861
如果沒有啟動的話,那就啟動一下,命令如下
root@wzt-dev2-PC:/home/wzy# service sshd start
命令執行完之后,再查看一下,這時看見已經啟動起來了
在第三行 ,進程號 13293
root@wzt-dev2-PC:/home/wzy# ps -ef| grep sshd
root 12838 1 0 18:42 ? 00:00:00 sshd: wzy [priv]
wzy 12866 12838 0 18:42 ? 00:00:00 sshd: wzy@pts/9
root 13293 1 0 19:11 ? 00:00:00 /usr/sbin/sshd -D
root 13310 13224 0 19:11 pts/9 00:00:00 grep --color=auto sshd
客戶端使用密碼的方式登錄目標主機
這里我在測試環境機器的ip是 192.168.0.187, 我在自己的電腦上想要登錄這臺機器,我要做的就是使用ssh命令去登錄192.168.0.187這臺主機
我需要告訴192.168.0.187這臺主機我以誰的身份去登錄, 192.168.0.187會詢問密碼,命令如下
? ~ ssh root@192.168.0.187
root@192.168.0.187's password:
敲入正確的密碼之后,我們就已經成功登錄了主機了
Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-83-generic x86_64)
* Documentation: https://help.ubuntu.com/
318 packages can be updated.
1 update is a security update.
You have new mail.
Last login: Fri Jun 30 14:18:16 2017 from 192.168.0.159
root@wzt-dev2-PC:~#
等進去之后可以看到一些歡迎詞,以及系統的信息,這些是可以自己定制的,這里就不展開了
客戶端使用密匙方式登錄目標主機
為什么有了密碼登錄,還需要密匙來登錄呢?我能想到的場景大概是:
如果某個運維人員臨時需要登錄一臺機器,但是機器的管理員并不想把密碼暴露給他,所以會讓這個運維人員發一個自己的公鑰給自己,幫他添加進去,這個運維人員就可以順利的登錄機器了。在運維做完了自己的事情之后,機器的管理員會把他從公鑰列表中刪掉,這樣一來整個過程,密碼沒有暴露,運維也在這段時間內登上了機器,很完美。
因為自己懶,不想敲密碼,想直接使用ssh_config和密匙對來登錄
使用ssh-keygen生成密匙對
命令 ssh-keygen -t [rsa|dsa]
這里RSA和DSA只是兩種不同的加密方式,詳細的區別可以看這篇博客 DSA和RSA的區別
? .ssh ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zhaochao/.ssh/id_rsa):foxchao
這里看到讓我輸入一個文件名字來保存密匙,我這里示例就輸入一個"foxchao"
? .ssh ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zhaochao/.ssh/id_rsa): foxchao
Enter passphrase (empty for no passphrase):
回車以后,詢問是否要輸入一個密碼來保護這個密匙,為了方便起見,我就不輸入了,不然每次使用這個密匙文件還要輸一遍密碼,直接一路回車就ok,如下所示
? .ssh ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/zhaochao/.ssh/id_rsa): foxchao
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in foxchao.
Your public key has been saved in foxchao.pub.
The key fingerprint is:
SHA256:cIeYcSCxgUjbMN+syODAM3VYiZ5/ zchao@zxhao.local
The key's randomart image is:
+---[RSA 2048]----+
|.= oB++.. |
|o Oo+= = . |
|o=.ooo+ E|
| o+ oo|
| .o o.. o oo|
| ...o.o++ ..o+|
+----[SHA256]-----+
到了這里,可以看到我們已經創建好了密匙對
? .ssh ll fox*
-rw------- 1 zhaochao staff 1.6K 7 17 19:32 foxchao
-rw-r--r-- 1 zhaochao staff 418B 7 17 19:32 foxchao.pub
使用密匙對登錄目標主機
將公鑰文件放到目標主機上,并添加進authorized_keys中
傳公鑰文件
現在我們新建了自己的密匙對之后,把foxchao.pub這個文件放到目標的機器上,加入目標機器的 authorized_keys 中就可以了,以后登錄的時候就可以免去輸入密碼的步驟。
那我們先用scp放上去 ,關于scp命令,這里不過多介紹,就是傳文件的一個命令,使用也比較簡單,具體想了解可以看這里Linux scp命令
? .ssh scp foxchao.pub root@192.168.0.187:~/
這里表示我要把foxchao.pub這個文件拷貝到192.168.0.187這臺機器root用戶的用戶目錄下
回車之后會詢問密碼,輸入密碼確認之后,文件就傳上去了,如下
? .ssh scp foxchao.pub root@192.168.0.187:~/
root@192.168.0.187's password:
foxchao.pub 100% 418 0.4KB/s 00:00
? .ssh
這時候我們先用密碼登上去看看傳上去沒有
? .ssh scp foxchao.pub root@192.168.0.187:~/
root@192.168.0.187's password:
foxchao.pub 100% 418 0.4KB/s 00:00
? .ssh ssh root@192.168.0.187
root@192.168.0.187's password:
Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-83-generic x86_64)
* Documentation: https://help.ubuntu.com/
318 packages can be updated.
1 update is a security update.
You have new mail.
Last login: Mon Jul 17 19:17:33 2017 from 192.168.0.115
root@wzt-dev2-PC:~# ls
dead.letter foxchao.pub php-5.6.9 php-5.6.9.tar.gz wzyadmin
root@wzt-dev2-PC:~#
可以看到foxchao.pub這個文件已經傳上來了
添加進authorized_keys
目標主機上如果沒有.ssh文件夾,就自己創建一個,創建好之后,再創建一個authorized_keys文件。如果有的話就不用了。
root@wzt-dev2-PC:~/.ssh# ll
total 8
drwxr-xr-x 2 root root 4096 7月 17 19:49 ./
drwx------ 10 root root 4096 7月 17 19:49 ../
-rw-r--r-- 1 root root 0 7月 17 19:49 authorized_keys
把剛才的foxchao.pub這個文件內容寫進authorized_keys
root@wzt-dev2-PC:~# cat foxchao.pub >> .ssh/authorized_keys
看一下,已經有內容了
root@wzt-dev2-PC:~# cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDwR8/Clov/rRfRkvpiKHVsHEQJKdSE +r4rbWKh0ce9Hz258Td6/bjq44yxb
這里需要注意
authorized_keys 文件對權限有喲求,必須是600(-rw——-)或者644
.ssh目錄 必須是700(drwx——),否則一會兒登錄不成功
弄完之后檢查一下權限,如果不是的話,改成響應的權限就ok了
準備就緒,在客戶端上登錄目標主機
在登錄之前,要確認一下目標主機是否允許密匙對登錄,一般都是打開的,如果沒有打開就自己打開
(查看 /etc/ssh/sshd_config 文件內容 中的 PubkeyAuthentication 這一項是否為 yes,如果不是就自己修改成yes之后重啟sshd服務 )
wzy@wzt-dev2-PC:~$ cat /etc/ssh/sshd_config
# Package generated configuration file
# See the sshd_config(5) manpage for details
# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes
# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024
# Logging
SyslogFacility AUTH
LogLevel INFO
# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile %h/.ssh/authorized_keys
# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes
# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes
# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
#MaxStartups 10:30:60
#Banner /etc/issue.net
# Allow client to pass locale environment variables
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes
? ~ ssh -i ~/.ssh/foxchao root@192.168.0.187
Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-83-generic x86_64)
* Documentation: https://help.ubuntu.com/
318 packages can be updated.
1 update is a security update.
You have new mail.
Last login: Mon Jul 17 19:46:30 2017 from 192.168.0.115
root@wzt-dev2-PC:~# exit
logout
Connection to 192.168.0.187 closed.
? ~ ssh -i ~/.ssh/foxchao root@192.168.0.187
Welcome to Ubuntu 16.04 LTS (GNU/Linux 4.4.0-83-generic x86_64)
* Documentation: https://help.ubuntu.com/
318 packages can be updated.
1 update is a security update.
You have new mail.
Last login: Mon Jul 17 20:01:25 2017 from 192.168.0.115
root@wzt-dev2-PC:~#
ssh 的-i用于指定私鑰登錄 , 這里可以看到我剛使用foxchao這個私鑰成功登錄了192.168.0.187這臺機器,并沒有讓我輸入密碼
客戶端使用ssh的config文件管理會話
為了避免繁瑣的每次都敲一長串 user@host 這樣的命令, 可以自己在.ssh 目錄下建一個config文件,文件內容如下,想要多了解一下配置參數使用的,可以看linux ssh_config和sshd_config配置文件
Host wzy-dev-1
Hostname 192.168.0.185
User wzy
ServerAliveInterval 60
ControlMaster auto
ControlPath /tmp/master-%r@%h:%p
ControlPersist yes
Host wzy-dev-2
Hostname 192.168.0.187
User wzy
ServerAliveInterval 60
ControlMaster auto
ControlPath /tmp/master-%r@%h:%p
ControlPersist yes
- Host 代表自己取的主機別名
- Hostname 填寫主機的ip地址
- User 登錄的用戶名
- ServerAliveInterval 60 #client每隔60秒發送一次請求給server,然后server響應,從而保持連接,避免操作一半就被服務器斷開
- ControlMaster 模式,可以復用之前已經建立的連接
- ControlPath 配合ControlMaster模式使用
- ControlPersist 配合ControlMaster模式使用
- Port 服務器主機指定的ssh服務端口,不寫默認就是22,可以自己填寫,因為有的主機為了安全考慮換了端口
- IdentityFile ~/.ssh/identity "IdentityFile"設置讀取用戶的RSA安全驗證標識,也就是之前說的密鑰對登錄方式,默認會去.ssh目錄下面去找私鑰,也可以自己指定
文件建立好之后,直接使用自己定義的別名登錄,非常方便快捷
? ~ ssh wzy-dev-1
Last login: Tue Jul 18 09:48:26 2017 from 192.168.0.115
wzy@wzy--dev1-pc ~ [10:44:59]
> $
服務端使用更安全的配置
如果是自己局域網搭建的機器,倒不用在意服務器的安全問題,但如果是暴露在公網上的機器,可以通過公網ip登錄的,一定要注意自己服務器的安全問題,最起碼不能開放默認端口,以及密碼登錄
在服務器上查看一下登錄的日志,可以看到很多想要嘗試登陸機器的人,所以公網上面的機器一定要做好自我保護
這里只列出一小部分的日志
[root@VM_centos ~]# cat /var/log/secure | grep "Failed password for root"
Jun 1 03:45:18 localhost sshd[2766]: Failed password for root from 180.169.47.94 port 49223 ssh2
Jun 1 03:45:20 localhost sshd[2770]: Failed password for root from 180.169.47.94 port 49393 ssh2
Jun 1 03:45:23 localhost sshd[2774]: Failed password for root from 180.169.47.94 port 49533 ssh2
Jun 1 03:45:25 localhost sshd[2778]: Failed password for root from 180.169.47.94 port 49661 ssh2
Jun 1 03:45:27 localhost sshd[2782]: Failed password for root from 180.169.47.94 port 49800 ssh2
Jun 1 03:45:30 localhost sshd[2786]: Failed password for root from 180.169.47.94 port 49926 ssh2
Jun 1 03:45:32 localhost sshd[2790]: Failed password for root from 180.169.47.94 port 50092 ssh2
Jun 1 03:45:34 localhost sshd[2794]: Failed password for root from 180.169.47.94 port 50223 ssh2
Jun 1 03:45:37 localhost sshd[2798]: Failed password for root from 180.169.47.94 port 50363 ssh2
Jun 1 03:45:39 localhost sshd[2802]: Failed password for root from 180.169.47.94 port 50522 ssh2
Jun 1 03:45:42 localhost sshd[2806]: Failed password for root from 180.169.47.94 port 50656 ssh2
Jun 1 03:45:44 localhost sshd[2810]: Failed password for root from 180.169.47.94 port 50822 ssh2
Jun 1 03:45:46 localhost sshd[2814]: Failed password for root from 180.169.47.94 port 50944 ssh2
Jun 1 03:45:49 localhost sshd[2818]: Failed password for root from 180.169.47.94 port 51061 ssh2
Jun 1 03:45:51 localhost sshd[2822]: Failed password for root from 180.169.47.94 port 51246 ssh2
Jun 1 03:45:54 localhost sshd[2826]: Failed password for root from 180.169.47.94 port 51383 ssh2
Jun 1 03:45:56 localhost sshd[2830]: Failed password for root from 180.169.47.94 port 51541 ssh2
Jun 1 03:45:59 localhost sshd[2834]: Failed password for root from 180.169.47.94 port 51695 ssh2
統計一下,可以看到有29190次登錄失敗的記錄
[root@VM_23_114_centos ~]# cat /var/log/secure | grep "authentication failure" -c
29190
我們改掉默認的端口,以及禁用密碼登錄,只支持密匙對登錄,這樣一來,提高了服務器本身的安全性,至少沒那么容易被別人登錄上來為所欲為。
在服務器上修改sshd的配置文件
[root@VM_centos ~]# vim /etc/ssh/sshd_config
- 找到 Port,修改為其他端口
# $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/local/bin:/bin:/usr/bin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options change a
# default value.
Port 12345
#AddressFamily any
# Disable legacy (protocol version 1) support in the server for new
# installations. In future the default will change to require explicit
# activation of protocol 1
Protocol 2
- 找到 PasswordAuthentication, 設置為no
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication no
- 找到 PubkeyAuthentication, 確保為yes,不然一會兒自己把自己鎖在外面了
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
#RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
保存之后,重啟sshd服務
root@wzt-dev2-PC:/home/wzy# service sshd restart
使用自己定義的端口登錄
? ~ ssh -p 12345 root@192.168.0.187 -i ~/.ssh/foxchao
-p 指定端口 -i 指定私鑰文件