Monday, November 26, 2018

Create a persistent reverse tunnel for a server behind firewall

To do this, you need to have a middleman server (middleman) to act as intermediaries between your workstation and the server behind firewall (target). The best is to have your middleman server running ssh server on the usual port that firewall allows, for example 80 and 443.

Step 1: In the target server, create a passwordless ssh access to your middleman server. Please refer here on how to accomplish that

Step 2: Create a simple bash script in target server that will check for the reverse tunnel connection, and restart the tunnel if the tunnel is broken. Lets say in this case, my middleman ssh server is running on port 443, you want to create a reverse tunnel on port 2222 on middleman server, and you want to use a user called foo in the middleman server. Don't forget to make the script executable by the owner.

$ cat /home/foo/bin/

ssh $USER@$SERVER -p $SPORT -t nc -vz localhost $PORT > /dev/null 2>&1
if [ $? -ne 0 ];
  then ssh -R $PORT:localhost:22 -l $USER -fN $SERVER -p $SPORT

$ chmod u+x /home/foo/bin/

Step 3: Set a crontab to run the above script every 10 minutes (or whatever interval you think is appropriate)
$ crontab -e
*/10 * * * * /home/foo/bin/

Step 4: Test the persistency by killing the ssh tunnel, and wait for crontab to run the script, and restart the tunnel

Step 5: You are now able to access the target server, simply by ssh'ng into port 2222 on middleman server
$ ssh foo@middleman -p 2222

No comments: