Skip to content

Instantly share code, notes, and snippets.

@sebcode
Last active July 8, 2016 10:47
Show Gist options
  • Save sebcode/77aad2427cfc7d6835901ea9fb07fe80 to your computer and use it in GitHub Desktop.
Save sebcode/77aad2427cfc7d6835901ea9fb07fe80 to your computer and use it in GitHub Desktop.
SSH Tunnel mini-HOWTO

SSH Tunnel Mini Howto

Local to Remote (-L)

-L Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side.

Use case: Make firewalled remote web server accessible from local machine

I have a Vserver myserver.com accessible via SSH on port 1122 for user peter. On this server runs a web server on port 8080. This web server is bound to localhost and is not accessible from the internet. Now I want to access this web server from my local machine. I type that command on my local machine:

ssh -p 1122 peter@myserver.com -L 9999:127.0.0.1:8080 -N

SSH now opened the port 9999 on my local machine which tunnels through to myserver.com:8080. I now have access to the remote web server through http://myserver.com:9999.

If I want that everybody on my local network have access to this remote web server, I can specify the local bind address 0.0.0.0 like so:

ssh -p 1122 peter@myserver.com -L 0.0.0.0:9999:127.0.0.1:8080 -N

It gets even crazier: If I want to give all machines on my local network access to a remote web server which is accessible by myserver.com via 10.0.0.1:666, I can do this:

ssh -p 1122 peter@myserver.com -L 0.0.0.0:9999:10.0.0.1:666 -N

This opens port 9999 on my local machine accessible by everyone on my local network and tunnels through 10.0.0.1:666 via myserver.com.

Remote to Local (-R)

-R Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side.

Use case: Make local web server accessible from the internet

I have a Vserver myserver.com accessible via SSH on port 1122 for user peter. On my local machine, I have a web server running on port 80. I am behind a firewall, so my local web server is only accessible on my local network. Now I want to make this web server accessible by my Vserver on his port 8080. I type that command on my local machine:

ssh -p 1122 peter@myserver.com -R 0.0.0.0:8080:127.0.0.1:80 -N

SSH now opened the port 8080 on myserver.com which tunnels back through to my local machine on port 80. If I open port 8080 of myserver.com via firewall, everybody can access my local webserver via http://myserver.com:8080/

Note: By default sshd binds remote port forwardings to the loopback address. You have to set GatewayPorts clientspecified in your sshd_config to be able to bind to any other address.

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