SSH tunnelling

SSH tunnelling

Quick reference guide to use when you need to use OpenSSH’s various tunnelling features.

I initially wrote this as a draft for myself because I would often forget what each parameter does, and what the correct syntax is, so I’m releasing this post in the hope that others find it helpful.

Basic options

The following options can be used with any of the three tunnel types below this section.

  • -N tells SSH to not execute any command, this option is necessary if the remote host has shell access disabled, as trying to spawn a shell would kick you out immediately
  • -q suppresses most warning and diagnostic messages
  • -f sets the SSH session up for background execution
  • -p sets the SSH port, by default it’s 22, but if it’s a different port number, you must specify it here

Local forwarding

Exposes a port from the server to the client. For example, if your client is on a VPN and you want to give other machines in your LAN access to a port on the server that’s not accessible via the Internet.

ssh -L ABC:hostname:XYZ user@server

This will make the client on port ABC listen for connections and, once it receives one, forward them to hostname on port XYZ.

For the above example, you can run the following command:

ssh -L 8080:10.3.1.200:443 user@server

This will make the SSH client listen on port 8080 and forward any incoming requests to the machine with the IP 10.3.1.200 (from the perspective of the server) over port 443.

Now, you can open a browser in your local machine and type https://localhost:8080 and you will connect to https://10.3.1.200 as seen from the SSH server.

Remote forwarding

Exposes a port from the client to the server. For example, you can run a web server on your client, then, expose it to the remote server so that friends and co-workers can connect to it even if you’re behind a restrictive NAT.

ssh -R ABC:hostname:XYZ user@server

The above command will map port ABC on the specified hostname to the port XYZ on the client.

For the example given above, you can expose a web server running on the client on port 80 in the following manner:

ssh -R 8080:localhost:80 user@server

After running this command, you can now connect to port 8080 on server and the SSH server will connect back to the client on port 80 where the web server is running

Dynamic (SOCKS) forwarding

This allows you to use SOCKS-aware applications behind your SSH server. This is generally used for masking your browser IP behind the SSH server’s IP, potentially bypassing content filtering firewalls or increasing your anonymity to website owners.

ssh -D XYZ user@server

Where XYZ is the localhost port you can connect your application (for example, web browser). Once you are connected to the SSH server, you must configure your applications to use the proxy settings for the SOCKS protocol with the IP address 127.0.0.1 or localhost and the port XYZ you have specified.