8

Somebody answered my earlier question by describing how to create a new routing table with source policy routing:

echo 13 eth3 >> /etc/iproute2/rt_tables
ip route add default via 10.20.0.1 table eth3
ip rule add from 10.20.0.2 lookup eth3

How do I make those "ip" commands persist across a reboot? I assume that there's some appropriate lines to be added to /etc/network/interfaces. Is this the right away (adding "up" lines to the interface), or is there another way to do it?

iface eth3 inet static
    address 10.20.0.2
    netmask 255.255.255.0
    up ip route add default via 10.20.0.1 table eth3
    up ip rule add from 10.20.0.2 lookup eth3
    down ip rule del from 10.20.0.2 lookup eth3
    down ip route del default via 10.20.0.1 table eth3

(I'm on Ubuntu 12.04).

Lorin Hochstein
  • 4,868
  • 15
  • 54
  • 72
  • I never did find a good way to do it. I wrote myself script to handle that. I am somewhat willing to share it, but it is what I would call great. If your interested you can ask me about it in chat later when I get back to a 'real' computer. – Zoredache Mar 14 '13 at 21:03

2 Answers2

7

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.

4

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"
mgorven
  • 30,036
  • 7
  • 76
  • 121