SSH 反向隧道外部無法連線?GatewayPorts 設置完全解決方案
Copyright Notice: This article is an original work licensed under the CC 4.0 BY-NC-ND license.
If you wish to repost this article, please include the original source link and this copyright notice.
Source link: https://v2know.com/article/1292
SSH 反向隧道外部無法連線?GatewayPorts 設置完全解決方案
最近在配置 SSH 反向隧道(Reverse SSH Tunnel)時遇到一個奇怪問題:
隧道建立成功、SSH 已連線,但外部始終無法透過指定端口連回本地服務(例如 RDP 3389)。
問題的根源竟然是 —— SSH 的 GatewayPorts 設定。
本文記錄完整排查過程與最終的解決方案。
🎯 問題現象
使用自製的 SSH 隧道工具時,日誌顯示正常:
SSH connected
Tunnel active (remote 127.0.0.1:5555 → local 127.0.0.1:3389)
但外部連:
mstsc /v:server_ip:5555
永遠連不上。
UFW 開放規則也正確:
5555/tcp ALLOW IN Anywhere
然而執行:
ss -lntp | grep 5555
卻看到:
127.0.0.1:5555
表示隧道只在 loopback 上開放,外部永遠連不上。
🔍 關鍵原因:GatewayPorts = no(預設值)
SSH 反向隧道的行為受到 GatewayPorts 控制:
| GatewayPorts | 行為 |
|---|---|
| no(預設) | 反向隧道強制綁定在 127.0.0.1 |
| clientspecified | 只有客戶端顯式指定 0.0.0.0 時才綁外部 |
| yes | 反向隧道可以綁定在 0.0.0.0,自動對外可連 |
由於我的工具 不允許填寫 Remote Host = 0.0.0.0(只能填 127.0.0.1),
導致:
-
GatewayPorts clientspecified時 → 仍然只能綁 loopback -
只有設成
GatewayPorts yes時隧道才會開在 0.0.0.0:5555
Vultr 新機器之所以原本可用,是因為默認配置允許對外綁定。
✅ 最終解決方案
1. 編輯 sshd_config
sudo nano /etc/ssh/sshd_config
加入:
GatewayPorts yes
保存並重啟:
sudo systemctl restart sshd
2. 隧道工具仍然填寫:
Remote Host = 127.0.0.1 (不可更改)
Remote Port = 5555
3. 再次檢查端口
ss -lntp | grep 5555
會看到:
0.0.0.0:5555
此時外部即可透過:
mstsc /v:server_ip:5555
成功連線到 Windows 的 RDP。
🔐 安全性考量:GatewayPorts=YES 安全嗎?
很多人擔心 GatewayPorts yes 會讓 Linux 變肉雞,
但實際上,安全性取決於 SSH 的驗證方式。
在以下條件成立的情況下:
-
僅允許 RSA 私鑰登入
-
SSH PasswordAuthentication=no
-
私鑰本身還有 passphrase
-
未授權者無法取得私鑰
➡ 外人即使掃描到端口,也無法建立隧道,更無法登入 root。
➡ 使用 GatewayPorts yes 不會降低伺服器安全性。
⚠ 唯一要注意的是避免私鑰外流。
建議額外使用:
sudo ufw allow from <你的IP> to any port 5555 proto tcp
讓 5555 僅限自己的來源 IP。
🟦 最終結論
-
反向隧道外部無法連線的真正原因:GatewayPorts=no
-
解決方法:將 GatewayPorts 設為 yes
-
在 RSA Key + Passphrase 條件下,安全性完全沒問題
-
可搭配 UFW 限制來源 IP 提升防護
這次排查花了不少時間,特別寫成筆記,
希望未來遇到同樣問題的朋友能一眼看到核心解法。
This article was last edited at