OpenSSH(OpenBSD Secure Shell)是使用 安全外殼協議(SSH),在計算機網絡上提供加密通信會話的軟體集。它是 SSH Communications Security 專有 SSH 軟體的開源替代方案。OpenSSH 是 OpenBSD 項目的一部分,該項目由 Theo de Raadt 領導。
OpenSSH 有時候會與名字相似的 OpenSSL 相混淆;然而,它們的目的不同,開發團隊也不同,名字相似只因為兩者目標相似。
安裝
客戶端用法
連接伺服器:
$ ssh -p 端口 用户名@服务器地址
如果伺服器只允許公鑰認證,參考 SSH 密鑰。
配置
客戶端可以配置一些通用的參數和主機信息。所有的參數都可以全局配置或者限制為特定主機,例如:
~/.ssh/config
# 全局選項 User 用戶名 # 特定於主機的選項 Host myserver Hostname 伺服器地址 Port 埠
配置之後,下面的兩條命令是等價的:
$ ssh -p 端口 用户名@服务器地址 $ ssh myserver
參考 ssh_config(5) 可以獲得更多的信息。
一些參數沒有對應的命令行選項,但你可以在命令行中使用 -o
指定配置選項。例如 -oKexAlgorithms=+diffie-hellman-group1-sha1
。
服務端用法
sshd
是 OpenSSH 伺服器守護程序,通過 /etc/ssh/sshd_config
配置並由 sshd.service
管理。每次更改配置後,請在重新啟動服務前在測試模式下運行 sshd
以確保它能夠乾淨地啟動。有效配置將不會產生輸出:
# sshd -t
配置
要僅允許某些用戶訪問,請添加以下一行:
AllowUsers 用户1 用户2
要僅允許某些用戶組訪問:
AllowGroups 用户组1 用户组2
要添加漂亮的歡迎消息(例如,輸出 /etc/issue
文件),請配置 Banner
選項:
Banner /etc/issue
sshdgenkeys 服務會自動在 /etc/ssh
中生成缺失的任何算法的公鑰和私鑰,即使 sshd_config
中的 HostKeyAlgorithms
選項只允許部分加密算法。OpenSSH 提供了三種基於 ed25519、ecdsa 和 rsa 算法的密鑰對。要讓 sshd 使用特定的密鑰,請指定以下選項:
HostKey /etc/ssh/ssh_host_ed25519_key
如果伺服器要暴露在公網下,建議將默認埠從 22 更改為更高的隨機埠,例如:
Port 39901
- 要選擇尚未分配給常見服務的備用埠,請查看 TCP 和 UDP 埠號列表,還可以在本地的
/etc/services
中查找埠信息。更改 OpenSSH 所使用的埠有助於減少由攻擊者使用自動程序嘗試通過 SSH 登錄你的伺服器的情況(但無法徹底解決)。查看 Port knocking 了解相關內容。 - 建議完全禁用密碼登錄。這將大大提高安全性,更多信息請參見#強制公鑰認證。更多推薦的安全方法,請參閱#保護。
- OpenSSH 可以監聽多個埠,只需在配置文件中添加多行
Port 埠號
。 - 可以通過從
/etc/ssh
中刪除要替換的主機密鑰對並以 root 身份運行ssh-keygen -A
來生成新的(或缺失的)主機密鑰對。
管理守護程序
啟動/啟用 sshd.service
。它將保持 SSH 守護程序始終處於活動狀態,並為每個傳入連接 fork。
sshd.socket
,更多信息請參考 FS#62248。如果在更新到 openssh包 8.0p1-3 時啟用了 sshd.socket
,則 sshd.socket
和 sshd@.service
單元將被複製到 /etc/systemd/system/
並重新啟用。這樣做只是為了不破壞現有設置;仍然建議用戶遷移到 sshd.service
。sshd.socket
, 請注意下列問題:
-
sshd.socket
單元可能會失敗 (例如:在內存耗盡的情況下) 並且Restart=always
不能被用於 socket 單元. 點擊 systemd issue 11553 了解更多內容。 - 使用套接字激活會導致拒絕服務,因為太多的連接會導致拒絕進一步激活服務。見 FS#62248。
sshd.socket
使得 ListenAddress
設置失效,因此它會允許連接任意地址。為了使 ListenAddress
設置起作用,你必須編輯 sshd.socket
來為 ListenStream
指定埠和IP(例如 ListenStream=192.168.1.100:22
)。你還必須在 [Socket]
添加 FreeBind=true
,否則設置 IP 地址會有 ListenAddress
設置一樣的缺點:如果網絡沒有及時啟動,套接字會啟動失敗。sshd@.service
的瞬態實例(實例名稱會不同)。因此,不論是 sshd.socket
還是守護進程常規的 sshd.service
都會不被允許在日誌中監控連接嘗試。可以通過 root 運行 journalctl -u "sshd@*"
或者 journalctl /usr/bin/sshd
查看 SSH 套接字激活實例的日誌。保護
允許通過 SSH 遠程登錄有利於管理,但可能會威脅伺服器的安全。由於 SSH 訪問通常是暴力攻擊的目標,因此需要適當限制 SSH 訪問以防止第三方訪問伺服器。
ssh-audit包 提供對服務端和客戶端配置的自動分析。關於這個主題,還有其他幾個很好的指南和工具,例如:
強制公鑰認證
如果客戶端無法通過公鑰進行身份驗證,SSH 服務端默認會退回到使用密碼進行身份驗證,從而允許惡意用戶嘗試通過暴力窮舉密碼來獲取訪問權限。防止這種攻擊的最有效方法之一是完全禁用密碼登錄,並強制使用 SSH 密鑰。這可以通過在守護程序配置文件中設置以下選項來完成:
/etc/ssh/sshd_config.d/20-force_publickey_auth.conf
PasswordAuthentication no AuthenticationMethods publickey
authorized_keys
文件中設置了公鑰身份驗證。詳細信息請參閱 SSH 密鑰#將公鑰複製到遠程伺服器上。雙重身份認證和公鑰
SSH 可以被設置成需要多重驗證。你可以通過 AuthenticationMethods
選項指定使用哪些驗證方式,這將同時啟用公鑰和雙重驗證。
身份驗證提供程序
設置 Google 身份驗證器的方法請查看 Google 身份驗證器。
對於 Duo,安裝提供 pam_duo.so
模塊的包 duo_unixAUR 。閱讀 Duo Unix 文檔以了解如何設置 Duo 憑據(Integration Key,密鑰和 API 主機名)。
PAM 設置
要在 OpenSSH 中使用 PAM,請編輯下列文件:
/etc/ssh/sshd_config.d/20-pam.conf
KbdInteractiveAuthentication yes AuthenticationMethods publickey keyboard-interactive:pam
然後你可以通過公鑰或在 PAM 中設置的用戶身份驗證方法登錄。
另一方面,如果您想要根據 PAM 設置的要求使用公鑰和用戶身份驗證對用戶進行驗證,請使用逗號而不是空格來分隔 AuthenticationMethods:
/etc/ssh/sshd_config.d/20-pam.conf
KbdInteractiveAuthentication yes AuthenticationMethods publickey,keyboard-interactive:pam
為了要求同時使用公鑰和 pam 身份驗證,您可能希望禁用密碼登錄:
/etc/pam.d/sshd
auth required pam_securetty.so #disable remote root #Require google authenticator auth required pam_google_authenticator.so #But not password #auth include system-remote-login account include system-remote-login password include system-remote-login session include system-remote-login
防止暴力窮舉攻擊
暴力攻擊的概念非常簡單:使用大量隨機用戶名和密碼組合嘗試登錄網頁或類似 SSH 等服務。
請參考 ufw#連接速率限制,如果使用的是 iptables,請參考 Simple stateful firewall#Bruteforce attacks。
從 9.8 版本開始,OpenSSH 引入了類似 fail2ban 的基本保護實現:PerSourcePenalties
選項默認配置了一個合理值,會對同一地址上的客戶端針對各種條件進行懲罰,導致在一段時間內被拒絕連接。
另外,你也可以使用自動化腳本封禁任何嘗試暴力窮舉登錄的對象。
- 只允許可信源地址進行 SSH 連接
- 使用 fail2ban 或 sshguard 自動封禁多次密碼登錄失敗的 IP
- 使用 pam_shield 封禁一段時間內多次嘗試登錄的 IP。與 fail2ban 或 sshguard 不同,該程序不會對成功和失敗登錄請求進行區分。
限制root用戶登錄
It is generally considered bad practice to allow the root user to log in without restraint over SSH. There are two methods by which SSH root access can be restricted for increased security.
拒絕
Sudo selectively provides root rights for actions requiring these without requiring authenticating against the root account. This allows locking the root account against access via SSH and potentially functions as a security measure against brute force attacks, since now an attacker must guess the account name in addition to the password.
SSH can be configured to deny remote logins with the root user by editing the "Authentication" section in the daemon configuration file. Simply set PermitRootLogin
to no
:
/etc/ssh/sshd_config.d/20-deny_root.conf
PermitRootLogin no
Next, restart the SSH daemon.
You will now be unable to log in through SSH under root, but will still be able to log in with your normal user and use su or sudo to do system administration.
限制
Some automated tasks such as remote, full-system backup require full root access. To allow these in a secure way, instead of disabling root login via SSH, it is possible to only allow root logins for selected commands. This can be achieved by editing ~root/.ssh/authorized_keys
, by prefixing the desired key, e.g. as follows:
command="rrsync -ro /" ssh-ed25519 ...
This will allow any login with this specific key only to execute the command specified between the quotes.
The increased attack surface created by exposing the root user name at login can be compensated by adding the following to sshd_config
:
PermitRootLogin forced-commands-only
This setting will not only restrict the commands which root may execute via SSH, but it will also disable the use of passwords, forcing use of public key authentication for the root account.
A slightly less restrictive alternative will allow any command for root, but makes brute force attacks infeasible by enforcing public key authentication. For this option, set:
PermitRootLogin prohibit-password
對 authorized_keys 文件加鎖
If, for whatever reason, you think that the user in question should not be able to add or change existing keys, you can prevent them from manipulating the file.
On the server, make the authorized_keys
file read-only for the user and deny all other permissions:
$ chmod 400 ~/.ssh/authorized_keys
To prevent the user from simply changing the permissions back, set the immutable bit on the authorized_keys
file. To prevent the user from renaming the ~/.ssh
directory and creating a new ~/.ssh
directory and authorized_keys
file, set the immutable bit on the ~/.ssh
directory too. To add or remove keys, you will have to remove the immutable bit from authorized_keys
and make it writable temporarily.
authorized_keys
file via e.g auditd.SSH certificates
While common SSH keys and manual fingerprint verification may be easy to use with a handful of hosts that are managed by a single administrator, this method of authentication does not scale at all. When a number of servers need to be accessed through SSH by several users, manually verifying ssh public key fingerprints of every host becomes nearly impossible to do securely and reliably.
The solution for this is to use SSH certificates that provide automatic verification of public key identities through a chain of trust that scales significantly better than the default trust-on-first-use approach of SSH. SSH certificates are basically nothing else than normal public SSH keys, but with an additional signature from a trusted certificate authority that verifies the key identity.
Create a host certificate authority key for your infrastructure
$ ssh-keygen -t ed25519 -f ~/.ssh/ca_host_key -C 'Host certificate authority for *.example.com'
The private certificate authority key should be stored securely, ideally on a smartcard or hardware token that prevents key extraction like the Nitrokey or YubiKey.
Sign a server's public SSH host key
Copy the public server key to your local system containing the private certificate authority key to sign it:
$ ssh-keygen -h -s ~/.ssh/ca_key -I certLabel -n server01.example.com ./ssh_host_ed25519_key.pub
Move the new certificate and configure sshd to use it
The generated certificate ssh_host_ed25519_key-cert.pub
should be copied to the server at /etc/ssh/
.
/etc/ssh/sshd_config.d/20-ed25519_key.conf
HostCertificate /etc/ssh/ssh_host_ed25519_key-cert.pub
Configure all clients to trust the certificate authority
~/.ssh/known_hosts
@cert-authority *.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKL8gB/pjuff005YNazwMCqJpgsXAbQ3r4VStd/CRKwU Host certificate authority for *.example.com
SSH user certificates
Depending on the number of users and method of deployment, SSH User keys can also be used with Certificates. For organizations with many ssh users, this is strongly advised to manage User key deployment securely.
The deployment of user certificates works basically the same as for server identities. More details and instructions can be found at Wikibooks:OpenSSH/Cookbook/Certificate-based Authentication.
Certificate deployment automation
Automated deployment of SSH certificates can be provided by a number of open source tools. Popular examples are:
- Ansible - openssh_cert module
- privacyIDEA - authentication server
- Theo App - authorized keys manager
SSHFP record
The Secure Shell fingerprint record (SSHFP) is an optional resource record in the domain name system that associates SSH keys to a host name. It can be used to verify the SSH fingerprint on public servers by using DNSSEC instead of deploying trusted CA certificates, which allows even unmanaged clients to verify the validity of key fingerprints.
Generate record entry
To generate the required hexadecimal key fingerprint to be stored in the DNS record, create the hash on the target server.
$ ssh-keygen -r host.example.com
This will read all available SSH keys for the specified domain and output valid SSHFP records that can then be stored in the DNS entries of the affected domain.
Client configuration
In order to automatically retrive and trust SSH key fingerprints stored as SSHFP records, add the following to your ssh client configuration file:
~/.ssh/config
# global options Match all VerifyHostKeyDNS yes
If the target host has a valid SSHFP record and this record is verified with a valid DNSSEC signature, the fingerprint is automatically accepted without prompting the user to verify the hosts identity. In case the DNS record is not verified by DNSSEC, the user will be prompted to verify the fingerprint instead.
Generate SSHFP records
To determine the SSH fingerprint of a specific domain, use ssh-keyscan to retrieve the ssh fingerprints in a valid DNS record format. (Note that by default fingerprints for every available key type is provided as both SHA1 and SHA256.)
$ ssh-keyscan -D github.com
; github.com:22 SSH-2.0-babeld-57ca1323 ; github.com:22 SSH-2.0-babeld-57ca1323 github.com IN SSHFP 1 1 6f4c60375018bae0918e37d9162bc15ba40e6365 github.com IN SSHFP 1 2 b8d895ced92c0ac0e171cd2ef5ef01ba3417554a4a6480d331ccc2be3ded0f6b ; github.com:22 SSH-2.0-babeld-57ca1323 github.com IN SSHFP 3 1 3358ab5dd3e306c461c840f7487e93b697e30600 github.com IN SSHFP 3 2 a764003173480b54c96167883adb6b55cf7cfd1d415055aedff2e2c8a8147d03 ; github.com:22 SSH-2.0-babeld-57ca1323 github.com IN SSHFP 4 1 e9619e2ed56c2f2a71729db80bacc2ce9ccce8d4 github.com IN SSHFP 4 2 f83898df0bef57a4ee24985ba598ac17fccb0c0d333cc4af1dd92be14bc23aa5 ; github.com:22 SSH-2.0-babeld-57ca1323
Since the SSHFP record stores the key fingerprints as hexadecimal values while the common output for SSH fingerprints is the base64 encoded SHA256 hash of the public key, it is necessary to convert the record back to the base64 format in order to compare it with values in the known_hosts file or other documentation that commonly stores fingerprints as SHA256.
$ echo "SSHFP-fingerprint" | xxd -r -p | base64
Example for github.com using the hex value for the sha256 fingerprint of the key type ed25519
$ echo "f83898df0bef57a4ee24985ba598ac17fccb0c0d333cc4af1dd92be14bc23aa5" | xxd -r -p | base64
+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU=
Compare with known_hosts entries:
$ ssh-keygen -l -f ~/.ssh/known_hosts
Manually retrieve SSHFP records from DNS
$ dig SSHFP targetdomain.tld +short
小技巧
使用加密的 SOCKS 隧道
這對連接到各種不安全無線連接的筆記本電腦用戶非常有用。你唯一需要的是在一個比較安全的位置運行的 SSH 伺服器,比如你的家或工作地點。使用動態 DNS 服務可能很有用,如DynDNS,這樣你就不必記住你的 IP 地址。
步驟 1:開始連接
你只需要執行這一條命令就可以開始連接:
$ ssh -TND 4711 user@host
其中 user
是你在 host
上運行的 SSH 伺服器的用戶名。它將詢問你的密碼,然後建立連接。N
標誌禁用了交互式提示,D
標誌指定了監聽的本地埠(如果你願意,可以選擇任何埠號)。{Ic|T}} 標誌禁用偽終端分配。
可以添加 verbose(-v
)標誌,這樣就可以通過輸出驗證是否成功連接。
步驟 2 (方法 A):配置你的瀏覽器(或其它程序)
上述步驟僅與使用新創建的 SOCKS 隧道的網頁瀏覽器或其他程序結合使用時有用。SSH 現在同時支持 SOCKS v4 和 SOCKS v5,你可以選擇它們中的任意一種。
- 對於火狐瀏覽器:進入首選項 > 通用,跳到頁面底部並點擊網絡設置項右邊的設置...按鈕。接下來,在打開的二級窗口中,選中手動代理配置並在 SOCKS 主機名框內輸入
localhost
,並在旁邊的埠項輸入埠號(上述例子使用4711
)。
- 火狐不會自動通過 SOCKS 隧道發出 DNS 請求,該潛在隱私問題可通過選中頁面下方的使用 SOCKS v5 時代理 DNS 查詢解決。顯然,這只在使用 SOCKS v5 而不是 v4 時有效。
- 重啟火狐來應用設置。
- 對於 Chromium,可以將 SOCKS 設置為環境變量或通過命令行選項進行配置。例如,可以在
.bashrc
中添加以下函數:
function secure_chromium { port=4711 export SOCKS_SERVER=localhost:$port export SOCKS_VERSION=5 chromium & exit }
或者是
function secure_chromium { port=4711 chromium --proxy-server="socks://localhost:$port" & exit }
現在打開終端,然後執行:
$ secure_chromium
就可以使用安全隧道了!
步驟 2(方法 B):配置本地 TUN 接口
這種方法在前期稍微複雜,但以後無需手動配置每個應用程式來使用 SOCKS 代理,具體原理是建立一個本地 TUN 接口並通過該接口路由流量。
具體方法請參考 VPN over SSH#Set up badvpn and tunnel interface。
X11 轉發
使用 X11 轉發可以在本地客戶端上顯示遠程系統運行的 X11 程序圖形界面。對於 X11 轉發,遠程主機不需要安裝完整的 X11 環境,但至少要安裝 xauth。xauth是維護 Xauthority
配置的工具,該配置被服務端和客戶端用於認證 X11 會話(源)。
設置
服務端
- 安裝 xorg-xauth包
- 在
/etc/ssh/sshd_config
中:- 設置
X11Forwarding
為 yes - 檢查
AllowTcpForwarding
和X11UseLocalhost
選項是否已設為 yes,並且X11DisplayOffset
設為 10(未修改情況下是默認值,參考 sshd_config(5))
- 設置
- 然後重啟 sshd daemon.
客戶端
- 安裝 xorg-xauth包
- 啟用
ForwardX11
選項,可以在命令行中使用-X
選項,也可以在客戶端配置文件中設置ForwardX11
為 yes。
ForwardX11Trusted
選項(命令行下使用 -Y
),這會防止 X11 轉發受到 X11 SECURITY extension 的影響。在操作前,確保你已經看過警告信息。用法
正常登錄到遠程機器,如果客戶端的配置文件中沒有啟用 ForwardX11,則指定 -X
開關:
$ ssh -X user@host
如果你在試圖運行圖形應用程式時收到錯誤,請嘗試用 ForwardX11Trusted 代替:
$ ssh -Y user@host
如果出現 X11 forwarding request failed
報錯,則需要為你的遠程機器重新進行設置。一旦 X11 轉發請求成功,你可以在遠程伺服器上啟動任何 X 程序,它將被轉發到你的本地會話:
$ xclock
如果出現了 Can't open display
報錯,表示 DISPLAY
設置有誤。
對一些應用程式要小心,因為它們會檢查本地機器上是否有正在運行的實例。Firefox 就是一個例子:要麼關閉正在運行的 Firefox 實例,要麼使用下面的啟動參數在本地機器上啟動一個遠程實例:
$ firefox --no-remote
如果你在連接時出現「X11 forwarding request failed on channel 0」報錯(並且伺服器 /var/log/errors.log
顯示「Failed to allocate internet-domain X11 display socket」),請確保已安裝 xorg-xauth包。如果安裝了也還是不行,可以嘗試以下方法之一:
- 在服務端的
sshd_config
中啟用AddressFamily any
選項,或者 - 在服務端的
sshd_config
中將AddressFamily
選項設置為 inet。
將其設置為 inet 可能會解決 Ubuntu 客戶端在 IPv4 上的問題。
對於在 SSH 伺服器上以另一個用戶身份運行 X 應用程式,you need to xauth add
the authentication line taken from xauth list
of the SSH logged in user.
X11 轉發
排障可參考以下連結:
轉發其他埠
除了SSH對X11的內置支持外,它還可以通過本地轉發或遠程轉發使用安全隧道傳輸任何 TCP 連接。
本地轉發打開本地計算機上的一個埠,連接將被轉發到遠程主機,並從那裡轉發到給定的目的地。通常,轉發目的地將與遠程主機相同,從而為同一機器提供安全外殼,例如安全 VNC 連接。本地轉發會使用到 -L
選項,後接 <tunnel port>:<destination address>:<destination port>
格式的轉發規則。
因此:
$ ssh -L 1000:mail.google.com:25 192.168.0.100
將使用 SSH 進行登錄到 192.168.0.100
並打開 shell,同時創建本地 TCP 埠 1000 到 mail.google.com 埠 25 的隧道。連接成功後,發送到 localhost:1000
的連接會連到 Gmail 的 SMTP 埠。除非使用了其它手段,否則對於谷歌來說,他們會觀察到所有這些連接都是從 192.168.0.100
發送出來的(但對於連接傳送的數據又是另一回事),而不是 192.168.0.100
。
類似地:
$ ssh -L 2000:192.168.0.100:6001 192.168.0.100
將允許連接到 localhost:2000
,然後數據會被透明發送到遠程主機的 6001 埠。The preceding example is useful for VNC connections using the vncserver utility--part of the tightvnc package--which, though very useful, is explicit about its lack of security.
Remote forwarding allows the remote host to connect to an arbitrary host via the SSH tunnel and the local machine, providing a functional reversal of local forwarding, and is useful for situations where, e.g., the remote host has limited connectivity due to firewalling. It is enabled with the -R
switch and a forwarding specification in the form of <tunnel port>:<destination address>:<destination port>
.
Thus:
$ ssh -R 3000:irc.libera.chat:6667 192.168.0.200
will bring up a shell on 192.168.0.200
, and connections from 192.168.0.200
to itself on port 3000 (the remote host's localhost:3000
) will be sent over the tunnel to the local machine and then on to irc.libera.chat on port 6667, thus, in this example, allowing the use of IRC programs on the remote host to be used, even if port 6667 would normally be blocked to it.
Both local and remote forwarding can be used to provide a secure "gateway", allowing other computers to take advantage of an SSH tunnel, without actually running SSH or the SSH daemon by providing a bind-address for the start of the tunnel as part of the forwarding specification, e.g. <tunnel address>:<tunnel port>:<destination address>:<destination port>
. The <tunnel address>
can be any address on the machine at the start of the tunnel. The address localhost
allows connections via the localhost
or loopback interface, and an empty address or *
allow connections via any interface. By default, forwarding is limited to connections from the machine at the "beginning" of the tunnel, i.e. the <tunnel address>
is set to localhost
. Local forwarding requires no additional configuration; however, remote forwarding is limited by the remote server's SSH daemon configuration. See the GatewayPorts
option in sshd_config(5) and -L address
option in ssh(1) for more information about remote forwarding and local forwarding, respectively.
跳板機
有時,可能無法直接連接到目標的 SSH 守護程序,因而需要使用一個跳轉伺服器(或堡壘伺服器)。為此,我們試圖將兩個或更多的 SSH 隧道連接在一起,並假設你的本地密鑰對鏈上的每個伺服器都有授權。這可以通過 SSH 代理轉發(-A
)和使用偽終端分配(-t
)轉發你的本地密鑰實現:
$ ssh -A -t -l user1 bastion1 \ ssh -A -t -l user2 intermediate2 \ ssh -A -t -l user3 target
這一流程可以使用 ProxyCommand 選項進行自動化:
$ ssh -o ProxyCommand="ssh -W %h:%p bastion.example.org" targetserver.example.org
一個更簡單和更安全的方法是將 ProxyJump 選項結合 -J
使用:
$ ssh -J user1@bastion1,user2@intermediate2 user3@target
-J
指令中的多個主機可以用逗號隔開,它們將按照列出的順序被連接。user...@
部分不是必須的,但可以使用。The host specifications for -J
use the ssh configuration file, so specific per-host options can be set there, if needed.
The main difference between the ProxyCommand and ProxyJump options is that the later does not require a shell on the jumphost. Consequently, this also means that the jumpserver does not require access to the users login credentials or SSH agent forwarding. With the ProxyJump option, the ssh client connects through the jumpserver directly to the target server, establishing an end-to-end encrypted channel between client and target server.
-J
標誌相當於配置文件中 ProxyJump
選項,相關細節請參考 ssh_config(5)。
Reverse SSH through a relay
The idea is that the client connects to the server via another relay while the server is connected to the same relay using a reverse SSH tunnel. This is useful when the server is behind a NAT, and the relay is a publicly accessible SSH server used as a proxy to which the user has access. Therefore, the prerequisite is that the client's keys are authorized against both the relay and the server, and the server needs to be authorized against the relay as well for the reverse SSH connection.
The following configuration example assumes that user1 is the user account used on client, user2 on relay and user3 on server. First, assuming we will use port 2222, the server needs to establish the reverse tunnel with:
ssh -R 2222:localhost:22 -N user2@relay
Which can also be automated with a startup script, systemd service, autossh or sidedoorAUR.
At the client side, the connection is established with:
ssh -t user2@relay ssh user3@localhost -p 2222
ssh user3@relay -p 2222
would require you to open this port in the firewall of your relay server, as well as to allow connections to this port from other addresses.The remote command to establish the connection to reverse tunnel can also be defined in relay's ~/.ssh/authorized_keys
by including the command
field as follows:
command="ssh user3@localhost -p 2222" ssh-ed25519 KEY2 user1@client
In this case the connection is established with:
ssh user2@relay
Alternatively, you can add an entry to your ssh configuration that specifies both RemoteCommand
and RequestTTY
:
~/.ssh/config
Host jump-destination Hostname relay User user2 RemoteCommand ssh user3@localhost -p 2222 RequestTTY yes
Which will reduce connecting to:
ssh jump-destination
多路復用
SSH 守護進程通常監聽 22 埠。然而,許多公共熱點會屏蔽所有不在常規 HTTP/S 埠(80 和 443)的流量,從而阻止了 SSH 連接。最直接解決這個問題的辦法是讓 sshd
額外監聽白名單中的一個埠。
/etc/ssh/sshd_config
Port 22 Port 443
然而,443 埠很可能已經被提供 HTTPS 內容的網頁伺服器使用,在這種情況下,可以使用類似 sslh包 的多路復用器,它會監聽多路復用埠,並智能地將數據包轉發給多個服務。
Speeding up SSH
There are several client configuration options which can speed up connections either globally or for specific hosts. See ssh_config(5) for full descriptions of these options.
-
Use a faster cipher: on modern CPUs with AESNI instructions,
aes128-gcm@openssh.com
andaes256-gcm@openssh.com
should offer significantly better performance over openssh's default preferred cipher, usuallychacha20-poly1305@openssh.com
. Cipher can be selected with the-c
flag. For a permanent effect, putCiphers
option in your~/.ssh/config
with ciphers in new preferred order, e.g.:Ciphers aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
-
Enable or disable compression: compression can increase speed on slow connections; it is enabled with the
Compression yes
option or the-C
flag. However, the compression algorithm used is the relatively slow gzip(1) which becomes the bottleneck on fast networks. In order to speed up the connection, one should use theCompression no
option on local or fast networks.
-
Connection sharing: you can make all sessions to the same host share a single connection using these options:
ControlMaster auto ControlPersist yes ControlPath ~/.ssh/sockets/socket-%r@%h:%p
- where
~/.ssh/sockets
can be any directory not writable by other users.
-
ControlPersist
specifies how long the master should wait in the background for new clients after the initial client connection has been closed. Possible values are either:-
no
to close the connection immediately after the last client disconnects, - a time in seconds,
-
yes
to wait forever, the connection will never be closed automatically.
-
- Login time can be shortened by bypassing IPv6 lookup using the
AddressFamily inet
option or-4
flag.
- Last, if you intend to use SSH for SFTP or SCP, High Performance SSH/SCP can significantly increase throughput by dynamically raising the SSH buffer sizes. Install the package openssh-hpnAUR to use a patched version of OpenSSH with this enhancement.
使用 SSHFS 掛載遠程文件系統
關於將 SSH 可訪問的遠程系統掛載到本地目錄的內容請查看 SSHFS 文章。這樣您就可以使用任何工具對掛載的文件執行任何操作(複製、重命名、使用 vim 編輯等)。sshfs 一般優於 shfs,後者自 2004 年以來一直沒有更新。
保活
默認情況下,如果 SSH 會話空閒了一段時間,它將自動註銷。為了保持會話,如果在一段時間內沒有收到數據,客戶端可以向伺服器發送保持活動的信號,或者如果伺服器沒有收到客戶端的消息,則可以對稱地定期發送消息。
- 在服務端,
ClientAliveInterval
以秒為單位設置超時,如果沒有從客戶端接收到數據,sshd 將發送響應請求。默認值為 0(不發送消息)。例如,要每 60 秒從客戶端請求一次響應,請在伺服器配置中設置ClientAliveInterval 60
選項。另見ClientAliveCountMax
和TCPKeepAlive
選項。
- 在 '客戶端,
ServerAliveInterval
控制從客戶端發送到伺服器的響應請求之間的間隔。例如,要請求伺服器每 120 秒響應一次,請將ServerAliveInterval 120
選項添加到客戶端配置中。另請參見ServerAliveCountMax
和TCPKeepAlive
選項。
ServerAliveInterval
,並使其他客戶機和伺服器保持默認配置。Automatically restart SSH tunnels with systemd
systemd can automatically start SSH connections on boot/login and restart them when they fail. This makes it a useful tool for maintaining SSH tunnels.
The following service can start an SSH tunnel on login using the connection settings in your ssh configuration. If the connection closes for any reason, it waits 10 seconds before restarting it:
~/.config/systemd/user/tunnel.service
[Unit] Description=SSH tunnel to myserver [Service] Type=simple Restart=always RestartSec=10 ExecStart=/usr/bin/ssh -F %h/.ssh/config -N myserver
Then enable and start the Systemd/User service. See #Keep alive for how to prevent the tunnel from timing out. If you wish to start the tunnel on boot, you might want to rewrite the unit as a system service.
Autossh - automatically restarts SSH sessions and tunnels
When a session or tunnel cannot be kept alive, for example due to bad network conditions causing client disconnections, you can use autossh包 to automatically restart them.
Usage examples:
$ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" username@example.com
Combined with SSHFS:
$ sshfs -o reconnect,compression=yes,transform_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,ssh_command='autossh -M 0' username@example.com: /mnt/example
Connecting through a SOCKS-proxy set by Proxy settings:
$ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" -NCD 8080 username@example.com
With the -f
option autossh can be made to run as a background process. Running it this way however means the passphrase cannot be entered interactively.
The session will end once you type exit
in the session, or the autossh process receives a SIGTERM, SIGINT of SIGKILL signal.
Run autossh automatically at boot via systemd
If you want to automatically start autossh, you can create a systemd unit file:
/etc/systemd/system/autossh.service
[Unit] Description=AutoSSH service for port 2222 After=network.target [Service] Environment="AUTOSSH_GATETIME=0" ExecStart=/usr/bin/autossh -M 0 -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com [Install] WantedBy=multi-user.target
Here AUTOSSH_GATETIME=0
is an environment variable specifying how long ssh must be up before autossh considers it a successful connection, setting it to 0 autossh also ignores the first run failure of ssh. This may be useful when running autossh at boot. Other environment variables are available at autossh(1). Of course, you can make this unit more complex if necessary (see the systemd documentation for details), and obviously you can use your own options for autossh, but note that the -f
implying AUTOSSH_GATETIME=0
does not work with systemd.
Remember to start and/or enable the service afterwards.
You may also need to disable ControlMaster e.g.
ExecStart=/usr/bin/autossh -M 0 -o ControlMaster=no -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com
Alternative service should SSH daemon fail
For remote or headless servers which rely exclusively on SSH, a failure to start the SSH daemon (e.g., after a system upgrade) may prevent administration access. systemd offers a simple solution via OnFailure
option.
Let us suppose the server runs sshd
and telnet is the fail-safe alternative of choice. Create a file as follows. Do not enable telnet.socket
!
/etc/systemd/system/sshd.service.d/override.conf
[Unit] OnFailure=telnet.socket
That's it. Telnet is not available when sshd
is running. Should sshd
fail to start, a telnet session can be opened for recovery.
Terminal background color based on host
為了更好地區分在不同主機上的情況,可以設置基於主機類型的不同背景顏色 。
這種解決方案僅限於 ZSH。
Network specific configuration
You can use host configuration specific to the network you are connected to using a Match exec
.
For example, when using nmcli(1), and the connection is configured (manually or through DHCP) to use a search-domain:
Match exec "nmcli | grep domains: | grep example.com" CanonicalDomains example.com # Should you use a different username on this network #User username # Use a different known_hosts file (for private network or synchronisation) #UserKnownHostsFile <network>_known_hosts
Another example for Match host ... exec "..."
: Consider that connecting to internal.example.com
requires a bastion/proxy (via ProxyJump
) unless you are already connected via VPN. The fragment !exec "host internal.example.com"
applies only when internal.example.com
cannot be looked up via DNS. Various alternatives are discussed at [3].
Match host internal.example.com !exec "host internal.example.com" ProxyJump bastion.example.com Host internal.example.com User foobar
Private networks hostkeys verification
Because different servers on different networks are likely to share a common private IP address, you might want to handle them differently.
The best solution is to use the #Network specific configuration to use a different UserKnownHostsFile
depending on the network you are on. The second solution, best used as default when you are working on new/prototype networks, would be to simply ignore hostkeys for private networks:
Host 10.* 192.168.*.* 172.31.* 172.30.* 172.2?.* 172.1?.* # Disable HostKey verification # Trust HostKey automatically StrictHostKeyChecking no # Do not save the HostKey UserKnownHostsFile=/dev/null # Do not display: "Warning: Permanently Added ..." LogLevel Error
在登錄時運行命令
如果你使用的是交互式會話,有多種方法可以在登錄時執行一個命令:
- 使用遠程主機上的
authorized_keys
文件(參見 sshd(8) § AUTHORIZED_KEYS FILE FORMAT) - 如果伺服器啟用了
~/.ssh/rc
選項,則使用遠程主機上的PermitUserRC
選項 - 使用遠程主機上的 shell 配置文件,例如
.bashrc
。
轉發代理
SSH 代理轉發允許你在連接到一個伺服器時使用你的本地密鑰。建議只對選定的主機啟用代理轉發。
~/.ssh/config
Host myserver.com ForwardAgent yes
接下來,配置 SSH 代理並使用 ssh-add 添加你的本地密鑰。
如果你現在連接到一個遠程伺服器,你將能夠使用你的本地密鑰連接到其他服務。
生成新的密鑰對
新的伺服器私鑰可以通過以下方式生成:
- 刪除已有的所有密鑰,例如:
# rm /etc/ssh/ssh_host_*_key*
-
重啟
sshdgenkeys.service
或者以根用戶身份運行ssh-keygen -A
Run sshd as non-privileged user
You may want to run sshd
as non-privileged user in containers, or for testing, etc.
Since non-privileged user cannot read host keys in /etc/ssh
, new host keys must be generated:
$ ssh-keygen -q -N "" -t rsa -b 4096 -f /path/to/host/keys/ssh_host_rsa_key $ ssh-keygen -q -N "" -t ecdsa -f /path/to/host/keys/ssh_host_ecdsa_key $ ssh-keygen -q -N "" -t ed25519 -f /path/to/host/keys/ssh_host_ed25519_key
Create an sshd_config
file. The example below uses a port higher than 1024, provides a new path to the host keys and disables PAM:
/path/to/sshd_config
Port 2022 HostKey /path/to/host/keys/ssh_host_rsa_key HostKey /path/to/host/keys/ssh_host_ecdsa_key HostKey /path/to/host/keys/ssh/ssh_host_ed25519_key UsePAM no
Run sshd with the created config. The -D
flag disables daemon mode and -e
redirects output to stderr to allow easy monitoring.
$ sshd -f /path/to/sshd_config -D -e
排障
Checklist
Check these simple issues before you look any further.
- The configuration directory
~/.ssh
, its contents should be accessible only by the user (check this on both the client and the server), and the user's home directory should only be writable by the user:$ chmod go-w ~ $ chmod 700 ~/.ssh $ chmod 600 ~/.ssh/* $ chown -R $USER ~/.ssh
- Check that the client's public key (e.g.
id_ed25519.pub
) is in~/.ssh/authorized_keys
on the server. - Check that you did not limit SSH access with
AllowUsers
orAllowGroups
in the server config. - Check if the user has set a password. Sometimes new users who have not yet logged in to the server do not have a password.
-
Append
LogLevel DEBUG
to/etc/ssh/sshd_config
. - Run
journalctl -xe
as root for possible (error) messages. -
Restart
sshd
and logout/login on both client and server.
Connection refused or timeout problem
Port forwarding
If you are behind a NAT mode/router (which is likely unless you are on a VPS or publicly addressed host), make sure that your router is forwarding incoming ssh connections to your machine. Find the server's internal IP address with $ ip addr
and set up your router to forward TCP on your SSH port to that IP. portforward.com can help with that.
Is SSH running and listening?
The ss utility shows all the processes listening to a TCP port with the following command line:
$ ss --tcp --listening
If the above command do not show the system is listening to the port ssh
, then SSH is not running: check the journal for errors etc.
Are there firewall rules blocking the connection?
Iptables may be blocking connections on port 22
. Check this with:
# iptables -nvL
and look for rules that might be dropping packets on the INPUT
chain. Then, if necessary, unblock the port with a command like:
# iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
For more help configuring firewalls, see firewalls.
Is the traffic even getting to your computer?
Start a traffic dump on the computer you are having problems with:
# tcpdump -lnn -i any port ssh and tcp-syn
This should show some basic information, then wait for any matching traffic to happen before displaying it. Try your connection now. If you do not see any output when you attempt to connect, then something outside of your computer is blocking the traffic (e. g., hardware firewall, NAT router etc.).
Your ISP or a third party blocking default port?
In some cases, your ISP might block the default port (SSH port 22) so whatever you try (opening ports, hardening the stack, defending against flood attacks, et al) ends up useless. To confirm this, create a server on all interfaces (0.0.0.0) and connect remotely.
If you get an error message comparable to this:
ssh: connect to host www.inet.hr port 22: Connection refused
That means the port is not being blocked by the ISP, but the server does not run SSH on that port (See security through obscurity).
However, if you get an error message comparable to this:
ssh: connect to host 111.222.333.444 port 22: Operation timed out
That means that something is rejecting your TCP traffic on port 22. Basically that port is stealth, either by your firewall or 3rd party intervention (like an ISP blocking and/or rejecting incoming traffic on port 22). If you know you are not running any firewall on your computer, and you know that Gremlins are not growing in your routers and switches, then your ISP is blocking the traffic.
To double check, you can run Wireshark on your server and listen to traffic on port 22. Since Wireshark is a Layer 2 Packet Sniffing utility, and TCP/UDP are Layer 3 and above (see IP Network stack), if you do not receive anything while connecting remotely, a third party is most likely to be blocking the traffic on that port to your server.
Diagnosis
Install either tcpdump包 or Wireshark with the wireshark-cli包 package.
For tcpdump:
# tcpdump -ni interface "port 22"
For Wireshark:
$ tshark -f "tcp port 22" -i interface
where interface
is the network interface for a WAN connection (see ip a
to check). If you are not receiving any packets while trying to connect remotely, you can be very sure that your ISP is blocking the incoming traffic on port 22.
Possible solution
The solution is just to use some other port that the ISP is not blocking. Open the /etc/ssh/sshd_config
and configure the file to use different ports. For example, add:
Port 22 Port 1234
Also make sure that other "Port" configuration lines in the file are commented out. Just commenting "Port 22" and putting "Port 1234" will not solve the issue because then sshd will only listen on port 1234. Use both lines to run the SSH server on both ports.
Restart the server sshd.service
and you are almost done. You still have to configure your client(s) to use the other port instead of the default port. There are numerous solutions to that problem, but let us cover two of them here.
Read from socket failed: connection reset by peer
Recent versions of OpenSSH sometimes fail with the above error message when connecting to older ssh servers. This can be worked around by setting various client options for that host. See ssh_config(5) for more information about the following options.
The problem could be the ecdsa-sha2-nistp*-cert-v01@openssh
elliptical host key algorithms. These can be disabled by setting HostKeyAlgorithms
to a list excluding those algorithms. On the client side, the HostKeyAlgorithms
that the client wants to use can also be set by preceding the HostKeyAlgorithms
list with a -
to remove the specified algorithms (including wildcards) from the default set (see ssh_config(5)
man page).
You can check the actually used host key algorithm with ssh -v server_to_connect_to
in the line that contains kex: host key algorithm:
.
If that does not work, it could be that the list of ciphers is too long. Set the Ciphers
option to a shorter list (fewer than 80 characters should be enough). Similarly, you can also try shortening the list of MACs
.
See also the discussion on the OpenSSH bug forum.
"[your shell]: No such file or directory" / ssh_exchange_identification problem
One possible cause for this is the need of certain SSH clients to find an absolute path (one returned by whereis -b [your shell]
, for instance) in $SHELL
, even if the shell's binary is located in one of the $PATH
entries.
"Terminal unknown" or "Error opening terminal" error message
If you receive the above errors upon logging in, this means the server does not recognize your terminal. Ncurses applications like nano may fail with the message "Error opening terminal".
The correct solution is to install the client terminal's terminfo file on the server. This tells console programs on the server how to correctly interact with your terminal. You can get info about current terminfo using $ infocmp
and then find out which package owns it.
If you cannot install it normally, you can copy your terminfo to your home directory on the server:
$ ssh myserver mkdir -p ~/.terminfo/${TERM:0:1} $ scp /usr/share/terminfo/${TERM:0:1}/$TERM myserver:~/.terminfo/${TERM:0:1}/
After logging in and out from the server the problem should be fixed.
TERM hack
Alternatively, you can simply set TERM=xterm
in your environment on the server (e.g. in .bash_profile
). This will silence the error and allow ncurses applications to run again, but you may experience strange behavior and graphical glitches unless your terminal's control sequences exactly match xterm's.
Connection closed by x.x.x.x [preauth]
If you are seeing this error in your sshd logs, make sure you have set a valid HostKey
HostKey /etc/ssh/ssh_host_ed25519_key
subsystem request failed
Since OpenSSH 8.8, scp uses SFTP as the default protocol for data transfers by requesting the subsystem named sftp
. If you run scp in verbose mode, scp -v
, you can determine which subsystem your client is using (e.g. Sending subsystem: <subsystem-name>
). Errors such as subsystem request failed on channel 0
may be fixed by configuring the server's Subsystem settings: sshd_config(5) § Subsystem. The server configuration should resemble the example below.
/etc/ssh/sshd_config
... Subsystem subsystem-name /path/to/subsystem-executable ...
id_dsa refused
OpenSSH 7.0 deprecated DSA public keys for security reasons and OpenSSH 9.8 is built without support for DSA keys by default. The first OpenSSH release of 2025 will remove DSA support entirely. For now, if you absolutely must use them, you will need to rebuild openssh包 while passing --enable-dsa-keys
to configure
.[4]
No matching key exchange method found by OpenSSH 7.0
OpenSSH 7.0 deprecated the diffie-hellman-group1-sha1 key algorithm because it is weak and within theoretical range of the so-called Logjam attack (see https://www.openssh.com/legacy.html). If the key algorithm is needed for a particular host, ssh will produce an error message like this:
Unable to negotiate with 127.0.0.1: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
The best resolution for these failures is to upgrade/configure the server to not use deprecated algorithms. If that is not possible, you can force the client to reenable the algorithm with the client option KexAlgorithms +diffie-hellman-group1-sha1
.
tmux/screen session killed when disconnecting from SSH
If your processes get killed at the end of the session, it is possible that you are using socket activation and it gets killed by systemd包 when it notices that the SSH session process exited. In that case there are two solutions. One is to avoid using socket activation by using ssh.service
instead of ssh.socket
. The other is to set KillMode=process
in the Service section of ssh@.service
.
The KillMode=process
setting may also be useful with the classic ssh.service
, as it avoids killing the SSH session process or the screen包 or tmux包 processes when the server gets stopped or restarted.
SSH session stops responding
SSH responds to flow control commands XON
and XOFF
. It will freeze/hang/stop responding when you hit Ctrl+s
. Use Ctrl+q
to resume your session.
Broken pipe
If you attempt to create a connection which results in a Broken pipe
response for packet_write_wait
, you should reattempt the connection in debug mode and see if the output ends in error:
debug3: send packet: type 1 packet_write_wait: Connection to A.B.C.D port 22: Broken pipe
The send packet
line above indicates that the reply packet was never received. So, it follows that this is a QoS issue. To decrease the likely-hood of a packet being dropped, set IPQoS
:
/etc/ssh/ssh_config
Match all IPQoS reliability
The reliability
(0x04
) type-of-service should resolve the issue, as well as 0x00
and throughput
(0x08
).
Terminate unresponsive SSH connection
If a client session is no longer responding and cannot be terminated by instructing the running program (e.g. shell), you can still terminate the session by pressing Enter
, ~
and .
one after another in that order.
The ~
is a pseudo-terminal escape character (see ssh(1) § ESCAPE CHARACTERS), which can be added multiple times depending on the client session to terminate. For example, if you connected from A to B and then from B to C and the session from B to C freezes, you can terminate it by pressing Enter
and typing ~~.
, which will leave you in a working session on B.
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!
If the client warns that the key of an ssh server has changed, you should verify that the newly offered key really belongs to the server operator via an authenticated (not necessarily encrypted) channel. Then remove the old key from the known_hosts
file with ssh-keygen -R $SSH_HOST
and accept the new key as if it was a new server.
Connecting to a remote without the appropriate terminfo entry
When connecting to hosts that do not have a terminfo entry for your terminal, for example, when using a terminal emulator whose terminfo entry is not shipped with ncurses包 (e.g. kitty and rxvt-unicode), or when connecting to hosts with a limited terminfo database (e.g. systems running OpenWrt), various issues will occur with software that relies on terminfo(5).
A proper solution is to place the appropriate terminfo entry on the host. If that is not feasible, an alternative is to set TERM
to a value that is both supported by the remote host and compatible with the terminal.
Since OpenSSH 8.7, a custom TERM
environment variable can be passed to remote hosts with a simple configuration snippet:
~/.ssh/config
Host example.com SetEnv TERM=xterm-256color
Connection through jump host fails with "bash: No such file or directory"
If you do not have the SHELL
environment variable set to a full valid path (on the jump server), connection will fail with an error message simmilar to this one:
bash: No such file or directory kex_exchange_identification: Connection closed by remote host Connection closed by UNKNOWN port 65535
You can simply solve this by setting your SHELL
to a full path name of a shell that will also be valid on the jump server or by setting a specific SHELL
variable for each server in your ~/.ssh/config
file.
參見
- Wikibooks:OpenSSH
- 防禦暴力 ssh 攻擊
- OpenSSH 密鑰管理:第一部分在 IBM developerWorks 上, 第二部分、第三部分在 funtoo.org 上
- Secure Secure Shell