Routing a particular subnet into a VPN tunnel
This can be achieved using a custom routing table and policy (I recently did something very similar myself)
-
Firstly create a custom routing table for your VPN
echo "10 vpn" >> /etc/iproute2/rt_tables
-
Tell iproute2 to use this routing table for traffic to and from your 192.168.2.0 network
ip rule add from 192.168.2.0/24 table vpn ip rule add to 192.168.2.0/24 table vpn
-
Set up NAT masquerading for the 192.168.2.0 network
iptables -A FORWARD -i eth0:2 -s 192.168.2.0/24 -j ACCEPT iptables -A FORWARD -i tun0 -d 192.168.2.0/24 -j ACCEPT iptables -t nat -A POSTROUTING -s 192.168.2.0/24 -o tun0 -j MASQUERADE
-
Enable IP forwarding if it's not enabled (required for NAT)
echo 1 > /proc/sys/net/ipv4/ip_forward
-
In your OpenVPN config add the following lines
#Prevents default gateway from being set on the default routing table route-noexec #Allows route-up script to be executed script-security 2 #Calls custom shell script after connection to add necessary routes route-up /etc/openvpn/route-up.sh
-
Create a custom shell script in /etc/openvpn/route-up.sh and chmod +x it
#!/bin/sh #Clear all routes on vpn routing table (this is to make sure there isn't any crap left over from a previous vpn connection /sbin/ip route flush table vpn #Copy routing table from main routing table into vpn table /sbin/ip route show table main | grep -Ev ^default | while read ROUTE ; do ip route add table vpn $ROUTE; done #Add default gateway to vpn routing table /sbin/ip route add default via ${route_vpn_gateway} dev ${dev} table vpn
Steps 2 and 3 will not persist across reboots so you will need to add those parts to your init scripts as required.