summaryrefslogtreecommitdiff
path: root/rapid-tunneling
blob: 996c9df1cb4a3015743cae58139b49c8a385a527 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/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"