Home Ufw How To Setup Firewall With UFW On Linux

How To Setup Firewall With UFW On Linux

By Karthick
Published: Updated: 9.5K views

This guide explains what is UFW, how to install UFW in Linux, and how to setup firewall with UFW on various Linux operating systems.

Introduction

Security is a serious business. Whether you are running your Linux operating system in data centers or on your desktop, you should secure your operating system against all possible threats.

In fact, servers running in the corporate environment will be well protected. Most corporate companies invests millions of dollars to secure their infrastructure.

There will be a separate network team, firewall team, security team to protect your environment and Linux servers. This will not be the case when you run Linux on your desktops or servers.

You should be aware of how to secure your Linux machines with the right tools. One such tool is UFW.

What is UFW?

UFW, stands for Uncomplicated Firewall, is a firewall program that comes preinstalled by default with Ubuntu-based distributions.

Why UFW instead of iptables? You might wonder.

If you don't know already, Netfilter is a packet filtering system that ships with a Linux kernel and iptables are used to manipulate net filters with a set of commands.

Getting comfortable with iptables may take time and could be a daunting task. To make the firewall management easy, there are many front-ends to iptables are created. UFW is one of them.

UFW is a command line front-end to manage iptables. It provides a framework for managing and manipulating netfilter firewall.

UFW is available by default in all Ubuntu installations after 8.04 LTS version.

There is a also a graphical front-end for UFW named Gufw. We will discuss about it in a separate guide. In this article, our focus will be on using ufw from command line.

Without further ado, let us go ahead and see how to install and setup UFW firewall on Linux.

1. Install UFW in Linux

UFW comes preinstalled with most of Debian-based and Arch-based distributions. To check if UFW is installed or not, run the following command:

$ which ufw
/usr/sbin/ufw
$ ufw version
ufw 0.36
Copyright 2008-2015 Canonical Ltd.

If it is not installed on your distribution, you can install it using your distribution's default package manager.

To install UFW in Alpine Linux, run:

$ sudo apk add ufw

Install UFW in Arch Linux and its variants such as EndeavourOS and Manjaro Linux:

$ sudo pacman -S ufw

Install ufw in Debian, Ubuntu and its derivatives:

$ sudo apt update
$ sudo apt install ufw

Install UFW in Fedora:

$ sudo dnf install ufw

UFW is available in [EPEL] repository for Enterprise Linux operating systems such as RHEL, CentOS, AlmaLinux and Rocky Linux.

Enable [EPEL] repository and install UFW in RHEL, CentOS, AlmaLinux, Rocky Linux like below:

$ sudo dnf install epel-release
$ sudo dnf install ufw

Install UFW in openSUSE:

$ sudo zypper install ufw

1.1. Enable, start, and stop UFW service

In Debian-based systems, UFW daemon will be started and enabled automatically.

Run the following command to check the status of the UFW service:

$ systemctl status ufw

Sample output:

