I want to setup nat on a server/router with a multiple public ip addresses (on different subnets and with different gateways, but the same physical ethernet interface), using address A for all local traffic originating from the server, and address B for other machines behind the nat. I've done plenty of simple nat setups before but rarely worked with multiple non-localnet-only addresses on the same machine. Assuming the setup I want is possible, how do I go about setting it up?
2 Answers
As i understand from your requirement, you need to have two nat , one for the local network and another for the server itself. You want local ips/ LAN should go out via address A and Server generated traffic should go via address B.
First Add address A and address B on external ethernet via sub interface.
ifconfig eth0 address A/x.x.x.x
ifconfig eth0:1 address B/x.x.x.x
Second Add the SNAT rule for LAN network
iptables -t nat -A POSTROUTING -s < LAN IP NETWORK > -o eth0 -j SNAT --to < address a >
Third Add the SNAT for the rest (this will include the souce machine also)
iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to < address B >
if this does not work, we can test.
-
Unfortunatel, this won't work (very well, if at all), as it ignores the routing issues. If the [lowest metric] gateway is route A, all traffic which is not through a known route will exit via route A, regardless of source address. Thus outgoing traffic will (pretty much) all go out 1 interface, and depending on if the providers do EGRESS filtering may or may not come back through one of the routers.– davidgoCommented Feb 24, 2014 at 5:22
-
I was going to respond with a full howto, but its quite long. have a look at serverfault.com/questions/165182/policy-based-routing and tldp.org/HOWTO/Adv-Routing-HOWTO/lartc.rpdb.simple.html for a starting point.– davidgoCommented Feb 24, 2014 at 5:31
Assuming we have one primary interface A
called eth0
:
inet 192.168.1.1 netmask 255.255.255.0 broadcast 192.168.1.255
and another interface B
called eth1
:
inet 192.168.2.1 netmask 255.255.255.0 broadcast 192.168.2.255
Also there's third network C
in subnet 10.0.0.0/24
from which we want to route traffic to either A
or B
.
First of all check ip rule ls
:
0: from all lookup local
32766: from all lookup main
32767: from all lookup default
and main routing policy ip route list table main
default via 192.168.1.1 dev eth0
10.0.0.0/24 dev lxc proto kernel scope link src 10.0.0.1
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.1 metric 100
Now we want to add a rule for a mailserver with IP address 10.0.0.13
to route via B
interface.
echo "200 mail" >> /etc/iproute2/rt_tables
ip rule add from 10.0.0.13 table mail
check routing table ip rule ls
0: from all lookup local
32765: from 10.0.0.13 lookup mail
32766: from all lookup main
32767: from all lookup default
Finally we add the default route and flush cache:
ip route add default via 192.168.2.1 dev eth1 table mail
ip route flush cache