Wednesday, March 10, 2010

UFW - simply great firewall for Linux

UFW is a very simple and powerful firewall which allows us to configure our policies in minutes!
Moreover, it allows us to configure forwarding traffic between interfaces and even NAT!
We can check UFW status by typing sudo ufw status or even just sudo ufw to see the list of available options.
By default, all outbound traffic is permitted. UFW is stateful firewall, so it tracks connections via maintaining connection table. Returning traffic permitted to pass through the firewall only if corresponding connection is in the table. Or simply, traffic allowed to return only if connection were originated from the inside network.
To open ports in the firewall, so inbound connections can be allowed, we have to add the rules. It's simple:
sudo ufw allow port number[/tcp|udp]
or 
sudo ufw deny port number[/tcp|udp] to block open ports.
To disable logging we can execute
sudo ufw logging off

Here are steps to configure routing and NAT.

First, packet forwarding need to be enabled.
We need to modify 2 configuration files:
1.  /etc/default/ufw change DEFAULT_FORWARD_POLICY to "ACCEPT".
2.  /etc/ufw/sysctl.conf uncomment /net/ipv4/ip_forward=1
After previous steps our Linux machine will begin to forward packets between it's interfaces!
Only NAT configuration left and it pretty straightforward.
We need to add rules to the /etc/ufw/before.rules file. We need to add the following string right to the top of the file after the header comments:
# nat Table rules
*nat
:POSTROUTING ACCEPT [0:0]

# Forward traffic from eth1 through eth0.
-A POSTROUTING -s 192.168.0.0/24 -o eth0 -j MASQUERADE

# don't delete the 'COMMIT' line or these nat table rules won't be processed
COMMIT
To enable Port Forwarding, also add the following string before COMMIT keyword. If ports to be forwarded are different on NAT device and destination then simply add :[portNumber]
-A PREROUTING -i eth1 -p tcp --dport 3389 -j DNAT --to 192.168.139.101:[portNumber]
Of course, ip networks and interface names should be replaced with appropriate. eth0 in this example is our outside interface on which translation will be performed. 192.168.0.0/24 subnet is our internal subnet which requires translation.
Only restarting the firewall left.
sudo ufw disable && sudo ufw enable

2 comments:

  1. Thanks for the info! I just started getting my hands dirty w/ UFW and was looking for some concise notes on Port Forwarding.

    in your above port forwarding example should the specified interface be outside (eth0 not eth1)?

    ReplyDelete
    Replies
    1. Thanks for your comment!
      Yep, you are right. The interface should be "outside.

      Delete