MacOS – Permanently route an host to VPN in OS X

macosvpn

I need VPN from the university to ssh to my office computer. But each time I start the VPN, I have to route the host to ppp0 manually to use it,

sudo route add lab_computer.foo ppp0

because my previous attempt of rerouting was lost. And frankly it's a pain. I wonder if it's possible to use some script to automatically reroute it every time I successfully establish the vpn connection.


PS1. I am using OS X. But I think for both unix and linux system they should be similar?

PS2. I don't want to route all connection to vpn because in that way, the connection to other hosts will be unnecessarily slowed down.

Best Answer

You can put extra configuration in /etc/ppp/ip-up file, which is described in man pppd, and which is a standard shell script file that will be fired when the pppd establishes a connection.

I don't use the VPN anymore and unfortunately it seems I don't have a copy of my ip-up file anymore, but the way I used to do it is something similar to below (you'll need to verify this with the aforementioned man page).

Once pppd establishes the connection, it will call /etc/ppp/ip-up with the following arguments:

ip-up interface-name tty-device speed local-IP-address remote-IP-address ipparam

Your ip-up script could therefore look something like:

#!/bin/bash

IFNAME="${1}"
LOCALIP="${4}"
REMOTEIP="${5}"

if [[ "${REMOTEIP}" == "192.0.2.1" ]]; then
  /sbin/route add -host lab_computer.foo -interface "${IFNAME}"
fi

Please note the following:

  1. I'm assuming that the IP address of the VPN gateway you connect to is always the same and never changes, and in the example above I'm assuming it's 192.0.2.1 (RFC5737 address range specified to use as Documentation Examples - PLEASE CHANGE IT). The comparison here is used to only add the route when you're connected via the VPN to your office, and not any other VPN or PPP connection.
  2. It's also better to use an IP address instead of the hostname for the computer you want to add a static route to. Instead of using lab_computer.foo I would use an IP address in the route command.
  3. I'm using the -interface ${IFNAME} as opposed to hard-coding ppp0, which should make this work even if you have two VPN connections established at the same time (or a VPN and another form of PPP, e.g. a 3G modem)