Files
deluge-netns-VPN/vpn-deluge-daemon.sh

86 lines
2.6 KiB
Bash

#!/usr/bin/env zsh
# Must be run as root:
if [[ "${UID}" -ne "0" ]]; then
printf "This script must be run as root.\n"
exit 1
fi
function start() {
# Create the net network namespace
ip netns add vpnns
# Start the loopback interface in the namespace
ip netns exec vpnns ip addr add 127.0.0.1/8 dev lo
ip netns exec vpnns ip link set lo up
# Create virtual network interfaces that will let OpenVPN (in the namespace)
# access the real network, and configure the interface in the namespace (vpn1)
# to use the interface out of the namespace (vpn0) as its default gateway
ip link add vpn0 type veth peer name vpn1
ip link set vpn0 up
ip link set vpn1 netns vpnns up
ip addr add 10.200.200.1/24 dev vpn0
ip netns exec vpnns ip addr add 10.200.200.2/24 dev vpn1
ip netns exec vpnns ip route add default via 10.200.200.1 dev vpn1
# Enable IPv4 routing and NAT for the interface in the namespace.
# As my default interface is a wireless one, I use wl+ (which may match wlan0, wlp3s0, etc.)
# in iptables for the outgoing interface; if you use a wired interface you should probably
# use en+ (or br+ for a bridged interface)
iptables -A INPUT \! -i vpn0 -s 10.200.200.0/24 -j DROP
iptables -t nat -A POSTROUTING -s 10.200.200.0/24 -o en+ -j MASQUERADE
sysctl -q net.ipv4.ip_forward=1
# Configure the nameserver to use inside the namespace
mkdir -p /etc/netns/vpnns
echo 'nameserver 8.8.8.8' > /etc/netns/vpnns/resolv.conf
# Start OPENVPN connection
ip netns exec vpnns openvpn --config /home/cruiser/openvpn-files/delugevpn.ovpn &!
while ! ip netns exec vpnns ip a show dev tun0 up; do
sleep .5
done
# Start the deluge-deamon
ip netns exec vpnns sudo -u deluge deluged &!
# Start the deluge-web-interface
ip netns exec vpnns sudo -u deluge deluge-web &!
# Listen on 'main' network and redirect to the network namespace
socat tcp-listen:8112,reuseaddr,fork tcp-connect:10.200.200.2:8112 &!
socat tcp-listen:58846,reuseaddr,fork tcp-connect:10.200.200.2:58846 &!
}
function stop() {
ip netns pids vpnns | xargs -rd'\n' sudo kill
ip netns del vpnns
lsof -i tcp:8112 | grep "*:8112" | awk '{print $2}' | xargs kill
lsof -i tcp:58846 | grep "*:58846" | awk '{print $2}' | xargs kill
rm -rf /etc/netns/vpnns
sysctl -q net.ipv4.ip_forward=0
iptables -D INPUT \! -i vpn0 -s 10.200.200.0/24 -j DROP
iptables -t nat -D POSTROUTING -s 10.200.200.0/24 -o en+ -j MASQUERADE
ip link delete vpn0
}
case "${1}" in
"start")
start ;;
"stop")
stop ;;
*)
printf "Usage:\n\tsudo ./vpn-deluge-daemon.sh start|stop\n"
exit 1
;;
esac