Tag Archives: Shell

Automate SSH reverse tunnel for remote access to local network

A RPi is deployed in an unknown local network and should connect to a public jump box. Later a user could connect to the jump box to reach the local network via the reverse tunnel.

Configure your RPi

I used a Debian 11.8 on a RPi v1 (2011.12) and install autossh and configure your reverse tunnel

example to bind 0.0.0.0:10022 on the onlinejumpbox and forward it to the RPi localhost:22 SSH server.

ssh -R 0.0.0.0:10022:localhost:22 debian@onlinejumpbox

Create and install a service with systemd in the file /etc/systemd/system/tunnel.service

[Unit]
Description=SSH tunnel service
After=network.target network-online.target sshd.service
#After=sshd.service

[Service]
ExecStart=/usr/bin/autossh -i /home/debian/.ssh/id_rsa -R 0.0.0.0:10022:localhost:22 -NT debian@onlinejumpbox
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target

Optional: in /etc/ssh/sshd_config set

PasswordAuthentication no

Configure the server

Optional: if you want the bind_address parameter to work, in /etc/ssh/sshd_config set

GatewayPorts yes

Conclusion

A user can reach the local network via this command line

ssh -p 10022 debian@onlinejumpbox

Pretty Check

Demo
prettycheck

Code

#!/bin/sh

function prettycheck {
    local TPUT='tput'
    local RED='1'
    local GREEN='2'
    local BLUE='4'
#man 5 terminfo

    [ ! -f $(which $TPUT) ] && TPUT=true

    cmd="$@"
    echo "$> $cmd"
    $TPUT cuf $((`$TPUT cols` - 8)) # move the end-of-line minus 8 cols
    $TPUT cuu 1 # move on line up
    msgerr=$($cmd 2>&1 1> /dev/null)
    if [ "$?" -ne 0 ]; then
        $TPUT setaf $RED # change front color
        echo "[FAILED]"
        $TPUT setaf $BLUE # change front color
        echo "$msgerr"
    else
        $TPUT setaf $GREEN # change front color
        echo "[  OK  ]"                                                                                   
    fi                                                                                                    
    $TPUT reset                                                                                           
}