Saturday, March 21, 2015

Better Way To Force Traffic Through a VPN

I have been looking for a simple way to allow traffic to local subnets and a VPN server, but nothing else, and in a way that utilizes UFW (uncomplicated firewall). The script from my last post worked, but only if the default policies were set to ACCEPT, which is not what we want. It appears that UFW messes up your custom rules if they are in unmanaged chains. After a little research, I found a better solution.

This script allows access to all private IP ranges, so you won't have to adjust the rules if you are on a network with a different subnet. It's basically the same things, except the default input, output, and forward chains may be set to DENY, and UFW manages everything, so there's no chance of things breaking.

An even better solution would be to only allow outgoing traffic on the VPN port and only to the VPN IP address. And an even better solution would be to do that, and also make sure the connection originates from OpenVPN. That's tricky because it runs as user 'nobody' or 'root'... so you'd have to run it as it's own user.

However, for those of us that just want a simple 'killswitch' of sorts, this will do that trick. Original author Thomas Butz, modified by me for portability, flexibility, and also removed ipv6 multicast support.

#!/bin/bash
# Need root. Not doing "sudo everything" makes script more portable
if [[ $EUID -ne 0 ]]; then
   echo "Got root?"
   exit 1
fi



#First, define your vpn's listening port:
vpnPORT=1194
#And interface (usually tun0 or tap0)
vpnITF=tun0
#Flush our current chains:
#
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X

# Make sure UFW doesn't break anything
ufw reset

#Now for our UFW defaults:
ufw default deny incoming
ufw default deny outgoing

ufw default deny forward

# DNS Queries should pass to initiate the connection
ufw allow out 53

ufw allow out $vpnPORT
# Allow out on virtual NIC
ufw allow out on $vpnITF
#Note: If there are any private subnets you need to reach while you are
#connected to the VPN, add them here:
#Example: ufw allow out on eth0 to 192.168.1.0/24
#Ensure access to all private networks.
#You may want to restrict these to certain subnets, up to you.
ufw allow out to 192.168.0.0/16
ufw allow out to 172.16.0.0/12
ufw allow out to 10.0.0.0/8

#
# These rules may be ommitted, but for the sake of 'just work!':
#
# Allow ipv4 muticast

ufw allow out to 224.0.0.0/24
ufw allow out to 239.0.0.0/8
# Allow local ipv6

ufw allow out to ff01::/16

#Finally, turn it on


ufw enable

This time, (I promise) it really is idiot proof.

No comments:

Post a Comment