diff --git a/vpnerator.sh b/vpnerator.sh index 0ee8206..a074bad 100755 --- a/vpnerator.sh +++ b/vpnerator.sh @@ -8,8 +8,8 @@ HOST=$1 HOST_ADDR=$(echo ${HOST} | awk -F '@' '{ print $NF }') -INTERFACE_NAME=tun RAND=$(tr -dc 'a-zA-Z0-9' < /dev/urandom | fold -w 8 | head -1) +INTERFACE_NAME=tun-${RAND} SERVER_ADDR=10.99.255.1/24 CLIENT_ADDR=10.99.255.2/32 DNS=8.8.8.8 @@ -46,17 +46,26 @@ deps() { return 0 } +remove_interface() { + exec_sudo iptables -D FORWARD -i \$1 -j ACCEPT + exec_sudo iptables -D FORWARD -o \$1 -j ACCEPT + exec_sudo iptables -t nat -D POSTROUTING -s "${CLIENT_ADDR}" -o \${DEFAULT_IFACE} -j MASQUERADE + exec_sudo ip link del dev \$1 +} + cleanup() { - if ip link show ${INTERFACE_NAME} type wireguard > /dev/null 2>&1 ; then - exec_sudo iptables -D FORWARD -i ${INTERFACE_NAME} -j ACCEPT - exec_sudo iptables -D FORWARD -o ${INTERFACE_NAME} -j ACCEPT - exec_sudo iptables -t nat -D POSTROUTING -o \${DEFAULT_IFACE} -j MASQUERADE - exec_sudo ip link del dev ${INTERFACE_NAME} - exec_sudo sysctl -wq net.ipv4.ip_forward=0 + sudo sysctl -wq net.ipv4.ip_forward=0 + + EXIST_INTERFACE=\$(ip addr show to ${SERVER_ADDR} | head -1 | awk '{ print \$2 }' | cut -d':' -f1) + + if [ ! -z "\${EXIST_INTERFACE}" ] ; then + remove_interface \${EXIST_INTERFACE} + return 0 + elif ip link show ${INTERFACE_NAME} type wireguard > /dev/null 2>&1 ; then + remove_interface ${INTERFACE_NAME} return 0 - else - return 1 fi + return 1 } END ) @@ -100,7 +109,7 @@ exec_sudo ip link set mtu 1420 up dev "${INTERFACE_NAME}" exec_sudo iptables -A FORWARD -i "${INTERFACE_NAME}" -j ACCEPT exec_sudo iptables -A FORWARD -o "${INTERFACE_NAME}" -j ACCEPT -exec_sudo iptables -t nat -A POSTROUTING -o "\${DEFAULT_IFACE}" -j MASQUERADE +exec_sudo iptables -t nat -A POSTROUTING -s "${CLIENT_ADDR}" -o "\${DEFAULT_IFACE}" -j MASQUERADE END if [ "$?" -ne 0 ]; then