Manage multiple default gateways on Linux

Here is a setup:

Linux box
eth1 - going public IPv4
eth0 - going private IPv4 (

Now I want to keep a default route for everything to the Internet x.y.z.w UG 0 0 0 eth1

But I also want to be able to ping the internal LAN from another network without NAT and echos to be routed properly.

Example of real life fucked up scenario: pings through a router -> default gw -> routed to network -> goes to that routes it to my eth0 on my linux box. Great

But the Linux box has a thing: the default route going out on eth1. So replies won't be comming back. Actually nothing will come back.

So we need to treat traffic differently, having to default routes for two possibilities. How do we do that?
Simple. Two routing tables and ip rules.

Well we need to do the following:

a) Add a new routing table on the Linux box
Edit /etc/iproute2/rt_tables and add another ID/name after the already defined ones:

255 local
254 main

we'll add
1 testtable

Nice :) - Now you have two routing tables. A geek's dream.

b) Add another default route in the new table
#ip route add default via dev eth0 table testtable

c) To use the new default route for some traffic you need some rules
#ip rule add from all to lookup testtable
#ip rule add from lookup testtable

That practically states: traffic from or to will be routed accordingly to table testtable not the default local one.

Voila! Anything comes to the machine will be routed to the Internet except traffic comming to eth0 directly.

A little note: Point b) and c) are not persistent changes. Will be lost on reboot. So if you don't want to loose your remote connectivity the way I did, place them at least in /etc/rc.local or whatever suites you.

Tested on Redhat should work on anything with iproute 2. Won't work on old kernels that are not compiled with policy routing.

Verify everything using:

cat /etc/iproute2/rt_tables - for point a)
ip route show table testtable - for point b)
ip rule - for point c)
the mighty ping.

Hope I didn't forget something mandatory.

No comments:

Post a Comment