Thursday, April 28, 2005

remote access to a firewalled machine with ssh port forwarding

At some point last year, I needed to be able to remotely control a computer at work that could not be accessed from the outside world due to a firewall. I already knew the power of ssh port forwarding, and figured there was some way to accomplish what I wanted to do using ssh.

Sure enough, I was able to put together the following two commands, which allowed me to do what I needed to do, with the help of my computer at home (whose firewall I could actually open a port on). I only did it once, just to see if it could really be done, but I did not want to risk getting in trouble for making a hole in the firewall. It was a fun exercise, though, and I wanted to share it with anyone who cares to listen.

The following represent things to modify in the commandlines below, to suit your own needs:

HOME_IP = the ip address of my machine at home
HOME_USER = my username on my machine at home
RESTRICTED_HOSTNAME = the hostname of the machine I'm trying to open up
RESTRICTED_USER = my username on the machine I'm trying to open up

First, I executed this command from the machine I wanted to open up to the outside world:
ssh -g -R 8022:localhost:22 HOME_USER@HOME_IP

This forwards my local port 22 (on the restricted machine) to my home machine's port 8022
-g tells it to allow remote hosts to connect to locally forwarded ports


Next, I executed this command in that ssh session to my home machine that I created with the first command:
ssh -p 8022 -N -f -g -L 15900:RESTRICTED_HOSTNAME:5900 RESTRICTED_USER@localhost

This forwards the VNC port (5900) on the machine I'm trying to open up to port 15900 on my home machine.
-g tells it to allow remote hosts to connect to locally forwarded ports
-N says I just want to make this connection for port forwarding, not to actually execute a command
-f says to put ssh into the background after establishing the connection


Now, from any machine with an internet connection and a VNC client, I can open a VNC connection to HOME_IP:15900, and I will be remotely controlling the restricted machine.

Note that this only requires me to have ports 22 and 15900 open on my firewall at home.%

0 comments: