Public
Snippet $29862 authored by Fredrik Rambris

OpenVPN up-script that captures transmission traffic and sends it through the tunnel

up.sh
#!/bin/sh

INTERFACE=$1
IP=$4

LOCALNET=192.168.1.0/24

#set -x

for IPTABLES in /usr/sbin/iptables /usr/sbin/ip6tables ; do
	# Clear our tables
	$IPTABLES -F INPUT
	$IPTABLES -t mangle -F OUTPUT
	$IPTABLES -t nat -F POSTROUTING

	# Make sure we drop any incoming connections via VPN
	$IPTABLES -A INPUT -i $INTERFACE -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
	$IPTABLES -A INPUT -i $INTERFACE -m limit --limit 2/min -j LOG --log-prefix "VPN-IN "
	$IPTABLES -A INPUT -i $INTERFACE -j DROP

	# Not sure why
	$IPTABLES -t nat -I POSTROUTING -o $INTERFACE -j MASQUERADE
done

# Mark outgoing packets of certain users
for u in transmission flexget ; do
	# Exempt packets going to local network
	/usr/sbin/iptables -t mangle -A OUTPUT -d $LOCALNET -m owner --uid-owner $u -j RETURN
	/usr/sbin/iptables -t mangle -A OUTPUT -m owner --uid-owner $u -j MARK --set-mark 42
	/usr/sbin/ip6tables -t mangle -A OUTPUT -m owner --uid-owner $u -j MARK --set-mark 42
done

# Route all marked packages via routing table 42
/usr/sbin/ip rule add fwmark 42 table 42

# Not sure. Guessing clearing routing filters
for f in /proc/sys/net/ipv4/conf/*/rp_filter; do
    echo 0 > $f
done

# Route all packets in routing table 42 via VPN interface IP
/usr/sbin/ip route add default via $IP table 42

# Now, start the transmission service
/usr/bin/systemctl start transmission-daemon.service || /bin/true

# Wait for it to start up
sleep 5

# Allow connections to transmission.
# netstat all listening ports and allow traffic to those ports
/usr/bin/netstat -nlp | grep $( /usr/sbin/pidof transmission-daemon )/ | grep -v tcp6 | grep -v ":9091" | awk '{ print $1"\t"$4 }' | sed "s/:/\t/g" | grep 0.0.0.0 | while read proto ip port ; do
	echo "Opening for $proto/$port on $INTERFACE"
	/usr/sbin/iptables -A INPUT -i $INTERFACE -p $proto --dport $port -m conntrack --ctstate NEW -j ACCEPT
	/usr/sbin/ip6tables -A INPUT -i $INTERFACE -p $proto --dport $port -m conntrack --ctstate NEW -j ACCEPT
done

for IPTABLES in /usr/sbin/iptables /usr/sbin/ip6tables ; do
	# Remove the topmost log+drop
	$IPTABLES -D INPUT -i $INTERFACE -m limit --limit 2/min -j LOG --log-prefix "VPN-IN "
	$IPTABLES -D INPUT -i $INTERFACE -j DROP

	# Add it to the bottom
	$IPTABLES -A INPUT -i $INTERFACE -m limit --limit 2/min -j LOG --log-prefix "VPN-IN "
	$IPTABLES -A INPUT -i $INTERFACE -j DROP
done