IPTables Source NAT (SNAT) to /etc/ufw/before.rules

iptablesnat;Ubuntuufw

I have a need to source NAT (SNAT) traffic between two interfaces in an Ubuntu 18.04 server. I've been trying to use the '/etc/ufw/before.rules' file to implement my various NAT needs and so far so good… until now.

The following iptables command seems to do exactly what I need it to:

iptables -j SNAT -t nat -I POSTROUTING 1 -o eth0 -d 192.168.1.0/24 -s 172.18.0.0/16 --to-source 10.136.0.2

Can this rule be easily translated into a configuration in the '/etc/ufw/before.rules' file? The man pages for UFW NAT configs seem to be a little lacking when compared to the more common filtering rules.

Background:
I'm source NATing some docker/container traffic to send over an IPSec policy tunnel using StrongSwan. Without the previously mentioned iptables rule I can get traffic to route INTO the container from the VPN but traffic sourced FROM the container falls flat.

eth0 is my "public" interface IP 1.2.3.4 and eth1 is my "private" interface IP 10.136.0.2

Here is the *nat config that I already have in the '/etc/ufw/before.rules' file to get the traffic flowing (minus the docker sourced traffic):

*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 192.168.1.0/24  -d 10.136.0.0/16 -j MASQUERADE
-A POSTROUTING -s 192.168.1.0/24  -d 172.18.0.0/16 -j MASQUERADE
COMMIT
#

Best Answer

If you have already added this iptables rule manually, then you can find its correct format and position for adding to before.rules by running:

# sudo iptables -t nat -S
...
-A POSTROUTING -s 172.18.0.0/16 -d 192.168.1.0/24 -o eth0 -j SNAT --to-source 10.136.0.2
...
Related Topic