Configure port forwarding with an SSH tunnel
Learn how to use SSH tunnels to securely forward network traffic between local and remote ports.
Lesson Content
An SSH tunnel lets you forward traffic through an SSH server when a network blocks access to a website or remote service.
Forward a local port
Use the -L option to configure local port forwarding. Its value follows this format:
-L local-port:destination-host:destination-portFor example, this command forwards local port 8000 to yahoo.com on port 80 through example.com:
ssh -L 8000:yahoo.com:80 [email protected]The SSH server is the server that passes the final request to the destination. When you access port 8000 on your local machine, SSH sends the request through example.com, which then connects to yahoo.com on port 80. The response travels back through the same tunnel.
You can use this technique to get around internet firewalls or connect to remote services that are blocked from your current network.
By default, the SSH tunnel keeps the terminal window open. Add the -f option to run SSH in the background and the -N option to prevent it from running a remote command or opening a shell:
ssh -f -N -L 8000:yahoo.com:80 [email protected]Because the tunnel runs in the background, you can find its process with ps aux and grep:
ps aux | grep ssh | grep 8000The command output includes the process ID. Stop the tunnel by passing that ID to kill:
kill PROCESS_IDForward a remote port
Remote port forwarding sends connections on a remote host back to your local machine. This is useful when someone needs to access a service on your local machine but cannot connect to that port directly.
By default, SSH servers bind remotely forwarded ports to their loopback interface only, so other machines cannot reach them. On the SSH server, open /etc/ssh/sshd_config and set GatewayPorts to yes. Then restart the SSH service:
service ssh restartCreate the tunnel with the -R option instead of -L. Its value follows this format:
-R remote-port:local-host:local-portFor example, this command listens on port 8000 of the remote host and forwards requests to port 3000 on your local machine:
ssh -R 8000:localhost:3000 [email protected]The first value, 8000, is the port that listens on the remote host. The destination is localhost on the machine running the SSH client, and port 3000 is the local service that receives the requests.
Now, when someone accesses port 8000 on the remote host, SSH tunnels the request to port 3000 on your local machine.
Join the discussion!
Comments
Want to comment on this lesson?
Log in to leave comments.