Monday, June 18, 2012

Access Any Remote Server Port Without Modifying Firewall Settings

Q. I've couple of remote servers and I'd like to access few admin only application running on port 10000 and 3001. My firewall only allows port 80, 443, 25, 22 and 110 for public access. Do I need to open port 10000 and 3001 for everyone using firewall? How do I access my admin only apps without opening port 10000 and 3001?

A. SSH has feature called port forwarding (also known as tunneling). It allows the act of forwarding a network port from one network node to another. This technique can allow an external user to reach a port on a private IP address (inside a LAN) from the outside via a NAT-enabled router.
The following example tunnels port 3001 session from client machine 127.0.0.1 (localhost) to remote server called "server.nixcraft.in"
$ ssh -f -L {local-port}:localhost:{remote-server-port} user@remote.server.com
$ ssh -f -L 3001:localhost:3001 user@server.nixcraft.in

The connection is forwarded to port 3001 on the remote server. If 3001 is web based app, open a web browser and type the url http://localhost:3001/
Another example to forward to port 10000, enter:
$ ssh -N -f -L 10000:localhost:10000 vivek@server.nixcraft.com
Where,
  • -f : Requests ssh to go to background just before command execution
  • -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.
  • -N : Do not execute a remote command. This is useful for just forwarding ports
You can also create a script as follows (open.3001):
$ vi ~/open.3001
Append following code:
#!/bin/bash
ME="$(basename $0)"
SSHUSER=vivek
SERVER=remote.example.com
[ $ME == "open.3001" ] && ssh -N -f -L 3001:localhost:3001 ${SSHUSER}@${SERVER} || :
[ $ME == "open.10000" ] && ssh -N -f -L 10000:localhost:10000 ${SSHUSER}@${SERVER} || :
[ $ME == "open.3000" ] && ssh -N -f -L 3000:localhost:3000 ${SSHUSER}@${SERVER} || :
Set permissions, enter:
$ chmod +x ~/open.3001
Create soft-link, enter:
$ ln -s ~/open.3001 ~/open.10000
$ ln -s ~/open.3001 ~/open.3000

Now you can simply type the following to forward port 10000, enter:
$ ~/open.10000
OR
$ ~/open.3000

No comments:

Post a Comment