Apr 17, 2012
tom

iptables preroute localhost

Question

I would like to forward all incoming traffic from a certain port to another one using iptables. The problem is that prerouting doesn’t work for traffic from localhost. This topic suggests a solution:

iptables -t nat -I PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8080
iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 443 -j REDIRECT --to-ports 8080

This solution does work for most cases. However, when I connect to http://myserver:443 where myserver resolves to an IP address that is hosted on the local machine, but is not 127.0.0.1 it seems to bypass both rules.

Is there a way to also catch forwards requests from the local machine that are done to the eth0 ip address?

Asked by Jeroen

Answer

Instead of doing -d 127.0.0.1 on the OUTPUT rule, you could do -o lo. This will match any traffic going through the loopback interface no matter what the destination is.

As a side note, even when you send to ‘http://myserver:443′, the traffic is still local, so it still goes through the loopback interface, even though it doesnt resolve to ’127.0.0.1′.

Answered by Patrick

Related posts:

  1. Restricting output to only allow localhost using iptables
  2. iptables: redirect port to server that’s bound to a specific IP
  3. Why did my new iptables rules screw up outbound traffic?
  4. iptables is blocking ping and dns
  5. iptables REDIRECT scope

Leave a comment