I'm using iptables to forward and SRCNAT (specifically MASQUERADE) packets from a specific source. I want to route outgoing packets (initiated by this computer) differently from those being forwarded (different default route). How do I do this?
Asked
Active
Viewed 1,202 times
2 Answers
2
One way is to mark the traffic in iptables and match an outbound route with policy routing:
let's say you have gateway1 and gateway2 on the same LAN...
ip route flush table 3
ip route add table 3 <lan net>
ip route add default via <gateway1>
ip route flush table 4
ip route add table 4 <lan net>
ip route add default via <gateway2>
Tag the traffic in iptables:
iptables -t mangle -A PREROUTING -s 10.0.0.0/24 -j MARK --set-mark 3
iptables -t mangle -A PREROUTING -s 10.1.0.0/24 -j MARK --set-mark 4
You can match on anything you like, source address, destination address or port, etc...
Since you're explicitly rewriting the source IP in iptables rather than relying on a dynamic gateway IP you probably want to use SNAT instead of MASQUERADE. See Differences between SNAT and MASQUERADE
quadruplebucky
- 466
- 3
- 5
1
Edit /etc/sysctl.conf and add/edit "net.ipv4.ip_forward" option.
net.ipv4.ip_forward=1
For inmediate changes run:
sysctl net.ipv4.ip_forward=1
iptables rules:
iptables -A FORWARD -i input_dev -j ACCEPT
iptables -t nat -A POSTROUTING -o output_dev --src src_ip -j MASQUERADE
Pablo
- 11
- 1
-
I need it to have a different default route. This does not answer the question. – Dessa Simpson Jul 19 '17 at 15:44
-
Only create a virtual interface over output_dev (output_dev:0 for example) change the default route for this virtual interface and use it as output device on iptables rules. – Pablo Jul 19 '17 at 21:39
-
That doesn't make sense. Default routes are per routing table, not per interface – Dessa Simpson Jul 19 '17 at 21:42
-
If you can provide me a working example I'll accept your answer and give you the bounty. – Dessa Simpson Jul 19 '17 at 21:52
-
Bounty is insignifficant. I want to help you. :) I can not obtain any result, but try changing the mac destination of forwarded paquests that it's ip destination is not a local ip. (use arptables for it). – Pablo Jul 19 '17 at 22:14
-
What do you mean by different default route? there can be only one default. As @Pablo suggested, you should be able to create virtual interface and use "route add -net
-dev – rajaganesh87 Jul 20 '17 at 16:26 -
There can be multiple within different routing tables. – Dessa Simpson Jul 25 '17 at 12:29