Iptables: multiple exclusions on port forwarding

iptables

I have an existing iptables setup that does port forwarding. In this port forwarding scenario there are some instances where I do not want it to port forward. So, for instance I have this defined:

iptables -A PREROUTING -t nat -i eth0 '!' -s 10.200.0.0/16 -p tcp --dport 80 -j DNAT --to 10.200.30.11

This will prevent 10.200/16 from accessing this rule. As it turns out, I need to add multiple exclusions. However, there does not seem to be a way to do this:

iptables -A PREROUTING -t nat -i eth0 '!' -s 10.200.0.0/16,192.168.0.0/16 -p tcp --dport 8080 -j DNAT --to 10.200.30.11:80
iptables v1.4.8: ! not allowed with multiple source or destination IP addresses

I'm going to assume I have to approach this differently, but I do not know how.
Any suggestions?

Best Answer

You could use one of the following variants:

First one is ipset with set type "hash:net".

Second one is a iptables rule chain with -j RETURN for each network to skip check, and the desired default action as the last chain rule.

Third one is to mark packet with some bit flag using -j MARK and corresponding flag playing (with --set-mark, --set-xmark, etc.), and then to do the desired action if mark check is satisfied (-m mark and --mark). This is the most generic variant, because mark could be set in one table and checked in another one. OTOH the mark bitmask is limited to 32 bits, that could be not enough for complex rules.

Related Question