How can I take all traffic destined for a certain port, from any IP to any IP, and redirect it to the local machine, preserving the source IP?

2

I want to take all traffic, from any IP address to any IP address, originating on interface enp4s5, destined for port 80, and redirect it to the local machine (the router that iptables is running on).

The service running on port 80 of the local machine (a web server, if that was not obvious from the port) needs to be able to know the original SOURCE IP of the connection.

The use case is for a captive WiFi portal, that replaces all HTTP (I know this will not work for HTTPS) pages with a redirect to my login page running on the router, which they must authenticate with (and will then add an iptables rule or add their address to an ipset that bypasses this redirect).

I am pretty sure a DNAT accomplishes one half of the desired setup, redirecting the packets to the local machine, but where I got stuck was that I need a matching SNAT to send the reply packets back to the machine that originally sent them - but I can't do that because I don't know the source IP to supply in --to-source for the SNAT rule.

AppleDash

Posted 2018-10-03T05:31:51.697

Reputation: 155

Answers

2

What ended up working for me to satisfy all of the above requirements was a REDIRECT rule: iptables -t nat -A PREROUTING -i enp4s5 -p tcp --dport 80 -j REDIRECT --to-port 80

AppleDash

Posted 2018-10-03T05:31:51.697

Reputation: 155