Selective VPN Routing on Linux

If you want to route some ports to the VPN and not all, there is surprisingly little documentation on the Internet..

Here is one method that works. This is written in OORexx but can be converted to Bash easily. Assumption: The VPN IP range is within 10.8.x.x   — change it in the code if your VPN provider is different. This one is meant for the  VPN service.

Before you can use this, you need to disable the routes provided by the VPN provider. To do this, go into the Properties of your VPN configuration in the NetworkManager, and Select “Ignore automatically obtained routes.”

The following code ONLY routes http/https traffic over the VPN, and nothing else. Connect your VPN, then run the following script:

/* First enable VPN, then run this script */

/* learn VPN default gateway - it dynamically changes so we need to learn it */ 
'rxqueue /clear' 
'route -n|grep 10.8.|rxqueue' 
if queued()>0 then do 
  parse pull dest . 
say 'destination is' dest 
nonvpngateway = '' /* This is your regular gateway - without VPN enabled*/'
'iptables -t nat -A POSTROUTING -o client -j SNAT --to-source' dest 
'ip route add default via' nonvpngateway ' table 4' 
'ip rule add priority 1000 dport 443 table 3' 
'ip rule add priority 1000 dport 80 table 3' 
'ip route add default via' dest ' table 3' 
'ip route flush cache' 

Leave a Reply