Pages

Saturday

Manage multiple default gateways on Linux

Here is a setup:

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

Now I want to keep a default route for everything to the Internet
0.0.0.0 x.y.z.w 0.0.0.0 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:


10.10.2.2 pings through a router 192.168.163.2

10.10.2.2 -> default gw 10.10.2.1 -> routed to 192.168.163.0/24 network -> goes to 192.168.163.1 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 192.168.163.1 dev eth0 table testtable

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

That practically states: traffic from or to 192.168.163.2 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