How to Set Up a Firewall with UFW on Ubuntu 22.04

Written by: Linuxopsys   |   Last updated: May 28, 2022

UFW (Uncomplicated Firewall) is a command-line interface firewall designed for Ubuntu. It also works in Debian-based distributions.

It is built with the intention to ease the complexity of Iptables. UFW provides user-friendly ways to create a host-based firewall. GUFW is a graphical version for managing UFW.

UFW comes preinstalled on Ubuntu operating systems but is not enabled by default. You need to issue ufw command to enable and configure the firewall.

In this guide, we learn how to set up a Firewall with UFW on Ubuntu 22.04 LTS.

Prerequisites

  • A system running Ubuntu 22.04.
  • A root user or normal account with sudo privileges.
  • Previous knowledge about Firewall.
  • Access to the terminal.

How to Install UFW

UFW comes preinstalled in Ubuntu. In case not found you can install ufw package using apt.

sudo apt update
sudo apt install ufw

Step 1: Set up ufw default policy

Firewalls normally have a default policy. You can find the default policy in ufw configuration file located at /etc/default/ufw. The default policy will be getting active once the firewall is enabled.

Once UWF is enabled, by default it deny all incoming traffics and allows all outgoing traffics. It means that anyone trying to access your server will not be able to connect unless you open specific services.

You can find the default policy of ufw in /etc/default/ufw file.

$ cat /etc/default/ufw
Output
# /etc/default/ufw
#

# Set to yes to apply rules to support IPv6 (no means only IPv6 on loopback
# accepted). You will need to 'disable' and then 'enable' the firewall for
# the changes to take affect.
IPV6=yes

# Set the default input policy to ACCEPT, DROP, or REJECT. Please note that if
# you change this you will most likely want to adjust your rules.
DEFAULT_INPUT_POLICY="DROP"

# Set the default output policy to ACCEPT, DROP, or REJECT. Please note that if
# you change this you will most likely want to adjust your rules.
DEFAULT_OUTPUT_POLICY="ACCEPT"

# Set the default forward policy to ACCEPT, DROP or REJECT.  Please note that
# if you change this you will most likely want to adjust your rules
DEFAULT_FORWARD_POLICY="DROP"
....
....

Syntax to change ufw default policy:

ufw default allow|deny|reject DIRECTION 
  • allow|deny|reject is the permission that you will set
  • DIRECTION is one of the values: incoming, outgoing, or routed

In case someone changed the defaults, you need to change back to ufw default:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Note: All UFW rules added from the command line are stored in /etc/ufw/user.rules file.

Step 2: Check the default applications profiles

When you installed some standard applications, UFW recognized the services related to those applications. It's an application profile that is a text file in INI format describing the service and containing firewall rules for the service. This can be helpful to allow the service on UFW if you don't remember the port number. The application profiles are created in the /etc/ufw/applications.d directory during the installation of the package.

To list all application profiles that are recognized by default:

sudo ufw app list
Available applications:
  OpenSSH

OpenSSH is the application that allows you to use the SSH service is listed on the applications recognized on UFW by default.

If you install some tools like Nginx, you will see more applications.

Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

Step 3: Allow SSH

By default, SSH connections are not allowed on UFW. It means that if you enable UFW, there will be no rule allowing your SSH connection and it will be disrupted. So, the first thing to do after accessing your remote cloud server is to allow SSH connections on UFW.

sudo ufw allow 22
or
sudo ufw allow ssh
Output
Rule added
Rule added (v6)

When IPv6 is enabled, UFW will automatically add a rule for it. It's the line with the (v6) mention.

Step 4: Enable UFW

UFW is not enabled by default. So, you should activate it first. Remember that, when you activate it, if there is no SSH connection rule, you will lose your remote connection as by default it will deny all incoming connections not that are not explicitly specified.

To start UFW firewall, we need to enable ufw:

sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

With enabling ufw we have turned on the Firewall on Ubuntu.

You can see a warning that ssh connection may be disrupted. This will be true if there is no SSH rule on UFW.

Before starting the firewall you use the following command to display all added rules:

sudo ufw show added
Output
Added user rules (see 'ufw status' for running firewall):
ufw allow 22

Step 5: Check UFW status

You can any time check the ufw firewall status to check the firewall on or off. Additionally, it shows how the firewall rules are configured.

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

To                         Action      From
--                         ------      ----
22                         ALLOW IN    Anywhere
22 (v6)                    ALLOW IN    Anywhere (v6)   

The first line of the output shows the ufw status either active or inactive. The following lines display the logging status and list of rules that are set.

UFW status only shows the rules added from the command line and not the rules added manually in the /etc/ufw rules files.

Step 6: Allow incoming traffic

