Permanently adding source policy routing rules

Different administrators accomplish this in different ways.

I'm primarily using Debian and I feel the "most correct", correct being defined as the most obvious, integrated and documented way to do this , is by adding post-up directives to your /etc/network/interfaces file as you have done. If you do this make sure you don't cheat and just put all your up or post-up directives under one interface. Have each interface add the routes that appropriate to it.

The other way I've commonly seen this done is with a custom init script very similar to one @mgorven has posted.


I've written an if-up script which automatically does this for every non-loopback interface. (I've just modified it to deal with non-DHCP interfaces without a defined gateway, so it may be buggy.) The routing tables need to be created beforehand.

/etc/network/if-up.d/source-route:

#!/bin/sh
set -e

if [ "$METHOD" = loopback ]; then
    exit 0
elif [ "$METHOD" = dhcp ]; then
    IF_ADDRESS="$(echo "$IP4_ADDRESS_0" | cut -d'/' -f1)"
    IF_GATEWAY="$(echo "$IP4_ADDRESS_0" | cut -d' ' -f2)"
elif [ "$METHOD" = static]; then
    if [ ! "$GATEWAY" ]; then
        IF_GATEWAY="$(echo "$IF_ADDRESS" | cut -d. -f1-3).1"
    fi
fi

ip route flush table "$IFACE"
ip route add default via "$IF_GATEWAY" table "$IFACE"
ip rule del lookup "$IFACE" || true
ip rule add from "$IF_ADDRESS" lookup "$IFACE"