Skip to content

Instantly share code, notes, and snippets.

@thielemans
Last active February 7, 2019 14:08
Show Gist options
  • Save thielemans/e03815c2debc1f6af84dcd94fdb10ebc to your computer and use it in GitHub Desktop.
Save thielemans/e03815c2debc1f6af84dcd94fdb10ebc to your computer and use it in GitHub Desktop.
VPN routing script to only routes traffic for a specified user/group over VPN
File: routing.up (chmod 0775)
#!/bin/sh
iptables -t mangle -A OUTPUT -m owner --uid-owner vpnusername -j MARK --set-mark 3 #Change vpnusername
iptables -t nat -A POSTROUTING -o ${dev} -j SNAT --to-source ${ifconfig_local}
ip rule add fwmark 3 lookup 200
ip route add 192.168.1.0/24 dev eth0 table 200 # Change the IP to your LAN IP
ip route add default via ${route_vpn_gateway} dev ${dev} table 200
sysctl -w net.ipv6.conf.all.disable_ipv6=1 #Disable IPv6 to avoid leaking
File: routing.down (chmod 0775)
#!/bin/sh
iptables -t mangle -D OUTPUT -m owner --uid-owner vpnusername -j MARK --set-mark 3 #Change vpnusername
iptables -t nat -D POSTROUTING -o $1 -j SNAT --to-source $4
#iptables -t nat -D POSTROUTING -o ${dev} -j SNAT --to-source ${ifconfig_local}
ip rule delete fwmark 3
ip route flush table 200
sysctl -w net.ipv6.conf.all.disable_ipv6=1 #Enable IPv6 again
Add to openVPN config file:
route-noexec
script-security 2
route-up /etc/openvpn/routing.up
route-pre-down /etc/openvpn/routing.down
Test via:
curl https://ipinfo.io/ip
sudo -u vpnusername curl https://ipinfo.io/ip #Change vpnusername
Based on https://www.reddit.com/r/raspberry_pi/comments/4ahjgq/is_it_possible_to_route_only_torrent_traffic/ and https://0xacab.org/snippets/3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment