2016년 5월 28일 토요일

Enabling Port Forwarding with UFW on Ubuntu

Several months ago, I described how to enable port forwarding with the dynamic firewall firewalld in a post titled Internet connection sharing through a computer with two NIC's. Today I will describe how to achieve the same thing in Ubuntu 15.10 using uncomplicated firewall, ufw, a front-end to iptables.

Keep in mind that the method I am describing requires two NIC's on the machine that will be forwarding packets from the internal to the external network.

1. Make sure ip forwarding is enabled in the Kernel

On most linux distros this has historically been set in /etc/sysctl.conf but in recent years with the rise of systemd, the actual setting net.ipv4.ip_forward=1 might be found in a rules file under /usr/lib/sysctl.d/ or /etc/sysctl.d/ ; in the case of Ubuntu running ufw, however, the ip forwarding setting shown above should be made in /etc/ufw/sysctl.conf

2. Edit /etc/ufw/before.rules

Make sure that NAT is enabled with the following setting:

# NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]

And then enable the forwarding of packets from your internal network subnet (mine is 192.168.95.0/24) to the external network interface (enp3s5f0 in my case):

-A POSTROUTING -s 192.168.95.0/24 -o enp3s5f0 -j MASQUERADE

-A is for append rule
-s specifies the source address
-o indicates the output (egress) interface

The internal network at work is on the 192.168.95.X subnet (iface enp5s0), while the external subnet is on 192.168.30.X (iface enp3s5f0).

To apply the changes, sudo ufw disable && sudo ufw enable


Notes

For some reason after applying the changes, pinging the Ubuntu 15.10 server worked, but ssh was blocked by ufw. I thus had to manually add ssh to the ufw firewall with the following command:

sudo ufw enable ssh

It is also possible to enable port forwarding using native iptables commands:

iptables -A FORWARD -i enp5s0 -j ACCEPT
iptables -A FORWARD -o enp3s5f0 -j ACCEPT
iptables -t nat -A POSTROUTING -o enp3s5f0 -j MASQUERADE

But I didn't actually try this method, so it may or may not work on your machine.

References:

https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/4/html/Security_Guide/s1-firewall-ipt-fwd.html

https://gist.github.com/kimus/9315140