Linux as router: I have 3 Internet providers, each with its own modem.
Provider1, which is gateway address 192.168.1.1
Connected to linux router eth1/192.168.1.2
Provider2, gateway address 192.168.2.1
Connected to linux router eth2/192.168.2.2
Provider3, gateway address 192.168.3.1
Connected to linux router eth3/192.168.3.2
________
+------------+ /
| | |
+----------------------+ Provider 1 +--------|
__ |192.168.1.2 |192.168.1.1 | /
___/ \_ +------+-------+ +------------+ |
_/ \__ | eth1 | +------------+ /
/ \ eth0| |192.168.2.2 | | |
|Client network -----+ ROUTER eth2|--------------+ Provider 2 +------| Internet
\10.0.0.0/24 __/ | | |192.168.2.1 | |
\__ __/ | eth3 | +------------+ \
\___/ +------+-------+ +------------+ |
|192.168.3.2 | | \
+----------------------+ Provider 3 +-------|
|192.168.3.1 | |
+------------+ \________
I would like to route the clients in network 10.0.0.0/24 by source IP to different gateways.
The interface to the client network is eth0/10.0.0.1, which is the default gateway for all clients.
For example:
10.0.0.11 should be routed to Provider1 @ eth1
10.0.0.12 should be routed to Provider2 @ eth2
...and so on...
I think I need to use ip route
and iptables
for SNAT, but I have not figured out exactly how.
Here is the script I have so far.
ipv4 forwarding is enabled.
#!/bin/bash
# flush tables
ip route flush table connection1
ip route flush table connection2
ip route flush table connection3
# add the default gateways for each table
ip route add table connection1 default via 192.168.1.1
ip route add table connection2 default via 192.168.2.1
ip route add table connection3 default via 192.168.3.1
# add some IP addresses for marking
iptables -t mangle -A PREROUTING -s 10.0.0.11 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -s 10.0.0.12 -j MARK --set-mark 2
iptables -t mangle -A PREROUTING -s 10.0.0.13 -j MARK --set-mark 3
# add the source nat rules for each outgoing interface
iptables -t nat -A POSTROUTING -o eth1 -j SNAT --to-source 192.168.1.2
iptables -t nat -A POSTROUTING -o eth2 -j SNAT --to-source 192.168.2.2
iptables -t nat -A POSTROUTING -o eth3 -j SNAT --to-source 192.168.3.2
# link routing tables to connections (?)
ip rule add fwmark 1 table connection1
ip rule add fwmark 2 table connection2
ip rule add fwmark 3 table connection3
#default route for anything not configured above should be eth2