SSH tunneling templates

2024 Sep 22  |  1 min read  |  tags: infrastructure (2) linux (1)

Theory in short

Use LocalForward, RemoteForward, ProxyJump to simplify setup.

  • LocalForward - Local port forwarding
    • Forward local port to remote server
  • RemoteForward - Remote port forwarding
    • forward remote machine's port to local machine or other server
  • ProxyJump - SSH through jumphost/bastion/proxy
    • Route connection through intermediate server, to reach final server

~/.ssh/config examples

Simple direct remote ssh shell

Open SSH connection to remote server

Host remoteserver
  HostName dev.example.com
  User dev
  IdentityFile ~/.ssh/id_rsa
  Port 22

Forward local port to remote server port

Forward local's port 8080 to remote server's port 8080

local:8080 -> remote:8080
Host devserver
    User user
    Hostname domain.subdomain.tld
    IdentityFile ~/.ssh/id_rsa
    LocalForward 8080 127.0.0.1:8080

Forward remote server port to local port

Forward remote server's port 8080 to local's port 8080

local:8080 <- remote:8080
Host devserver
    User user
    Hostname domain.subdomain.tld
    IdentityFile ~/.ssh/id_rsa
    RemoteForward 8080 127.0.0.1:8080

SSH via jumphost/bastion/proxy

Host jump-host
    HostName jump1.example.com
    User user
    IdentityFile ~/.ssh/id_rsa

    Host target-server
        HostName target.example.com
        User user
        IdentityFile ~/.ssh/id_rsa
        ProxyJump jump-host

Notes: Can nest as many jump hosts as required.

OR, If jump host is shared across many target servers, declare jump host independently, and use them in target server configs:

Host jump-host
    HostName jump1.example.com
    User user
    IdentityFile ~/.ssh/id_rsa

Host target-server
    HostName target.example.com
    User user
    IdentityFile ~/.ssh/id_rsa
    ProxyJump jump-host
$ssh target-server