Niraj Zade | Website is a work in progress.

SSH tunneling templates

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


Theory in short

Use LocalForward, RemoteForward, ProxyJump to simplify setup.

~/.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).

Table Of Contents:

All Articles

Blog

Resources