Linux for Network Engineers: How to Set Up Firewall Rules with ufw

By January 30, 2019Linux

The Linux kernel provides a type of packet filtering called netfilter. The most common and native interface to netfilter is the iptables utility. iptables is powerful and is included by default in most Linux distributions. However, it’s moderately difficult to learn and to fully master it; it has a very steep learning curve.

For this reason there have been many efforts to simplify the manipulation of firewalls on Linux. One of them is a package called “uncomplicated firewalls” (ufw). The name of the package makes it clear that this is a firewall setup utility, and it’s easy to use.

Let’s see if we should believe it.

Installation

To install ufw type:

Once you do that, you can see the status of the firewall and its rules as follows:

Allow ssh

ufw attempts to avoid surprises, and by default, it’s not enabled because its default rules are to block all incoming connections and allow all outgoing. One of the most common ports that need to be open is port 22, for ssh’ing.

Before enabling the firewalls, we have to make sure that port 22’s incoming connections are allowed, otherwise we may lose ssh access to the Linux host.

Here is how to do that:

As you can see, tcp connections on port 22 are allowed from anywhere on both IPv4 and IPv6. Now we are ready to enable the firewall rules with:

ufw warns that we are currently using port 22 for ssh, and if for some reason this is blocked by ufw, our connection will drop. If you did everything correctly you shouldn’t worry about it and answer “y.”

Uncomplicated firewalls have a simple and intuitive syntax. Let’s look at some more examples:

Enable Logging

Logging is very useful in order to be able to go back in time and examine post mortem problems or even to keep an eye on our system in real time. To enable logging type:

And from now on, all activity will be logged in “/var/log/ufw.log.” Here is an example:

Specify host and subnet

You can allow or block traffic based on the IP or the subnet of the host that is sending the traffic:

Delete Rule

Deleting rules is as easy and intuitive as adding rules. Here is how to remove the last rule that we added:

Deleting rules by repeating the rules is a bit cumbersome, and there is an easier way to do that. First we need to display the rules with their corresponding number and delete the rule by using this unique number:

ufw is my go to utility when I want to manipulate firewall rules on a Linux host. It makes my life much better when it comes to adding, removing, or modifying firewall rules. It should be your go-to tool for setting up firewalls too.