2

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?

2
+50

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

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
  • I need it to have a different default route. This does not answer the question. – Duncan X 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 – Duncan X 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. – Duncan X 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.