docker-vpn/start-openvpn.sh
2022-06-30 16:45:34 +02:00

65 lines
1.4 KiB
Bash

#!/usr/bin/env bash
set -o pipefail
OVPN_LOG_FILE=/tmp/ovpnlog.txt
change_hostname() {
echo VPNDOCKER > /etc/hostname
}
create_net_dev() {
mkdir -p /dev/net
mknod /dev/net/tun c 10 200
chmod 600 /dev/net/tun
}
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
}
get_ip() {
nsout="$(nslookup -timeout=1 myip.opendns.com resolver1.opendns.com)"
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)"
}
switch_user() {
su -c "cd $OVPN_WORKDIR && "'$SHELL' -l "$OVPN_USER"
}
own_ip="$(get_ip)"
echo "OWN IP: $own_ip"
if [ "$own_ip" = "" ]; then
echo "ERROR: Failed to lookup own ip, aborting" >&2
exit 1
fi
change_hostname
create_net_dev
connect_vpn
for _ in {1..100}; do
vpn_ip="$(get_ip)"
if [ "$vpn_ip" = "$own_ip" ] || [ "$vpn_ip" = "" ]; then
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
exit 1
fi
echo "VPN IP: $vpn_ip"
switch_user