It's time to create rules in order to specify the incoming traffics that you are going to allow too. You should make sure to allow only the services that you need and trust.

Let's check how to write rules to allow connections based on port, port ranges, IP address, IP range, and more.

Allow a single port

If you have a single service to add, you can use the UFW to allow a single port.

For example to allow HTTP traffic on port 80:

sudo ufw allow 80

Verify by checking the UFW status:

sudo ufw status
Output
Status: active

To                         Action      From
--                         ------      ----         
22                         ALLOW       Anywhere                  
80                         ALLOW       Anywhere                           
22 (v6)                    ALLOW       Anywhere (v6)             
80 (v6)                    ALLOW       Anywhere (v6)

Allow port range

UFW allows setting rules to specify specific port ranges to allow connections.

For example, you are running some java applications listening from port 8080 to 8085. It will be tiring to go port by port; UFW allows you to indicate a port range. You will need to indicate the protocol allowed (TCP or UDP).

sudo ufw allow 8080:8085/tcp

You can do the same for UDP protocol just by replacing TCP

Allow multiple ports

You can allow multiple ports in a single command line. You also need to specify the protocol (TCP or UDP).

For example, allow ports 80 and 443 using ufw, type:

sudo ufw allow 80,443/tcp

You can try to check your UFW rules

sudo ufw status
Output
Status: active

To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere                  
80                         ALLOW       Anywhere                  
8080:8085/tcp              ALLOW       Anywhere   
80,443/tcp                 ALLOW       Anywhere                                 
22 (v6)                    ALLOW       Anywhere (v6)             
80 (v6)                    ALLOW       Anywhere (v6)             
8080:8085/tcp (v6)         ALLOW       Anywhere (v6) 
80,443/tcp (v6)            ALLOW       Anywhere (v6)                          

You can notice that the protocol name is indicated.

Allow Specific IP addresses

When you have a server accessible over the internet, you must be careful about who is allowed to reach the server. Using UFW you can specify IP addresses that are allowed to access the server. This can be useful if you are going to give some access to some partners.

For example, to allow connections from IP address 58.105.0.200, you can specify:

sudo ufw allow from 58.105.0.200    

Allow Subnets

Instead of allowing a specific IP address, you can just allow a subnet of IP addresses. UFW allows to specific subnet mask using CIDR notation.

For example to allow network 192.168.10.0 with netmask 24, type:

sudo ufw allow from 192.168.10.0/24    

Allow from specific IP Address to Port

UFW allows to specific IP address to connect to a port by using from IP address to any port option.

For example to allow IP address 58.105.0.200 to connect to port 22, type:

sudo ufw allow from 58.105.0.25 to any port 22

You can also filter to allow specific protocols using the proto option:

sudo ufw allow from 58.105.0.0/24 to any port 22 proto tcp

To set your server to listen to specific IP on a port:

ufw allow from any to 10.8.0.1 port 22

You may further filter to restrict from only a specific source to connect specific IP on a port:

sudo ufw allow proto tcp from 10.20.80.55 to 10.20.80.56 port 22

Allow traffic to a specific interface

Using UFW you can define firewall rules to be applied on a specific interface.

First, you may use the following ip command to check your interface details:

ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default ...
...
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group 
....
....
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group 
....
....
4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default 

The following command creates a UFW firewall rule to set on the network interface named eth1 to allow MYSQL traffic ie port 3306:

sudo ufw allow in on eth1 to any port 3306

Step 7: Add rule with comment

To add a comment to the ufw rule use the following syntax:

ufw rule comment 'add your comment here'

For example to add a comment for ufw allow rule, type:

sudo ufw allow 'Nginx HTTPS' comment 'For website allowed Nginx on port 443'

Step 8: Block Connections

As mentioned before default policy of UFW is to deny all incoming connections. If you have changed the default policy and need to deny specific services you can use ufw deny option. When we use deny UFW will ignore that traffic. Instead, if you want ufw to send a return denied message use the reject option.

The syntax is the same as allow rules, only needs to replace with deny option.

To deny connections to port 21, type:

sudo ufw deny 21

You can block all connections coming from an IP address 10.30.55.10 on port number 22.

sudo ufw deny from 10.30.55.10 to any port 22

Step 9: Create rules with application profile name

When you install some packages like Nginx or Apache, it will create an application profile with a service name linked to the corresponding port (80, 22, 443, etc). To list available application lists use ufw app list command.

You can simply apply the rule using the application profile name. For example, Nginx Full corresponds to ports 80 and 443, and OpenSSH to port 22.

For example to allow ports 80 and 443 using the Nginx profile, type

sudo ufw allow 'Nginx Full'

Step 10: Delete a rule

If you created a UFW rule and no longer required it, you can easily delete it using two methods.

