Reverse SSH tunnel

When you can't port forward in

Intro

Sometimes you aren't allowed or are unable to forward an SSH connection past your home gateway - if you are on a shared connection, behind carrier grade NAT or simply don't have access to NAT. What you can do instead is to ssh FROM your home machine to a machine outside your network, and forward a port on your inside machine to your outside machine. I highly recommend using DigitalOcean's $5 VPS instances, but I think free tier AWS instances are available.

Configure your outside machine

Configure your DigitalOcean machine to accept incoming ssh connections. Add non-root account. DONE

Configure your home machine

1) Install autossh

yum install autossh -y
or
apt install autossh -y

2) Generate ssh keys if you haven't already with ssh-keygen (just go with default values)

ssh-keygen

3) Send your home machine public key to the outside machine to enable password-less login using ssh-copy-id. This is the only time you'll need to use the password:

ssh-copy-id username@address

4) Try to ssh to your external machine from your internal to confirm that a password is no longer needed.

5) On your external machine, edit /etc/ssh/sshd_config and set:

PasswordAuthentication no

5b) Reload your sshd service or just reboot it external machine to apply password restriction.

6) Create a script to connect automatically to your external machine - name it /home/username/autossh.sh for example and use autossh inside, something like:

#!/bin/bash
AUTOSSH_GATETIME=30
export AUTOSSH_GATETIME
while true
do
        /usr/bin/autossh -M 10982 -N -R 2022:localhost:22 username@address -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2"
        sleep 5
done

7) Set the script to executable:

chmod +x /home/username/autossh.sh

8) Add it to /etc/crontab to have it run (and loop) on boot - just add the line

@reboot username /home/username/autossh.sh

From now on you SHOULD be able to ssh from your external machine directly to your internal machine on port 2022 like so:

ssh username@localhost -p 2022

You can tunnel any number of port forwards (to any home IP) over this connection like so:

ssh username@localhost -p 2022 -L 1443:192.168.1.1:443
or
ssh username@localhost -p 2022 -L 1443:192.168.1.1:443 -L 8989:192.168.1.5:8989 -L 8080:192.168.1.1:80
etc...

PUBLIC SSH ACCESS USING PASSWORDS IS A BAD IDEA!!!

The external machine is now effectively a backdoor to your home network (well, almost) - make sure to only connect to it using public key, and disable password ssh access.