#!/bin/sh

### Inverse SSH:
# This script uses ssh port forwarding to allow access to a computer inside
# a intranet.
#
## Terminology:
#   LOCAL: machine inside intranet, the one which runs this script
#   REMOTE: machine that will enable access to LOCAL, probably on internet
#
## Examples:
#
# - Access your Work machine (intranet) from Home:
#
#  PROBLEM:
#     At your Work you have a machine on a internal network with IP: 10.0.0.31
#  and you want to access it from your Home. Your Home machine is accessible
#  from your Work machine (you can ssh it).
#
#  SOLUTION:
#     Run this script from your Work machine, with configuration:
#        LOCAL_HOST=10.0.0.31
#        LOCAL_PORT=22
#        REMOTE_PORT_FW=8822
#        REMOTE_HOST=my-home-machine.dyndns.org
#        REMOTE_USER=my-user
#     Then you do:
#        At work:
#           work$ ./inverse-ssh.sh
#        At home:
#            home$ ssh -p8822 localhost
#        now you have access to your Work machine from home!
#
#
## Author: Gustavo Sverzut Barbieri <barbieri@gmail.com>
## License: GNU GPL

###############################################################################
# Configuration                                                               #
###############################################################################

# LOCAL_HOST/LOCAL_PORT: host/port on network this script runs, connections to
#    $REMOTE_HOST:$REMOTE_PORT_FW will be redirected to this.
LOCAL_HOST=192.168.0.1
LOCAL_PORT=22

# REMOTE_PORT_FW: Port on remote host to listen and 
#    redirect to $LOCAL_HOST:$LOCAL_PORT
REMOTE_PORT_FW=1111
REMOTE_HOST=my-home-dns.dyndns.org
REMOTE_USER=my-user


###############################################################################
# Code                                                                        #
###############################################################################

while true; do
    echo "$(date +"%x %X"): Inverse SSH: connections on $REMOTE_HOST:$REMOTE_PORT_FW will be redirected to $LOCAL_HOST:$LOCAL_PORT in this network." 1>&2
    ssh -C -R \
	$REMOTE_PORT_FW:$LOCAL_HOST:$LOCAL_PORT \
	$REMOTE_USER@$REMOTE_HOST \
	-o CompressionLevel=9 \
	-n sleep 365d 1>&2
done

