Conditional Routing over VPN in OSX

When connecting to a VPN, you may want to route some of your traffic to a specific gateway (and thus network). This is more than likely true if you have the option in your VPN connection to route all traffic through the VPN. OSX has two scripts that run when you connect and disconnect a VPN: /etc/ppp/ip-up and /etc/ppp/ip-down, respectively.

If you have more than one VPN, there is a way to determine which VPN you connect to and act accordingly. In my case, I used the host command to parse out the VPN server IP address (this won’t be necessary if you know you have a static IP, but I’m on a dynamic IP and I didn’t want to have to change this script if my work happened to change their VPN IP at some point):

#!/bin/sh

home_vpn_ip=`host vpn.homedomain.com | grep -m 1 "has address" | awk '{printf "%s", $4}'`
work_vpn_ip=`host vpn.workdomain.com | grep -m 1 "has address" | awk '{printf "%s", $4}'`

if [ "${5:-}" = "$work_vpn_ip" ]
then
    /sbin/route add 10.0.0.0/8 $5
elif [ "${5:-}" = "$home_vpn_ip" ]
then
    /sbin/route add 192.168.0.0/16 $5
else
    /bin/echo "Not found - ${5:-}" > ~/ip-up.err
fi

Then, subsequently in your ip-down script:

#!/bin/sh

home_vpn_ip=`host vpn.homedomain.com | grep -m 1 "has address" | awk '{printf "%s", $4}'`
work_vpn_ip=`host vpn.workdomain.com | grep -m 1 "has address" | awk '{printf "%s", $4}'`

if [ "${5:-}" = "$work_vpn_ip" ]
then
    /sbin/route delete 10.0.0.0/8
elif [ "${5:-}" = "$home_vpn_ip" ]
then
    /sbin/route delete 192.168.0.0/16
else
    /bin/echo "Not found - ${5:-}" > ~/ip-down.err
fi

Make sure you sudo chmod 755 the files after you create them.

See jms1.net