#!/bin/sh set -e base_dir="$HOME/.rapid-tunneling" usage() { me=`basename $0` echo >&2 "$me: Initiate a Rapid-Tunneling tunnel." echo >&2 "Usage:" echo >&2 " $me [options] remote-access-NAME.tar.gz" echo >&2 "" echo >&2 "Options:" echo >&2 " -c Copy tarball" echo >&2 " -D Don't daemonize" echo >&2 " -h HOST Connect to HOST rather the host from the tarball" echo >&2 " -p PORT Connect to PORT rather the host from the tarball" echo >&2 " -u USER Connect to USER rather the host from the tarball" echo >&2 "" } if [ -z "$1" ]; then usage exit 1 fi if [ -r /etc/rapid-tunneling/client ]; then . /etc/rapid-tunneling/client; fi opt_copy='no' opt_host='' opt_port='' opt_user='' opt_daemonize='yes' while getopts cdDh:p:u: opt; do case "$opt" in c) opt_copy='yes';; D) opt_daemonize='no';; d) opt_daemonize='yes';; h) opt_host="$OPTARG";; p) opt_port="$OPTARG";; u) opt_user="$OPTARG";; \?) usage; exit 1;; esac done shift $((OPTIND - 1)) tarball="$1" tmpdir=`mktemp -d rapid-tunneling.XXXXXX` mkdir $tmpdir/recv $tmpdir/send tar xzf "$tarball" -C $tmpdir/recv [ "$opt_host" ] && host="$opt_host" || host=`cat $tmpdir/recv/host` [ "$opt_port" ] && port="$opt_port" || port=`cat $tmpdir/recv/port` [ "$opt_user" ] && user="$opt_user" || user=`cat $tmpdir/recv/user` tunnelport=`cat $tmpdir/recv/tunnelport` ssh-keygen -q -t rsa -C rapid-tunneling -N "" -f $tmpdir/send/key # public will be in key.pub cp $tmpdir/recv/key $tmpdir/send/origkey mkdir -p $base_dir cp $tmpdir/recv/key $base_dir/key tar czf $base_dir/ra-params.tar.gz -C $tmpdir/send key origkey mkdir -p -m 700 $HOME/.ssh awk '$NF != "rapid-tunneling" {print}' $HOME/.ssh/authorized_keys > $HOME/.ssh/authorized_keys.new 2>/dev/null || true cat $tmpdir/send/key.pub >> $HOME/.ssh/authorized_keys.new mv -f $HOME/.ssh/authorized_keys.new $HOME/.ssh/authorized_keys chmod 644 $HOME/.ssh/authorized_keys rm -rf $tmpdir # Remove host key of $host (in case it has changed) ssh-keygen -R $host 2>/dev/null || true # Run in background if [ -x /sbin/start-stop-daemon ]; then SSD=/sbin/start-stop-daemon else SSD="/sbin/busybox start-stop-daemon" fi if [ "$opt_daemonize" = 'yes' ]; then SSD_CMD="$SSD -S -b -m -p $base_dir/pid -x /bin/sh -- -c" else SSD_CMD="/bin/sh -c" fi if [ "$opt_copy" = 'yes' ]; then cp "$tarball" "$base_dir/remote-access.tar.gz" fi $SSD_CMD "exec env SSH_AUTH_SOCK= ssh -o 'StrictHostKeyChecking no' -o 'BatchMode yes' -o 'ServerAliveInterval 60' -T -p $port -i $base_dir/key -R $tunnelport:127.0.0.1:22 -l $user $host < $base_dir/ra-params.tar.gz"