翻一下你的 SSH 日誌,大概會看到滿滿的惡意嘗試登入。以下五條建議(含幾個稍有爭議的特例)能讓你的 OpenSSH 會話更難被攻破。
密碼登入很方便,任何地方任何機器都能用,缺點是抵不住暴力破解。可以這樣補強:
pwgen 12 產生 12 字元的密碼。# 一律寫成 *。看到 Too many authentication failures for carla 這行錯誤時總有點惱人。解法是在用戶端的 ~/.ssh/config 強制走密碼登入。若檔案不存在,先建目錄:
$ mkdir ~/.ssh $ chmod 700 ~/.ssh
然後建立 ~/.ssh/config,寫入(把 HostName 換成你的遠端網域):
HostName remote.site.com PubkeyAuthentication=no
這個錯誤的成因是:你的 .ssh 目錄裡放了太多私鑰,而 ssh 用戶端在沒有指定 -i 時會逐一嘗試,全部失敗後才提示輸入密碼,一下就超出伺服器允許的嘗試次數。更精準的做法是登入時加上 -o PubkeyAuthentication=no,而不是全域停用公鑰認證——畢竟下面兩條建議正好與此相反,請視情境取舍。
公鑰認證比密碼安全得多,因為它完全不受暴力破解影響;代價是依賴 RSA 密鑰對,便利性下降。流程是:先產生密鑰對,私鑰留在用戶端,公鑰複製到要登入的伺服器。只有持有私鑰的機器才能登入。私鑰的敏感度等同你家門鑰匙,任何人拿到就是拿到你的帳號,所以強烈建議為私鑰設定 passphrase。
用 RSA 密鑰對管理多用戶也很好用:某個成員離開時,只要從伺服器刪掉他的公鑰,權限立刻撤銷。
以下產生一組 3072 位元的密鑰(比預設 2048 更強),並取個能辨識用途的名字:
$ ssh-keygen -t rsa -b 3072 -f id_mailserver
會得到 id_mailserver(私鑰,千萬別外傳)與 id_mailserver.pub(公鑰)。接著用 ssh-copy-id 安全地安裝公鑰——前提是你在遠端已有可用的登入方式:
$ ssh-copy-id -i id_mailserver.pub user@remoteserver /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed user@remoteserver's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'user@remoteserver'" and check to make sure that only the key(s) you wanted were added.
ssh-copy-id 會避免你誤傳私鑰。接著照它輸出的提示(記得帶單引號)測試:
$ ssh 'user@remoteserver'
若你為私鑰設了 passphrase,這裡會要求輸入。
確認公鑰登入無誤後,就可以把密碼登入關掉,讓暴力破解徹底失效。編輯遠端的 /etc/sshd_config:
PasswordAuthentication no
然後重啟 SSH 服務。建議在同一個已建立的會話中先驗證新設定,再關閉舊會話,避免把自己鎖在外面。
與其每次敲:
ssh -u username -p 2222 remote.site.with.long-name
不如直接 ssh remote1。在用戶端的 ~/.ssh/config 這樣寫:
Host remote1
HostName remote.site.with.long-name
Port 2222
User username
PubkeyAuthentication no
若使用公鑰登入,改成:
Host remote1
HostName remote.site.with.long-name
Port 2222
User username
IdentityFile ~/.ssh/id_remoteserver
OpenSSH 的文件很長也很細,但掌握基礎規則之後,你會發現它是工具箱裡最有價值的一支,還藏著不少有趣的效果。