Set up a firewall with UFW

🗓️
•
🔄
•
⏳ 2 min

What it is

The Uncomplicated Firewall is just an easy way to interact with iptables, the default way for Linux based systems to control connections to and from the web.

You’ll usually find it in web servers, although it can —and arguably should— be installed on your main machine.

Basic Setup

Let’s take a look at a basic setup for a web server:

Status: active
Default: deny (incoming), allow (outgoing)
To Action From
-- ------ ----
22 LIMIT IN Anywhere
80 ALLOW IN Anywhere
443 ALLOW IN Anywhere

The second line tells us the default policies for all non specified ports. In this case it denies all incoming traffic while allowing all outgoing.
Specific port policies are listed below (SSH, HTTP, HTTPS, etc.).

Config

If we run ufw status right after installing it, we’ll get an underwhelming Status: inactive as a response.

Makes sense, now let’s configure a basic server-ready setup like the one above:

sh
ufw default deny incoming # Block everything from the web
ufw limit in 22 # Limit incoming SSH connections
ufw allow in 80 # Allow incoming HTTP connections
ufw allow in 443 # Allow incoming HTTPS connections
ufw enable

Important: Make sure to not block ssh communication! That might lock yourself out of your VPS/Server completely!


Now if you run ufw status verbose you should see pretty much the same information as we saw in the example above.

Deleting rules

For example, if you want to delete the previous HTTPS rule:

sh
ufw delete allow in 443
ufw reload

Fine-Tuning

Of course, you can easily change the default behavior as well as fine tune the policy on a per port basis.
You can deny, reject, limit or allow either in or out going traffic for which ever port you might need, as well as use the same parameters to define default behaviors.


Other posts you might like