Sunday, November 8, 2009

Connect to the restricted port of a remote host via SSH tunnel

There are some scenarios where you can use this technique.

A remote server allows only local connections

To connect to such a server, you usually have to copy your application to the remote host where the server is running. Then login to that host and run your application there. If you are developing or testing your application, you may think that it is very inconvenient when you are frequently changing your source code. It will be much better if you can code, compile and test your application on your local machine against the remote server.

Supposed the restricted server program is listening on port 20001 on a remote host named restrictedhost and it only accepts local connections. You can create an SSH tunnel with the following command on your machine.
         ssh -L 30501:127.0.0.1:20001 restrictedhost

Input your password on restrictedhost to login. After you login, keep the terminal aside and alive. A secure SSH channel has been established. Now open another local terminal on your machine. Run your application and have it connect to the port 30501 of your machine. The connection will be forwarded to restrictedhost as a local connection to 127.0.0.1:20001. The remote server application will think your connection is from local to its port 20001 and accept it.

A remote server allows connections from certain hosts

Supposed the restricted server program is listening on port 20001 on a remote host named restrictedhost and it only accepts connections from a range of specific hosts.

If your machine is not in the range of the allowed hosts, you will have to copy your application to one of those allowed hosts in order to test it against the server. With SSH tunnel, you can run your application on your own machine and pretend that it is making connection from one of the allowed hosts, e.g. allowedhost1.
         ssh -L 30501:restrictedhost:20001 allowedhost1

Input your password on allowedhost1 to login. After you login, keep the terminal aside and alive. A secure SSH channel has been established from your machine to allowedhost1. Run your application and have it connect to the port 30501 of your machine. The connection will be forwarded to allowedhost1 as a connection from allowedhost1 to the port 20001 of restrictedhost. The remote server application will think your connection is from allowedhost1 and accept it.

To sum it up, your application makes a connection to a local port and the SSH tunnel makes it like a connection from the host you login to.

No comments:

Post a Comment