This page looks best with JavaScript enabled

Avoid Hairpinning with iptables

 ·  🎃 kr0m

There are many routers whose guts are an embedded Linux, which allows us great flexibility. This time we will explain how to avoid the Hairpinning problem, which consists of not being able to use the router’s WAN IP from within the LAN.

To solve this problem, two solutions can be chosen:

  • Configure a proxy
  • iptables rules

Taking into account that the iptables flow scheme is as follows:

In the PREROUTING chain, we modify the destination address:

iptables -t nat -A PREROUTING -s LAN_RED/24 -d WAN -p PROTO --dport PORT -i LAN_INTERFACE_ROUTER -j DNAT --to-destination LAN_IP_SERVER:PORT

NOTE: With this, we would already have the outbound connection, but if we left it like this, the connection initiated by the client would have the WAN IP as its destination, on the other hand, it would respond with LAN_IP_SERVER, as it has no record of this connection, the client would reset the connection through an RST.

Now we tell it to do SNAT within the same LAN:

iptables -t nat -I POSTROUTING 1 -p PROTO --dport PORT -s LAN_RED/24 -d LAN_IP_SERVER -j SNAT --to LAN_ROUTER_IP

With this, we would already have it ;)

If you liked the article, you can treat me to a RedBull here