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

Note: Can nest as many jump hosts as required.

OR, If jump host is shared across many target servers, declare jump host independently, and use it 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

Notes

Tunnels timeout/break all the time. Make sure you use auto-healing tunnels/connections.

Solutions: - Use autossh. This is the simplest solution. - Create a systemd service that takes care of the ssh process, and auto-restarts the process whenever it exits (whenever the tunnel breaks) (example blog post).