A Brief Tunneling Tutorial

by s0ke

Recently, I came across an issue where I wanted to be able to SSH into a box behind a pesky corporate firewall.  Not having access to said firewall, I decided to take matters into my own hands and set up a reverse SSH tunnel from that box to a box out on the Interweb that I can access.

Installation

The device that will be accessed behind the corporate firewall is a Raspberry Pi B+ installed with the vanilla version of Raspbian.  Out of the box, this is already set up for DHCP.  The following commands are all run on the Pi.

First, I will install 'autossh', which is a program that will automatically detect SSH connection drops and reconnect them - essentially keeping my tunnel alive and up:

$ sudo apt-get install autossh

I then generate an SSH key for my Pi to be able to SSH into myremotebox:

$ ssh-keygen

I copy the key from my Pi to myremotebox:

$ ssh-copy-id user@myremotebox

Bash/RC

Here is a simple Bash script (tun.sh) that creates the tunnel using autossh:

#!/bin/bash
sleep 30
/usr/bin/autossh -M 9090 -R 9091:localhost:22 user@myremotebox
#
#     -M = Monitoring port to use
#     -R 9091:localhost:22 = Reverse tunnel.  Forward all traffic on port 9091 to "myremotebox" on port 22.

I then add the following line to my /etc/rc.local file.  I want this to run as my Pi user.  I also add a sleep timer to ensure that networking is available before this script attempts to execute:

/bin/su - pi bash -c '/home/pi/tun.sh'

Tunnel Up

Now that everything is in place.  I covertly place my Pi inside the corporate office and leave for the day.  I then access my public Linux machine later that night and connect to the reverse tunnel.

sOke@pine64:~$ ssh -p 9091 pi@localhost
pi@localhost's password:
Linux raspberrypi 4.14.50+ #1122 Tue Jun 19 12:21:21 BST 2018 armv6l
The programs included with the Debian GNU/Linux system are free
software; the exact distribution terms for each program are
described in the individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Sep 26 18:21:26 2018 from ::1
Return to $2600 Index