Port forwarding in iptables on NAT server

Once I needed to forward a port to a VPN server that had a gray IP address and was behind NAT.

Let’s say the server uses a rule for NAT:

iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o ens3f1 -j SNAT --to-source 172.16.5.2-172.16.5.100 --persistent

Now we will forward a port to one of the NAT IP addresses to the local device with OVPN (10.0.0.2):

iptables -t nat -A PREROUTING -d 172.16.5.5/32 -i ens3f1 -p tcp -m tcp --dport 1194 -j DNAT --to-destination 10.0.0.2:1194

Another example for L2TP:

iptables -t nat -A PREROUTING -d 172.16.5.5/32 -i ens3f1 -p udp --dport 500 -j DNAT --to-destination 10.0.0.2:500
iptables -t nat -A PREROUTING -d 172.16.5.5/32 -i ens3f1 -p udp --dport 1701 -j DNAT --to-destination 10.0.0.2:1701
iptables -t nat -A PREROUTING -d 172.16.5.5/32 -i ens3f1 -p udp --dport 4500 -j DNAT --to-destination 10.0.0.2:4500

The local device was MikroTik, so ports that are forwarded through NAT should be open on it, and the firmware should be updated to the latest version to avoid vulnerabilities.

See also my articles:
Configuring Remote Access in Mikrotik
How to configure IPTables

Leave a comment

Leave a Reply