Ubuntu – How to use iptables to route packet with a specific destination IP through a specific interface

iptablesrouterUbuntu

I have a linux box setup as a router using this tutorial: https://help.ubuntu.com/community/Router

On that machine there are 2 network interfaces and one VPN: eth0 is the main internet interface, eno1 is the intranet and tun0 is the VPN interface.

As per the tutorial i'm using the script below to route everything that come from eno1 through the vpn:

iptables-restore <<-EOF
*nat
-A POSTROUTING -o tun0 -j MASQUERADE
COMMIT

*filter
:INPUT ACCEPT [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A FORWARD -i tun0 -o eno1 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -i eno1 -o tun0 -j ACCEPT
-A FORWARD -j LOG
COMMIT
EOF

That works great. But now i want to route all packets coming from eno1 and with destination IP of 203.205.147.173 through eth0.

What kind of iptables rules should I add to my script ?

Edit

i have change the script as follow to mark all packet to 203.205.147.173:

iptables-restore <<-EOF
*nat
-A POSTROUTING -o tun0 -j MASQUERADE
COMMIT

*filter
:INPUT ACCEPT [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A FORWARD -i tun0 -o eno1 -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
-A FORWARD -i eno1 -o tun0 -j ACCEPT
-A FORWARD -j LOG
COMMIT

*mangle
-A PREROUTING -i "$INTIF" -d 203.205.0.0/16 -j MARK --set-mark 0x15
COMMIT
EOF

Then i create the table X:

sudo nano /etc/iproute2/rt_tables, then add 1 tableX at the end of the file.

Then add rule and route:

sudo ip rule add fwmark 0x15 lookup tableX
sudo ip route add default via 192.168.5.1 dev eth0 table tableX
sudo ip route add 203.205.0.0/16 via 192.168.5.1 dev eth0 table tableX

but traceroute 203.205.147.173 timeout:

traceroute to 203.205.147.173 (203.205.147.173), 64 hops max, 52 byte packets
 (192.168.8.1)  2.384 ms  1.060 ms  1.027 ms
 2  * * *
 3  * * *
 4  * * *
 5  * * *
 6  * * *
 7  * * *
 8  * * *

I think i'm not adding the right route to tableX. Any suggestions about how to initialize tableX ?

Note that eth0 router ip is 192.168.5.1 and eno1 router ip is 192.168.8.1

Best Answer

The iptables doesn't route anything itself, but can affect to routing decision with firewall marks. You add another routing tables with the ip tool (something like ip route add <route> ... table X, then add the rules to route the packets by firewall mark (ip rule add fwmark 0x1 lookup X), and mark the packets with the iptables rules (iptables -t mangle -A PREROUTING ... -j MARK --set-mark 0x1). After those step the marked packets will be routed through routing table X. More information you can get from LARTC (linux advanced routing and traffic control).

Related Topic