# SSH Tunnel 穿越隧道


# 前言 SSH Tunnel

Tunnel 可以讓 Server 與 Client 之間建立可突破防火牆且安全可靠的連線, Tunnel 就想管道一樣可以幫助我們去把內網的 SSH 轉發到外網去,有如 Proxy , Port Forwarding 的功能


# Tunnel 種類

  1. Local Tunnel (Local Forwarding)
  2. Remote Tunnel (Remote Forwarding)
  3. Dynamic Tunnel (Dynamic Forwarding)

在 Tunnel 的情境中會有三個角色

ITRI-SSH.drawio

  1. Client
  2. SSH Server (實際可連線 SSH Server)
  3. Target Server (目標機器)

範例 將 22 對外且使用 2210 Port
ITRI-SSH.drawio (1)


# Local Tunnel

Local Tunnel 會從 Client 端將特定服務的流量透過 SSH 傳送給 Server 端 (Remote),再透過 Server 端將流量導向到 特定 的 Host 上的 Port。

1
ssh -NfL <local ip>:<local port>:<host ip>:<host port> <user>@<remote server ip>

指令詳解

  • -N : 不執行額外命令
  • -f : 在背景執行
  • -L : 建立 Local Tunnel

# Remote Tunnel

透過對外機器,用外網讓 Client 連回內網機器

ITRI-SSH.drawio (2)

把 8080 port 的服務用外部主機對外出去

1
ssh -R 0.0.0.0:8080:localhost:8080 root@140.96.83.15 -fN

這種做法需要在 SSH Server 開啟 GatewayPort
/etc/ssh/sshd_config

1
GatewayPorts yes

# Dynamic Tunnel

當在 9090 Port 收到流量會自動轉發到 Target Server 上面
SSH Server 需要支援 SOCKS 協議

ITRI-SSH.drawio (3)


# 延伸資料 autossh

SSH 斷線後,當恢復連線會自動恢復連線的好工具


# 參考資料

  • SSH Tunneling (Port Forwarding) 詳解
  • Linux (九) - SSH Tunnel 突破防火牆限制