A case for SSH remote port forwarding

2021-07-25 @Technology

I’ve often relied on SSH local forwarding to expose a private remote (web) service to my local machine. Yet I’ve somehow managed to avoid SSH remote forwarding, which exposes a private local service to the world through a proxy of a public-facing remote server. Recently I’ve faced precisely such a necessity, for which I demonstrate the steps.

As I travelled, I realized I’d require SSH access to another machine running at home (let’s call it A), which I wasn’t about to expose directly in a sane frame of mind. I do, however, have access to a public facing VPS server, called V. And let’s call my travelling tablet C.

At A:

ssh -f -N -R 6345:localhost:22 [user>@]V

The flags -f and -N insure the remote forwarding connection confines to the background. 6345 is a randomly chosen port to forward to V the local SSHD daemon on port 22.

At V:

Within /etc/ssh/sshd_config, insure the setting GatewayPorts is set to yes. The setting makes any remote-forwarded ports available not strictly via the local interface, but externally. Restart the sshd daemon if modified the config: service sshd restart.

Wherever you control the firewall settings for V: expose the TCP port 6345.

At C:

ssh [user@]V -p 6345

The above steps correctly followed, this should land you at the familiar terminal of A.


Since you are physically away from A, what happens if A’s network connection temporarily drops or the forwarding socket bails for some reason? Without preventative action taken on your part, you will be locked out of your home server.

A more thorough approach would involve running a scheduled service to check for the dropped connection and restart if necessary.

As for me, handling this in a rush, I didn’t even bother checking for a working connection. Nor did I use cron, thinking it might lack requirements available to my running shell. Rather, I enqueued a handful of at jobs throughout different days that would forcibly start the remote forwarding, which somehow didn’t interfere with the prior working sessions.

Example (on A):

at 12:00 +2 day <<< "ssh -f -N -R 6345:localhost:22 [user>@]V"

(The overall setup not being something I’d wish available for too long a period, the slight redundancy of labor isn’t much of an issue.)

Of course, the enqueuing of these jobs presumes an active agent with your ssh-key properly cached (or a passwordless key). That part I won’t here detail.

Questions, comments? Connect.