1

My setup is as follows:

I have a Linux server with two interfaces, eth0 and eth1. eth1 has an Internet connection through my normal LAN. eth0 is serving DHCP and the interface itself has an IP address of 10.0.0.1.

I want to accomplish the following:

I want to have packets on port 80 originating from machines connected to eth0 to be redirected to port 80 on the routing machine itself, and response packets to of course be redirected back. That in itself is simple enough, but I have one more requirement. I would like clients on eth0 with certain IP addresses to be able to be exempt from this, and have port 80 packets routed as they normally would be. How can I do this? So far, I've done the following to redirect all port 80 packets from eth0 to the local machine. It is working, but I do not know how to do my second requirement.

iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 10.0.0.1:80 -i eth0

iptables -t nat -A POSTROUTING -p tcp -d 127.0.0.1 --dport 80 -j SNAT --to-source 10.0.0.1

0

You need to just exit the PREROUTING table before it gets to the DNAT line:

iptables -t nat -I PREROUTING -p tcp -s <exempt ip> -j RETURN

This should insert (-I) a new rule to exit (-j RETURN) the routing table for any packet from the exempt IP (-s <exempt ip>) as the first rule, so it is hit before it gets to the DNAT rule.

(You might also need to do something similar on POSTROUTING, not sure.)


The other option is to create an IP set (man ipset) for the IPs that you want to exempt, and then add a inverted match to your DNAT and SNAT rules:

ipset create exempt hash:ip
ipset add exempt <exempt ip 1>
ipset add exempt <exempt ip 2>
ipset add exempt <exempt ip 3>
iptables -t nat -A PREROUTING -p tcp --dport 80 -m set ! --match-set exempt src -j DNAT --to-destination 10.0.0.1:80 -i eth0

This is easier to manage because you can easily add or remove exempted IPs from the ipset without modifying iptables.

2
  • This seems to have worked, but one more thing... How can I remove this rule? – AppleDash May 29 '15 at 20:49
  • You can remove the rule with iptables -t nat -D POSTROUTING 1 (where 1 is the index into the POSTROUTING chain of the rule you want to remove. Use iptables -t nat -L POSTROUTING to list all the rules in the POSTROUTING chain. – Darth Android May 29 '15 at 20:55

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.