Home > Command-Line, Open Source > Persistant SSH Reverse Tunnel Connection

Persistant SSH Reverse Tunnel Connection

I learned this trick while working in Open Source Systems Sdn Bhd. Thanks to Shawn and Alan for the trick.

The Scenario:
In one of our site ssh connection to Internet is permitted, but their firewall prevent connection from the Internet to login.

The Action Plan:
Persistent SSH reverse-tunnel. We need a persistent (respawns when it is killed) tunnel that is initiated from REMOTE site to our LOCAL server, which opens a path for us to connect into REMOTE site from our server.

The Challenges:

  1. SSH from REMOTE to LOCAL needs to be passwordless (so that it can be automated). This also means that we have to control what users in REMOTE site can do when the SSH into our server.
  2. It needs to be up all the time
  3. However needs to refresh now and then in case of defunct connection/process
  4. In case of connection to Internet down, we must prevent continuous tunnel establishment

On LOCAL side –

1. Create a user to be used by remote user

# useradd -m raihan
# passwd raihan

2. Create a default shell to be used by remote user. Here, we use sleep, so that user ‘raihan’ will not get an interactive shell, and connection will timeout after specified time. (counters problem 1 & 2)

# vi /bin/sleepsh
sleep 1200

# chown root:root /bin/sleepsh
# chmod 555 /bin/sleepsh
# echo “/bin/sleepsh” >> /etc/shells

3. set ‘raihan’ default shell

# usermod -s /bin/sleepsh raihan

4. Copy public key from REMOTE server and place into ‘raihan’ home directory for passwordless connection

# cp id_rsa.pub /home/raihan/.ssh/authorized_keys
# chown raihan: /home/raihan/.ssh/authorized_keys


ON REMOTE side –

1. Create a script that will establish reverse tunnel

# vi /usr/bin/ontunnel
—— /root/bin/osstunnel ——
/usr/bin/ssh raihan@localserver.net -R 2222:localhost:22 -k >/dev/null

if [ $? -eq 1 ]
sleep 10m

2. Add an entry in inittab that run the file. Use the respawn directive to restart it whenever it goes down. (problem 2 solved)

# vi /etc/inittab
—— /etc/inittab ——

3. Updated Init with the new /etc/inittab file

# telinit q


Once everything above is done, we can connect to REMOTE site whenever we want by login to our server, and then running

# ssh -p 2222 localhost

Categories: Command-Line, Open Source
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: