IP Forwarding and Masquerading in Linux Using UFW

In this example we have 2 private subnets and where only 192.168.1.xxx addresses can directly access the router at We want to access the internet from both subnets.

We need a machine connected to both networks and allow IP forwarding from to Although probably better with 2 NICs it can be done usings network aliases using only 1 network interface.

Presuming you have a configured NIC with an address for eth0 on the range and on eth0:1 an address from we can start configuring the machine. This machine will act as the gateway for the 172.16.1.xxx range.

First check if packet forwarding is activated.
Step 1:
Check /etc/default/ufw and make sure DEFAULT_FORWARD_POLICY is set to ACCEPT.


Step 2:
Type the following to test for IP forwarding

cat /proc/sys/net/ipv4/ip_forward

If this returns 0 we need to turn it on. Edit /etc/ufw/sysctl.conf and uncomment


Now to configure IP masquerading, network address translation
Edit the file /etc/ufw/before.rules and add the following code to the top.


#Forward traffic from the alias range 172.16.1.xxx through eth0


To activate new firewall settings type

ufw disable
ufw enable

If ufw was not already enabled you may need to alter some rules as it may now be blocking some routes and ports. In this example we may need to add rules such as.

ufw allow from
ufw allow to
ufw allow from
ufw allow to

Tested with ubuntu server 11.10