Skip to content

Instantly share code, notes, and snippets.

@tomkinsc
Last active January 17, 2017 16:59
Show Gist options
  • Save tomkinsc/1919ae659538786b272d to your computer and use it in GitHub Desktop.
Save tomkinsc/1919ae659538786b272d to your computer and use it in GitHub Desktop.
SSH tunnel cheatsheat

SSH tunnel cheatsheet

SSH Reverse tunnel

                                            ┌─┐                      
                                            │ │                      
                                            │ │                      
┌─────────────┐        ┌─────────────┐      │ │       ┌─────────────┐
│    local    │        │    relay    │      │ │       │   remote    │
│   machine   │◀──────▶│   machine   │◀─────┼─┼───────│   machine   │
└─────────────┘        └─────────────┘      │ │       └─────────────┘
                                            │ │                      
                                            │ │                      
                                            │ │                      
                                            │ │                      
                                            └─┘                      
                                       NAT/firewall                  

Create reverse tunnel between remote machine and relay machine (to penetrate NAT or firewall that still permits outbound SSH:

ssh -R PORTNUM:localhost:22 USERNAME@RELAYMACHINE

For a more persistent tunnel, use something like autossh set up as a systemd service:

autossh -i /home/USERNAME/.ssh/id_rsa -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R PORTNUM:localhost:22 PORTNUM@RELAYMACHINE

Access remote machine from the relay machine:

ssh RELAYMACHINE

Then, once connected to the relay machine:

ssh localhost -p 5001

Access remote machine from local machine, proxied by the relay machine (transparently connect to remote machine without having to log in to the relay first):

ssh -o ProxyCommand="ssh -W %h:%p RELAYMACHINE" localhost -p PORTNUM

Forward tunnel (port redirection)

Redirect a port on the same machine:

ssh -L NEWPORT:localhost:SOURCEPORT localhost

Redirect a port listening on the local machine to one on a remote host (access google.com at http://localhost:8000, via an outbound connection from the relay machine):

ssh -L 8000:google.com:80 RELAYMACHINE

Create a SOCKS proxy

Tunnel all web traffic through a remote machine:

ssh -D 8080 USERNAME@RELAYMACHINE

(then set the browser/system SOCKS proxy on the system initiating the SSH connection to proxy via 127.0.0.1:8080)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment