最近在研究自動登陸的linux伺服器的東西。本篇為關於ssh的秘鑰自動登陸。
update:2014.3.9 4:21 PM,昨晚寫完這篇之後,發現IBM的網上有篇關於ssh認證的完整描述。傷心了。。
https://www.ibm.com/developerworks/cn/linux/security/openssh/part1/
猜想:linux的秘鑰產生與伺服器無關,只和加密的方式(採用rsa或dsa)還有passphrase(密碼短語,在產生秘鑰的時候輸入的)有關。
如果是這樣的話,同一對秘鑰可以使用在多台伺服器上,因為對於伺服器和用戶端來說,他們在通訊的時候只需驗證秘鑰和公開金鑰是否匹配。
即存在一個global的公開金鑰存放在ssh伺服器上,而多台用戶端則使用的同一秘鑰登陸ssh伺服器上。
測試環境:本機windows使用secureCRT用戶端,兩台redhat 6.3的虛擬機器(linuxA和B,192.168.1.2/3)。虛機與主機使用橋接網路,處於同一區域網路。
測試過程:
註:公開金鑰一般是pub結尾,但是伺服器驗證的檔案是authorized_key,所以要把pub檔案的內容轉入authorized_key。pub檔案本身沒用。
1、使用CRT產生秘鑰對,將公開金鑰上傳到linuxA,成功登陸後,cpoyA機中的公開金鑰至B機中,實現CRT自動登陸B機,驗證公開金鑰為通用。
首先使用CRT產生秘鑰:
1.使用SecureCRT建立私密金鑰和公開金鑰(Set Passphrase 可以設定為空白密碼,比較方面驗證)SecureCRT: Quick Connect -> Authentiation -> Public Key -> Properties -> Create Identity File -> DSA/RSA -> Set Passphrase -> Done這個時候在指定目錄會產生兩個檔案,例如,私密金鑰my_rsa和公開金鑰my_rsa.pub2.linux伺服器上建立.ssh目錄,一般情況下,已經有這個目錄(更改許可權很重要,認證的時候許可權不是700不給通過)# mkdir /root/.ssh# chmod 700 /root/.ssh3.將公開金鑰 my_rsa.pub 傳到linux伺服器,將SSH2相容格式的公開金鑰轉換成為Openssh相容格式(一般情況是ssh2,不排除ssh1)# ssh-keygen -i -f Identity.pub >> /root/.ssh/authorized_keys2# chmod 600 /root/.ssh/authorized_keys24.在SecureCRT裡面設定登入模式為PublicKey,並選擇剛剛建立的my_rsa檔案作為私密金鑰5.重啟Linux伺服器上SSH伺服器(測試貌似不用重啟服務也能生效)
#service sshd restart 或者 /etc/rc.d/init.d/sshd restart
此階段,測試成功,A和B機使用的同一對authorized_keys2,CRT都能實現自動登陸。
2、在B機中產生秘鑰對,將公開金鑰複製到A中,實現B機自動登陸A,然後將B的秘鑰傳過去,把A的authorized_keys2內容寫入B的authorized_keys2檔案中,實現A自動登陸B。
步驟1: 用 ssh-key-gen 在本地主機上建立公開金鑰和密鑰
local-host$ ssh-keygen -t rsa
Enter file in which to save the key (/home/jsmith/.ssh/id_rsa):[Enter key]
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Pess enter key]
Your identification has been saved in /home/jsmith/.ssh/id_rsa.
Your public key has been saved in /home/jsmith/.ssh/id_rsa.pub.
The key fingerprint is: 33:b3:fe:af:95:95:18:11:31:d5:de:96:2f:f2:35:f9
local-host
步驟2: 用 ssh-copy-id 把公開金鑰複製到遠程A主機上
local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.2
remote-host‘s password:
Now try logging into the machine, with ―ssh ?remote-host‘‖, and check in:
.ssh/authorized_keys to make sure we haven‘t added extra keys that you weren‘t expecting.
[注: ssh-copy-id 把密鑰追加到遠程主機的 .ssh/id_rsa 上.]
步驟3: 直接登入A遠程主機
local-host$ ssh root@192.168.1.2
Last login: Sat Mar 8 12:37:48 2014 from 192.168.1.3
[注: SSH 不會詢問密碼.]
然後通過sftp,將B機的id_rsa傳到A機,把A的authorized_keys2傳過來。此時A和B都可互相自動登陸。
測試結果:驗證猜想成功,最好是有第三台linux再可以驗證下就好了。
補充安全問題:由於.ssh檔案夾和privatekey都許可權為700和600,同時sftp伺服器只開通sftp登陸許可權和控制home檔案目錄,只要妥善保管privatekey,在ssh協議下是沒有安全顧慮的。參見SSH認證原理(http://qujunorz.blog.51cto.com/6378776/1371344)
本文出自 “hiubuntu” 部落格,請務必保留此出處http://qujunorz.blog.51cto.com/6378776/1370921