● ufw.service - Uncomplicated firewall
     Loaded: loaded (/usr/lib/systemd/system/ufw.service; enabled; vendor prese>
     Active: active (exited) since Mon 2021-07-05 20:08:01 IST; 44s ago
       Docs: man:ufw(8)
             man:ufw-framework(8)
             file://usr/share/doc/ufw/README
    Process: 21690 ExecStart=/usr/libexec/ufw/ufw-init start (code=exited, stat>
   Main PID: 21690 (code=exited, status=0/SUCCESS)
        CPU: 169ms

Jul 05 20:08:01 ostechnix systemd[1]: Starting Uncomplicated firewall...
Jul 05 20:08:01 ostechnix systemd[1]: Finished Uncomplicated firewall.

The other way way to check if UFW service is enabled and active:

$ systemctl is-enabled ufw
enabled
$ systemctl is-active ufw
active

If UFW service is not started automatically after installation, run the following command to start UFW service:

$ sudo systemctl start ufw

Ufw should also be enabled to automatically started between system reboots.

$ sudo systemctl enable ufw

Or, you can combine both commands into one to enable and start the UFW service in one go like below:

$ sudo systemctl enable --now ufw

To stop UFW service, simply run:

$ sudo systemctl stop ufw

3. Setup firewall with UFW on Linux

3.1. Getting help

If you're new to UFW, the first thing to do after installing it is to refer the help section and man page of UFW to get the basic idea about UFW usage.

$ ufw --help
$ man ufw

If you forgot the syntax or need a reference for a particular feature of ufw, these two commands will be very handy.

3.2. Set default rules

Using UFW, you can create firewall rules (or policies) to allow or deny a specific service. Through these policies, you instruct the UFW what port, service, IP addresses, and interfaces should be allowed or denied.

There are default policies that come with ufw. The default policy will drop all incoming connections and allow all outgoing connections.

IMPORTANT: If you are setting up ufw in a remote server, make sure you've allowed the ssh port or service before enabling ufw firewall.

Default incoming policy will deny all incoming connections. So if you didn't configure the rules to allow SSH, you will be locked out of the remote system and you can not log in to the system. This is not the case when you running ufw on your local system.

The default policies are defined in the /etc/default/ufw file. Here is the contents of the file:

Ufw default policies
Ufw default policies

From here, we can set default policies.

Alternatively, We can use the ufw allow command to set default policies for incoming and outgoing commands:

$ sudo ufw default deny incoming
$ sudo ufw default allow outgoing

3.2.1. Check status of UFW firewall rules

To check if default policies are active, run the following command:

$ sudo ufw status

Sample output:

Status: active

To                         Action      From
--                         ------      ----
SSH                        ALLOW       Anywhere                  
224.0.0.251 mDNS           ALLOW       Anywhere                  
SSH (v6)                   ALLOW       Anywhere (v6)             
ff02::fb mDNS              ALLOW       Anywhere (v6)             

And for more verbose status information use this command:

$ sudo ufw status verbose

Sample output:

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp (SSH)               ALLOW IN    Anywhere                  
224.0.0.251 5353/udp (mDNS) ALLOW IN    Anywhere                  
22/tcp (SSH (v6))          ALLOW IN    Anywhere (v6)             
ff02::fb 5353/udp (mDNS)   ALLOW IN    Anywhere (v6)             

To view the numbered format, run:

$ sudo ufw status numbered
View UFW status
View UFW status

3.2.2. Add rules

Let me take SSH as an example to demonstrate how to add firewall rules with ufw command. Take a look at the below commands:

$ sudo ufw allow ssh
$ sudo ufw allow 22
$ sudo ufw allow 22/tcp
$ sudo ufw allow 2222/tcp

All commands serves the same purpose.

[ 1 ] - In the first command, I am allowing all access to ssh service. UFW knows by default ssh listens to port 22. So when you use allow ssh service, it will also enforce the rule for port 22.
[ 2 ] - In the second command, I am explicitly telling to allow incoming connections for port 22.
[ 3 ] - The third command is the same as the second command. It allows all access to tcp port 22. Both TCP and UDP protocols are supported.
[ 4 ] - In the fourth command, I am allowing a custom ssh port (i.e. 2222) to accept the incoming connections.

You can use these four commands not only for ssh but for any services and ports. For instance, if you want to connect to PostgreSQL running at port 5433, then the rule should be added like below.

$ sudo ufw allow 5433

Similarly, we can use ufw deny command to reject incoming connections:

$ sudo ufw deny 5433

This command will deny traffic on port 5433.

3.2.3. Delete UFW firewall rules

To remove a rule or policy, you can use ufw delete command.

For instance, If you no longer wish to allow HTTP traffic, simply run:

sudo ufw delete allow 80

3.2.4. Enable, disable and reload UFW firewall rules

This is different than enabling and starting the UFW daemon. Starting the ufw systemd unit will not enforce your firewall rules. UFW has dedicated commands to enable, disable and reload firewall rules.

To make the rules effective, you have to run the following command:

$ sudo ufw enable
Firewall is active and enabled on system startup

As I already mentioned, use the following command to view the status of UFW firewall rules:

$ sudo ufw status

Sample output:

Status: active

To                         Action      From
--                         ------      ----
SSH                        ALLOW       Anywhere                  
224.0.0.251 mDNS           ALLOW       Anywhere                  
SSH (v6)                   ALLOW       Anywhere (v6)             
ff02::fb mDNS              ALLOW       Anywhere (v6)           

To disable the Firewall rules, run:

$ sudo ufw disable
Firewall stopped and disabled on system startup

Please note: The above command will only disable the firewall rules. The UFW daemon will be still running and enabled on reboots.

After adding any policy, reload the ufw for the policy to take effect using command:

$ sudo ufw reload

3.2.5. Adding policy for port ranges

You can add a policy for a range of ports instead of creating a policy for a single port:

$ sudo ufw allow 8000:8080/tcp
$ sudo ufw deny 8000:8080/tcp

3.2.6. Adding policy for specific IP addresses, subnets and ports

You can create more fine-grained rules with ufw. Let’s say if you want your server to be connected (ssh’ed) from a specific IP only, you can do so by adding the following rule.

$ sudo ufw allow from 192.168.156.2
$ sudo ufw allow from 192.168.156.2 to any port 2222

The first command allows specified IP to connect based on opened ports. The second command specifies that the user can connect to port 2222 only from 192.168.156.2.

To allow a group of IPs from the same subnet to connect to ssh, you can use the subnet while adding a rule, allowing all IP parts of that subnet to be connected to port 2222.

$ sudo ufw allow from 192.168.156.1/24 to any port 2222

3.2.7. Adding network interface policy

You can also create policies based on network interfaces. The following command will create a policy to accept connections for network interface en01 to port 2222.

$ sudo ufw allow in on en01 to any port 2222

3.2.8. Test rules without applying them using dry-run option

UFW has --dry-run option to test rules without actually applying them. For example, the following is what would be applied if opening the SSH port:

$  sudo ufw --dry-run allow ssh
Dry run UFW commands
Dry run UFW commands

As you can see in the above output, the ufw command only outputs the resulting rules, but not apply them when we add --dry-run option. This comes in handy when you want to test any firewall policies.

3.2.9. Add comment to each rule

You might have added several rules. After a particular number of rules (Say 50), you have no way of remembering what the rule is about.

In that case, you can add a comment to each rule like below:

$ sudo ufw allow 22 comment 'open port 22 for ssh'

The above command will allow all traffic to port 22 and adds a comment for the rule. This way you can easily find the purpose of a specific rule.

4. Which rule gets priority?

Priority is important when you are creating multiple rules for the same service/ports. Policy gets their priority in the order they created. Run the following command which will give you policy along with its priority.

$ sudo ufw status numbered

Sample output:

Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22                         ALLOW IN    Anywhere                  
[ 2] 2222                       ALLOW IN    Anywhere                  
[ 3] 2222                       ALLOW IN    192.168.156.2             
[ 4] 2222                       DENY IN     192.168.157.0/24          
[ 5] 22 (v6)                    ALLOW IN    Anywhere (v6)             
[ 6] 2222 (v6)                  ALLOW IN    Anywhere (v6)   

Take a look at [ 4 ] in the above output. Any connection to port 2222 from the subnet 192.168.157.0/24 should be dropped.

But when I try to connect from any of the machines from the same subnet, the connection will be allowed because the high priority has been given to [ 2 ].

To override this behavior you have to create rules with priority. You can delete the existing rule and add a new rule with priority and reload the service.

$ sudo ufw delete 4
Deleting:
deny from 192.168.157.0/24 to any port 2222
Proceed with operation (y|n)? y
Rule deleted
$ sudo ufw insert 2 deny from 192.168.157.0/24 to any port 2222
Rule inserted
$ sudo ufw reload
Firewall reloaded
$ sudo ufw status numbered
Status: active
To Action From
-- ------ ----
[ 1] 22 ALLOW IN Anywhere
[ 2] 2222 DENY IN 192.168.157.0/24
[ 3] 2222 ALLOW IN Anywhere
[ 4] 2222 ALLOW IN 192.168.156.2
[ 5] 22 (v6) ALLOW IN Anywhere (v6)
[ 6] 2222 (v6) ALLOW IN Anywhere (v6)

Take a look at above output. Priority is reassigned to [ 2 ]. Now if I try to connect to port 2222
from 192.168.157.0/24, my connection will be denied.

5. UFW logging

Logs are the best bet when something has gone wrong.

To disable UFW logging, run the following command:

$ sudo ufw logging off
Logging disabled

To enable UFW logging, run:

$ sudo ufw logging on
Logging enabled

There is four-levels of logging, namely low, medium, high, and full. Depending upon the level you choose the logs will be generated under /var/log/ufw.log file. By default, the log level will be low.

You can use the below command to set to the suitable level you want:

$ sudo ufw logging [ high | medium | Full | Low ]

To check the status of logging and log level, run the ufw status command and look for logging entry.

$ sudo ufw status verbose
Status: active
Logging: on (high)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

6. Application profiles

When you install any packages using using your package manager (E.g. apt or pacman), an application profile that defines rules for that package will be created in ufw.

For example, if you are installing an OpenSSH server using apt, then profile will be created for port 22. All application profiles are stored under /etc/ufw/applications.d directory.

To get the list of application profiles, run the following command:

$ sudo ufw app list

Sample output:

Available applications:
CUPS
OpenSSH

This is a test machine. I have installed only OpenSSH. So you see only two profiles.

To get detailed information about that profile and what policy it enforces, run the following command:

$ sudo ufw app info 'OpenSSH'

Sample output:

Profile: OpenSSH
Title: Secure shell server, an rshd replacement
Description: OpenSSH is a free implementation of the Secure Shell protocol.
Port:
22/tcp

7. Reset UFW firewall to default policy

If you wish to clean all the rules you created and reset to default, you can do that by running the ufw reset command.

$ sudo ufw reset

Sample output:

Resetting all rules to installed defaults. Proceed with operation (y|n)? y
Backing up 'user.rules' to '/etc/ufw/user.rules.20210705_131655'
Backing up 'before.rules' to '/etc/ufw/before.rules.20210705_131655'
Backing up 'after.rules' to '/etc/ufw/after.rules.20210705_131655'
Backing up 'user6.rules' to '/etc/ufw/user6.rules.20210705_131655'
Backing up 'before6.rules' to '/etc/ufw/before6.rules.20210705_131655'
Backing up 'after6.rules' to '/etc/ufw/after6.rules.20210705_131655'

When you run this command your current rules will be backed up before resetting to the default profile.

Ufw also has many graphical front-ends. One of them is Gufw.

8. Gufw, a graphical front-end to UFW

Some of you may not be comfortable with command line mode. Fortunately, there is a graphical front-end for UFW available.

Gufw is a graphical front-end application to manage the Uncomplicated Firewall (UFW) in Linux. Gufw is mainly developed to install and configure firewall for Linux desktops.

Refer the following guide to learn how to install and configure Gufw on Linux:

Conclusion

In this guide, we have discussed what is UFW, how to install and setup UFW firewall on Linux with example commands.

Now it is your turn to test ufw on your machine. I suggest test ufw in any Virtual machine before implementing it on your desktop or server.

Resource:

You May Also Like

3 comments

Jasper Brannigan July 7, 2021 - 10:05 am

Do people still use “ufw”? All the cool kids switched to the far superior “firewalld” years ago.

Reply
Paride July 20, 2023 - 4:09 pm

Do people still use “firewalld”? All the cool kids is remained to the far ssuperior “iptables/ebtables” from the begin.

Reply
sk July 9, 2021 - 11:00 pm

I can’t speak for others. But I do use UFW in my Ubuntu server.

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More