aboutsummaryrefslogtreecommitdiffstats
path: root/covpn/covpn.sh
blob: 613990998f9cd3a713b2a288a2a419ddb837e694 (plain) (blame)
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
#!/bin/sh

# covpn - Wrapper to run OpenVPN with server push filtering, tcp/udp/defgw modes
# 2013 Laurent Ghigonis <laurent@gouloum.fr>

# Works together with correct openvpn-up.sh
# Uses same config file for UDP and TCP, passing --proto and --remote in command line
# Change of default gateway and DNS is done in openvpn-up.sh
# Passes env var 'openvpn_gateway' to openvpn-up.sh in case default gw is set to VPN
# Passes env var 'covpn_conf' to openvpn-up.sh to load it's configuration

usage_exit() {
	echo "`basename $0` [-g] [-t] <conf_path>"
	exit 1
}

restore() {
	restore_gateway
	restore_dns
}

restore_gateway() {
	echo "INFO: check_gateway"
	gw_cur=`ip route show 0/0 |cut -d' ' -f3`
	echo "INFO: gw_cur=$gw_cur"
	if [ "$gw_before" != "$gw_cur" ]; then
		echo "INFO: Gateway changed (before=$gw_before, cur=$gw_cur)"
		echo "INFO: Restoring previous default gw"
		/usr/sbin/ip route delete default
		/usr/sbin/ip route add default via $gw_before
	fi
}

restore_dns() {
	echo "INFO: check_dns"
	if [ -f /etc/resolv.conf.bak-covpn ]; then
		echo "INFO: restoring previous DNS"
		mv /etc/resolv.conf.bak-covpn /etc/resolv.conf
	fi
}

if [ `id -u` -ne 0 ]; then
	echo "must be root"
	exit 1
fi

gw_before=`ip route show 0/0 |cut -d' ' -f3`

opts="$(getopt -o gth -l gateway,tcp,help -n "$program" -- "$@")"
openvpn_proto="udp"
gateway=0
err=$?
echo "INFO: gw_before=$gw_before"
eval set -- "$opts"
while true; do case $1 in
	-g|--gateway) gateway=1; shift;;
	-t|--tcp) openvpn_proto="tcp"; shift ;;
	-h|--help) usage_exit ;;
	--) shift; break ;;
esac done
test $err -ne 0 && usage_exit
test $# -lt 1 && usage_exit
conf_path=`readlink -f $1`
shift

covpn_conf="$conf_path/covpn.conf"
if [ ! -f $covpn_conf ]; then
	echo "ERROR: missing covpn.conf in $conf_path !"
	exit 1
fi
. $covpn_conf

if [ $openvpn_proto = "udp" ]; then
	openvpn_remote="$CONF_UDP_REMOTE"
else
	openvpn_remote="$CONF_TCP_REMOTE"
fi

trap restore INT TERM EXIT

/usr/sbin/openvpn --setenv openvpn_gateway $gateway \
	 --setenv covpn_conf $covpn_conf \
	--cd $conf_path --config openvpn.conf --chroot $conf_path \
	--proto $openvpn_proto --remote $openvpn_remote $@