Thursday, 13 August 2015

Ubiquiti AirOS Hairpin NAT


When setting up a port forward (Destination NAT) on a Ubiquiti AirOs device, you will find that users inside your network will not be able to use the WAN IP to access the internal device. This is because you need to add what is known as a "Hairpin NAT". Read below for instructions on how to do that, and why it is necessary.

Picture the network below:

In order for a user from the internet (wan) side of the router to be able to access the webserver, you would add the following port forward to your router:

This would immediately work for users outside the network, but if you wanted to access the webserver from the workstation inside the lan by using the ip 12.34.56.78, it would fail. Why?

Let us picture the process as follows:

This explains why the workstation never receives the response, and why a connection isn't opened.

To fix this, we need to make sure that the server responds via the router. We do this by telling the router to not only change the Destination IP, but also the Source IP in step one above.
Unfortunately as of version 5.6 of AirOs, Ubiquiti still hasn't implemented a hairpin function in the web interface, but you can do it from the command line.

What you need to do is open up a telnet or ssh session to the router, and run the following commands:
echo iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -d 12.34.56.78 -j MASQUERADE >> /etc/persistent/rc.poststart

This will add a rule to your router's firewall that says when anyone tries to connect to 12.34.56.78 from inside the 10.0.0.0/24 subnet, the SOURCE IP will be replaced with the Source IP of the router.

Run the following command to save the change:
cfgmtd -w -p /etc/
And reboot the router.

When you open the web interface for the router you will now see that it shows that you are running custom scripts, do not be alarmed, this is normal.


You should now be able to connect to the device using the public ip of your router.

0 comments:

Post a comment