docker-vpn/start-openvpn.sh

66 lines
1.4 KiB
Bash
Raw Normal View History

2021-08-07 20:36:47 +02:00
#!/usr/bin/env bash
set -o pipefail
OVPN_LOG_FILE=/tmp/ovpnlog.txt
2021-08-07 20:36:47 +02:00
change_hostname() {
echo VPNDOCKER > /etc/hostname
}
2021-08-07 18:24:20 +02:00
create_net_dev() {
mkdir -p /dev/net
mknod /dev/net/tun c 10 200
chmod 600 /dev/net/tun
}
2021-08-07 19:54:15 +02:00
connect_vpn() {
sed -e 's|^up .*$|up /etc/openvpn/up.sh|' \
-e 's|^down .*$|down /etc/openvpn/down.sh|' \
-e 's|^auth-user-pass.*$|auth-user-pass|' \
"$OVPN_CONFIGURATION_FILE" > /tmp/ovpn.conf
openvpn --config /tmp/ovpn.conf --log "$OVPN_LOG_FILE" --daemon
2021-08-07 19:54:15 +02:00
}
2021-08-07 20:36:47 +02:00
get_ip() {
2021-11-28 02:53:29 +01:00
nsout="$(nslookup -timeout=1 myip.opendns.com resolver1.opendns.com)"
2021-08-07 20:36:47 +02:00
if [ "$?" != 0 ]; then
echo "WARN: Failed to run nslookup" >&2
fi
echo "$nsout" | grep -o 'Address:.*' | grep -Eo '(\d+\.?){4}' | tail -n1
}
print_ip() {
echo "VPN IP: $(get_ip)"
}
2021-08-07 20:09:36 +02:00
switch_user() {
2022-03-24 01:32:10 +01:00
su -c "cd $OVPN_WORKDIR && "'$SHELL' -l "$OVPN_USER"
2021-08-07 20:09:36 +02:00
}
2021-08-07 20:36:47 +02:00
own_ip="$(get_ip)"
echo "OWN IP: $own_ip"
2021-11-28 02:53:29 +01:00
if [ "$own_ip" = "" ]; then
echo "ERROR: Failed to lookup own ip, aborting" >&2
exit 1
fi
2021-08-07 20:36:47 +02:00
change_hostname
2021-08-07 18:24:20 +02:00
create_net_dev
2021-08-07 19:54:15 +02:00
connect_vpn
for _ in {1..100}; do
2021-08-07 20:36:47 +02:00
vpn_ip="$(get_ip)"
2021-11-28 02:53:29 +01:00
if [ "$vpn_ip" = "$own_ip" ] || [ "$vpn_ip" = "" ]; then
2021-08-07 20:36:47 +02:00
sleep .1
else
break
fi
done
if [ "$vpn_ip" = "$own_ip" ] || [ "$vpn_ip" = "" ]; then
echo "ERROR: Failed to connect to VPN (vpn_ip=$vpn_ip), aborting" >&2
echo "Ovpn log:" >&2
cat "$OVPN_LOG_FILE" >&2
2021-08-07 20:36:47 +02:00
exit 1
fi
echo "VPN IP: $vpn_ip"
2021-08-07 20:09:36 +02:00
switch_user