ssh port forwarding

Written by Walter

< >

Good summary on ssh port forwarding (much easier to read than the manpages found it on linux.com somewhere) : Here's another nifty SSH feature. You already know it's a very bad idea to send important data over the network unencrypted. But what if you want to work with a remote service that doesn't offer encryption by default? Or what if you'd like to reach a machine that's behind a firewall? Using SSH's port forwarding features, you can do all this and more. First, you can forward a port on your local host directly to a port on a remote host. For example, let's say I'd like to be able to use a MySQL GUI application on my local machine to work with MySQL on my Web server. All I need to do is run the command: ssh -f -N -L 3306:localhost:3306 username@webserver Let's break that down a little. The -f option tells ssh to go into the background, while the -N option tells ssh not to execute any remote commands -- like a shell. The -f -N options are useful when forwarding ports, especially when you're using this in a script, unless you want to open a shell on the remote host in addition to forwarding a port. The -L option tells ssh to forward a port from the local host to a port on the remote host. In this case, both ports are 3306, so any traffic directed to port 3306 on my local machine will be directed to port 3306 on the Web server. Note that you will need to be logged in as root to forward the privileged ports below 1024. Now, if I fire up my MySQL GUI client and point it at localhost port 3306, it will actually be communicating with MySQL on the Web server over an encrypted connection. But that's not all! What if there's a firewall between my Web server and me, so that I can't connect directly to the Web server via SSH? Assuming you're working with a Linux firewall, or other firewall that's running SSH, you can still connect. This time, let's try forwarding a local port to port 25, so that I can connect to SMTP over a secured connection. Here's how it's done: ssh -f -N -L 2205:webserver:25 username@firewall The first argument, 2205:webserver:25 tells ssh to forward traffic from local port 2205 to port 25 on host Web server. Because I've specified firewall as the host to forward traffic through, by using username@firewall, the traffic will pass through that host. There is a drawback here, however. Traffic from my workstation to the firewall will be encrypted, but traffic between the firewall and the Web server will not. Last, but not least, you can go the other direction and forward traffic from a remote host to your local host. To do this, use the -R option instead of the -L option, like this: ssh -f -N -R 8081:localhost:8080 webserver This will forward all traffic from port 8081 on the host webserver to port 8080 on the local machine. Note that you need to be a privileged user on the remote host to open privileged ports.

Back to archive