Linux_SSH服務(wù)器只允許Key建立連接
1. 創(chuàng)建 SSH KEY
使用ssh-keygen生成一個(gè)密鑰對(duì),并且將公鑰注冊(cè)到服務(wù)器的 $HOME/.ssh/authorized_keys 文件。
2. 確保啟用 SSH 公鑰認(rèn)證功能
查看 /etc/ssh/sshd_config 文件,確保以下兩條為 yes:
RSAAuthentication yes
PubkeyAuthentication yes
一般它們默認(rèn)都是 yes,如果不是,請(qǐng)修改為 yes,保存并且重啟 SSH 服務(wù):
$ sudo service ssh reload
3. 禁止密碼安全驗(yàn)證
編輯 /etc/ssh/sshd_config 文件,確保以下內(nèi)容出現(xiàn)在文件中:
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
保存并重啟 SSH 服務(wù):
$ sudo service ssh restart
如果你當(dāng)前處于 SSH 連接登錄狀態(tài),可能重啟服務(wù)會(huì)失敗,可以嘗試重啟系統(tǒng)。
4. 禁止特定條件使用密碼登錄
有時(shí)我們并不想禁止所有用戶的口令登錄,可以通過(guò)配置 sshd_config 文件來(lái)實(shí)現(xiàn)對(duì)特定對(duì)象的登錄設(shè)置。
使用 $ man sshd_config 查看幫助信息。sshd_config 支持在文件中增加 Match 區(qū)塊,如果 Match 關(guān)鍵字所在行的條件匹配成功,則 Match 后所有的關(guān)鍵字將被逐個(gè)加載,直到遇見另一個(gè) Match 關(guān)鍵字或者文件結(jié)尾。所以一般 Match 區(qū)塊添加在 sshd_config 文件末尾。
Match 關(guān)鍵字支持的條件包括 User, Group, Host 和 Address,條件樣式是單個(gè)字符串,多個(gè)樣式使用逗號(hào)分隔,也可以使用通配符(*)和求反符號(hào)(!)。
Address 條件樣式可以是 CIDR(地址/掩碼)格式,例如:192.0.2.0/24 或 3ffe:ffff::/32。
例如
禁止用戶 foo,用戶組 bar 使用口令登錄,在 /etc/ssh/sshd_config 文件末尾添加以下內(nèi)容:
Match User foo, Group bar
PasswordAuthentication no
禁止除用戶 foo 以外其他用戶使用口令登錄:
Match User *, !foo
PasswordAuthentication no
Match 區(qū)塊支持的關(guān)鍵字包括:
AllowAgentForwarding, AllowTcpForwarding, AuthorizedKeysFile,
AuthorizedPrincipalsFile, Banner, ChrootDirectory, ForceCommand,
GatewayPorts, GSSAPIAuthentication, HostbasedAuthentication,
HostbasedUsesNameFromPacketOnly, KbdInteractiveAuthentication,
KerberosAuthentication, MaxAuthTries, MaxSessions, PasswordAuthentication,
PermitEmptyPasswords, PermitOpen, PermitRootLogin, PermitTunnel,
PubkeyAuthentication, RhostsRSAAuthentication, RSAAuthentication,
X11DisplayOffset, X11Forwarding, X11UseLocalHost.