#! /bin/bash
#------------------------------------------------------------------------------
case "$1" in
-h|--help)
	echo "RSSH syntaxe:"
	echo "set configuration : $0 Forwarded_port MITM_server -p port"
	echo "use: $0"
	echo "unset configuration : rm /usr/local/etc/RSSH/RSSH.conf"
	echo "------------------"
	if [ -f /usr/local/etc/RSSH/RSSH.conf ] ; then
		. /usr/local/etc/RSSH/RSSH.conf
		echo "remote connection:"
		echo "in terminal 1: ssh -L 12345:localhost:$ForwardedPort $MitmServer"
		echo "in terminal 2: ssh root@localhost -p 12345"
		echo "to skip password authentication, copy the content of /root/.ssh/id_rsa.pub to"
		echo "/root/.ssh/authorized_keys"
		echo "on both distant server and $MitmServer server"
	fi
	exit 0
	;;
esac
RsshLog="/var/log/RSSH.log"
if [ ! -d /usr/local/etc/RSSH ] ; then
	mkdir /usr/local/etc/RSSH
fi
if [ ! -f /usr/local/etc/RSSH/RSSH.conf ] ; then
	if [ ! -z "$1" ] && [ ! -z "$2" ] ; then
		echo "ForwardedPort=\"$1\"" > /usr/local/etc/RSSH/RSSH.conf
		shift
		echo "MitmServer=\"$*\"" >> /usr/local/etc/RSSH/RSSH.conf
		if ! crontab -l | grep "RSSH" ; then
			crontab -l > /tmp/crontab.txt
			echo "*/5 * * * *  /usr/local/bin/RSSH" >> /tmp/crontab.txt
			crontab  /tmp/crontab.txt
		fi
	else
		echo "RSSH syntaxe:"
		echo "set configuration : $0 Forwarded_port MITM_server -p port"
		echo "use: $0"
		echo "unset configuration : rm /usr/local/etc/RSSH/RSSH.conf"
	fi
else
	. /usr/local/etc/RSSH/RSSH.conf
	WorkingProcesses=`ps axo pid,cmd`
	if ! echo "$WorkingProcesses" | grep -q "$ForwardedPort:localhost:22 $MitmServer" ; then
		echo "" >> $RsshLog
		echo "`date` $0:$$: open reverse tunnel ssh -N -R $ForwardedPort:localhost:22 $MitmServer" >> $RsshLog
		ssh -v -N -R $ForwardedPort:localhost:22 $MitmServer >> $RsshLog
		echo "" >> $RsshLog
		echo "`date` $0:$$: close reverse tunnel ssh -N -R $ForwardedPort:localhost:22 $MitmServer" >> $RsshLog
	else
		echo -n "." >> $RsshLog
	fi
fi
exit 0

