Reverse-tunnel SSH through NAT: Remote-access a computer that is behind a NAT router/firewall without manually forwarding ports on the router

Using port-forwarding over an SSH connection allows one to set up a SSH reverse-proxy server, allowing SSH access to a machine that cannot receive incoming connections (e.g. behind NAT firewall/router) by proxying them through a machine which can (e.g. a cheap VPS)

Problem: Dynamic IP, NAT and a bad router

While travelling around Europe (and now, living in Estonia), I occasionally want to connect to my home PC in order to backup photos to it from my camera, or to copy music from it to my phone. Unfortunately my PC is at the family house (now that I don’t have a UK house) and they have a crappy ISP router which “forgets” its settings every time the ISP pushes some new pointless stealth update to it.  The dynamic IP problems arising from the cheap ISP are easily resolved via my Dynamic DNS package, however that isn’t even necessary for the solution in this article.

Reverse port forwarding

This means that my PC in England essentially cannot receive connections from the outside world. However it can make connections. This is where “port backwarding” or rather “reverse port forwarding” comes in.  In typical port forwarding over tunnels, you connect to some other device and messages sent to some port on your end are forwarded down the tunnel to the other end.  In a reverse port forward, you connect to some other device and instruct it to forward packets back down the tunnel to you.

When my PC is powered on, a service loads which creates a tunnel to one of my cloud servers. On the remote end of this tunnel, a port on the server is forwarded back down the tunnel to my home PC. Therefore, connections made to that port on the server are forwarded down the tunnel to my home PC. Hence, my home PC can receive connections from the outside world, as long as they are passed through the tunnel that it created to the outside world. This is similar to a VPN, but much simpler and also quick and easy to configure.  In order to prevent me from having to enter a password for SSH login every time the service starts, I use public key authentication*.  If security is not an issue, you can also create port forwarding (reverse and forward) via netcat and pipes.

* I actually use this between ALL my secured PCs and servers, and disable password login.  This vastly reduces the risk of Chinese botnets getting into my networks.  The server hosting this blog (and others) gets on average three failed login attempts per second from China, plus some from other parts of the world too.  An IPTables rule-set restricting connection initiation rates on certain ports also hardens security against these bots somewhat.

Remote wake-on-lan without VPN or DDNS

First, to power my PC on remotely, I issue a command to one of my cheap cloud servers. A service running on a Raspberry Pi in the England house creates a connection to my cloud server.  The cloud server uses this connection to notify the Pi when a “power on” command is received by the server.  The Pi uses Wake-on-lan to power my PC on – much cheaper and simpler than the 1980’s power-relay method.  My PC powers on and the “port backwarding” service starts.  This method does not require a VPN or my Dynamic DNS service.  Nor is my old remote wake-on-lan interface needed any more.

The code

The service on my home PC runs the following:
[code language=”bash”]ssh -nNTR remoteIntf:remotePort:localHost:localPort remoteUser@remoteHost[/code]
This creates an SSH tunnel between localHost and remoteHost, and forwards any packets bound for remoteIntf:remotePort on remoteHost to localHost:localPort. Using this, we can forward ports from the remote host to any host/port on our local network. In this case, the machine creating the tunnel is also the target for the port forwarding, so we have:
[code language=”bash”]ssh -nNTR localhost:9000:localhost:22 server-user@cloud-server[/code]
which listens for packets via local loopback, port 9000 on the remote host, and forwards them over the tunnel to local loopback, port 22 (SSH port) on the home PC.

I could of course use this on the Pi instead, to tunnel from Pi to server, forward from server throuh Pi to PC:
[code language=”bash”]ssh -nNTR localhost:9000:home-pc:22 server-user@cloud-server[/code]
But I see no advantage in forwarding through the Pi, and it will definitely slow things down a little. Also if I decide to reboot the Pi then I would lose my connection to the home PC via this method.

Using the first method (service on home PC initiates reverse forwarding), to create an SSH connection to my home PC, I simply log onto my cloud server via SSH/Putty and issue:
[code language=”bash”]ssh home-user@localhost -p 9000[/code]
which creates an SSH connection through local loopback to port 9000 – which is forwarded over the previously-created tunnel to my home PC’s SSH port (22).

If I bind the tunnel to the public IP of my server, then I can connect to my home PC from my SSH client here, rather than logging into my server first.

This has security risks, so to enable it you must first set the following in /etc/ssh/sshd_config:
[code language=”bash”]GatewayPorts=yes[/code]
Service on target PC:
[code language=”bash”]ssh -nNTR cloud-server:9000:localhost:22 cloud-user@cloud-server[/code]
Connection from other PC/phone/tablet:
[code language=”bash”]ssh home-user@cloud-server -p 9000[/code]
Obviously, change the user-names and server names/ports to your own preferred values, I use home-user/cloud-user/cloud-server/9000 as examples here.

One-liner to duplicate database over network

Here is a handy little bash pipeline that I used to transfer a MariaDB database from a development system (in the USA) to the production system (in Europe).  It’s really a one liner, but this website isn’t wide enough to display it all on one line:

mysqldump -u root --password=<password> --databases <databases> |
ssh <user@target> "mysql -u root --password=<password>"

Note that this will drop any existing database on the target system with the same name as the one being duplicated.

If you use public-key cryptography rather than passwords for ssh authentication, then this will run with no user input necessary at all.

For a demonstration, use the following shell scripts:

Script to create example database:

#!/usr/bin/env sh
mysql -u root -p <<quit
create database lemon;
use lemon;
create table lime (field1 VARCHAR(32), field2 int);
insert into lime values ("zesty", 42);
quit

Script to copy example database to another system:

#!/bin/bash

# Prompts the user for input, stores input in variable, uses existing value if
# user provides no input.
# Parameters: prompt, default value, variable name, [optional: silent?]
function prompt {
        local def line silent
        def="$2"
        [ -z "$def" ] && def=`eval echo -n '$'"$3"`
        [ -z "$def" ] && val="" || val=" ($def)"
        echo -n "$1$val: "
        [ "$4" ] && silent="-s" || silent=""
        read $silent line
        [ -z "$line" ] && eval $3="$def" || eval $3="$line"
        [ "$silent" ] && echo ""
}

# Default values
DBNAME=lemon
DBUSER=root
DBPASS=
SSHOST=

# Get input from user
prompt "Database name" "$1" DBNAME
prompt "Database username" "$2" DBUSER
prompt "Database password" "" DBPASS "-s"
prompt "SSH target host" "$3" SSHOST

# A nice one/two-liner (well one-line if you replace the variables with useful
# values, and ditch the above code)
mysqldump -u "$DBUSER" --password="$DBPASS" --databases "$DBNAME" |
ssh "$SSHOST" "mysql -u \"$DBUSER\" --password=\"$DBPASS\""

This script assumes that an SSH server is enabled on the target machine, and that the MySQL root passwords are the same on both systems.

Then to see the copied database (run on the target system):

echo "select * from lemon.lime;" | mysql -p

Or if you can’t be bothered opening an interactive shell on the target system:

echo "select * from lemon.lime;" | ssh <user@target> "mysql -p"