You can delete UFW rules by rule number. To list rule numbers use the following command:

sudo ufw status numbered
Output
Status: active
  To                         Action      From  --                         ------      ----
 [ 1] OpenSSH                    ALLOW IN    Anywhere                  
 [ 2] 80                         ALLOW IN    Anywhere                  
 [ 3] 8080:8085/tcp              ALLOW IN    Anywhere                  
 [ 4] 80,443/tcp                 ALLOW IN    Anywhere                  
 [ 5] Anywhere                   ALLOW IN    X.Y.Z.T             
 [ 6] Anywhere                   ALLOW IN    X.Y.Z.0/24           
 [ 7] Anywhere                   ALLOW IN    X.Y.Z.T/tcp         
 [ 8] 25                         DENY IN     Anywhere                  
 [ 9] 1194/tcp                   DENY IN     X.Y.Z.T/24           
 [10] Nginx Full                 ALLOW IN    Anywhere                  
 [11] OpenSSH (v6)               ALLOW IN    Anywhere (v6)             
 [12] 80 (v6)                    ALLOW IN    Anywhere (v6)             
 [13] 8080:8085/tcp (v6)         ALLOW IN    Anywhere (v6)             
 [14] 80,443/tcp (v6)            ALLOW IN    Anywhere (v6)             
 [15] Anywhere (v6)              ALLOW IN    A:B:C::          
 [16] 25 (v6)                    DENY IN     Anywhere (v6)             
 [17] Nginx Full (v6)            ALLOW IN    Anywhere (v6)

Now you can delete the ufw rule number 6 using the following command:

$ sudo ufw delete 6

Second method: use the actual rule itself for deletion. For that add the rule followed by the ufw delete.

For example, to delete the rule where we have allowed port 1199:

$ sudo ufw delete deny from 10.20.59.0/24 to any port 1194

Step 11: Activate IP Masquerading

IP masquerading works like NAT. It allows machines with non-routable IP addresses to access the Internet through a machine acting as a gateway (the one doing the masquerading).

You should enable the IP forwarding to allow that. Let's edit the /etc/ufw/sysctl.conf configuration file and uncomment a specific line

sudo vim /etc/ufw/sysctl.conf
net/ipv4/ip_forward=1

Now you should allow the DEFAULT_FORWARD_POLICY for the forward policy

sudo ufw default allow routed

This will change the value of DEFAULT_FORWARD_POLICY to ACCEPT on the default policy file. Normally after a reboot, the changes will be effective. To apply it immediately, you should run a command

sysctl -p

You need to edit the nat table and the masquerade rule and set the default policy for the POSTROUTING chain. You should add some lines to the /etc/ufw/before.rules file

sudo vim /etc/ufw/before.rules
NAT table rules
 *nat
 :POSTROUTING ACCEPT [0:0]

 Forward traffic through eth0 - Change to match your public network interface
 -A POSTROUTING -s A.B.C.0/24 -o eth0 -j MASQUERADE

 don't delete the 'COMMIT' line or these rules won't be processed
 COMMIT

Step 12: Stop UFW

To make all rules inactive, run the following command:

sudo ufw disable
Output
Firewall stopped and disabled on system startup

Disable ufw doesn't delete any rules but it will make all rules no longer active. You can activate all rules back using the ufw enable command.

For any reason, you want to delete all rules, you need to reset ufw. But this will keeps default policies as it is.

sudo ufw reset

Step 13: IPv6 on UFW

By default, IPV6 is enabled on UFW (/etc/default/ufw). When set to no, only IPv6 on the loopback is accepted.

sudo vim /etc/default/ufw

Look for the definition "IPV6=" in the file.

As you edited the UFW configuration, to make the changes effective run ufw reload command. This is not required when you add rules using the command line.

Instead of reload, you can 'disable' and then 'enable' the firewall for the changes to take effect.

UFW Commands

Some of the useful UFW commands:

UFW CommandsDescription
ufw default allow|deny|rejectTo manage ufw default policies
ufw app listTo list all application profiles
ufw enableTo start or enable ufw firewall
ufw show addedBefore enabling show added rules
ufw status verboseShow active/inactive status and list rules for running firewall
ufw allowSet allow rules
ufw rule commentAdd comment to rules
ufw denySet deny rules
ufw deleteDelete specific rules by actual rule or by rule number
ufw disableMake all rules inactive
ufw resetDelete all rules

Conclusion

In this tutorial, we learned how to set up a Firewall with UFW on Ubuntu 22.04 LTS.

What all we covered about UFW? the default policy, application profiles, allow ssh, enable, allow and deny rules and delete rules. Make sure to only allow required incoming connections and deny all unnecessary connections.

Thanks for reading, please provide your feedback and suggestions in the below comment section.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment