You ask — we answer!

How to use Ubuntu firewall

How to use Ubuntu firewall main illustration

What is UFW

Most system administrators don’t like to configure network security applications, such as firewalls, remotely. These applications by default block access from the outside for all applications, except for those that are clearly indicated as allowed.

If an error occurs, you may lose remote control to the network. We created this guide specifically so that you can once again see the correct procedure for setting up a standard UFW firewall on the Ubuntu Linux operating system.

If you dig deeper, UFW isn’t actually a firewall. This is just a convenient utility with which you can configure the netfilter built into the Linux kernel since 2.4. There is no way to configure netfilter directly, so the iptables utility was written for this purpose.

Well, UFW made it possible to further simplify this process, making it possible to quickly manage rules without the need to write configuration files or carefully read the iptables manual. This is what is actually encoded in the acronym UFW: Uncomplicated Firewall.

Why UFW disabled by default

Once the Ubuntu operating system is installed on a server, by default it doesn’t have a single open port that should be protected by a firewall. Therefore even if UFW is installed, it remains in an inactive state until the user needs to configure protection. The thing to remember is that before you enable the firewall, you need to make sure that by doing so you’ll not deprive yourself of the way to configure the server.

For example, if you manage the server using an SSH connection, then before activating the firewall, you must explicitly indicate that OpenSSH daemon is allowed to use port 22 (or another, if configured) and should accept connections from the outside, and not discard them, as is implemented for all external connections by default. To do this, you need to use either a ready-made OpenSSH application profile or create your own rule.

UFW status

First, let’s make sure that UFW is in the operating system. To do this, run the command:

sudo ufw status verbose

If you receive the following response, it means that UFW is installed on the operating system, but as mentioned above, it is in an inactive state:

Status: inactive

Otherwise, update the package cache and install UFW using the standard packer manager:

sudo apt update && sudo apt -y install ufw

Enable firewall

Attention! Before executing the following command, ensure that you have the ability to control the server by enabling an application profile (OpenSSH for example) or activating a custom rule.

sudo ufw enable

Let’s check the state of UFW by calling the following command again:

sudo ufw status verbose

Disable firewall

The firewall can be turned off with the “disable” command. Please note that this action doesn’t affect previously created rules in any way. They will all continue to work as soon as the firewall is turned back on:

sudo ufw disable

Enable logging

The second most important firewall function is logging. With its help, you can both check that the UFW works correctly and identify signs of cyberattacks. To enable the logging feature, run the following command:

sudo ufw logging on
Logging enabled
tail -f /var/log/ufw.log
…
Jul 10 05:54:24 ubuntu22044 kernel: [56235.006445] [UFW BLOCK] IN=enp134s0f1 OUT= M
AC=ac:1f:6b:f5:60:43:02:01:01:01:01:02:08:00 SRC=152.32.129.154 DST=37.230.134.118
LEN=60 TOS=0x00 PREC=0x00 TTL=41 ID=5377 DF PROTO=TCP
SPT=47633 DPT=6606 WINDOW=29200 RES=0x00 SYN URGP=0
…

Also you can check syslog and kern.log:

grep -i ufw /var/log/syslog
grep -i ufw /var/log/kern.log

In both cases the result will be the same. To increase the amount of information recorded in the log, change its level. Available levels: low (by default) / medium / high / full:

sudo ufw logging full

Disable logging

To disable logging, the off level is provided:

sudo ufw logging off

Rules management

Access from specific IPs

When creating rules, two scenarios are most common. In the first, the system administrator requires that only those users who have a specific IP address or an IP address from a certain range can connect to the server. Connection attempts from any other addresses should be blocked. This is most applicable for non-public or corporate services:

sudo ufw allow from [ip_address]
sudo ufw allow from [ip_address/subnet_mask]

Deny from specific IPs

The second scenario will be relevant for public services whose servers are forced to accept and process all incoming connections. This makes them vulnerable to brute force attacks and denial of service (DoS) attacks. In this case, rules that prohibit connecting from a specific IP address or an IP address from a certain range will help:

sudo ufw deny from [ip_address]
sudo ufw deny from [ip_address/subnet_mask]

If your server is not used for sending emails, then it would be logical to block any outgoing SMTP traffic to prevent potential spam. You can do this with the following command:

sudo ufw deny out 25

Delete existing rules

The most convenient way to delete rules is by their serial number. To find out which number matches which firewall rule, run this command:

sudo ufw status numbered
Status: active                                                                                                                                                                                                                            
  To                         Action      From                                                                                                                                                                                          
  --                         ------      ----                                                                                                                                                                                          
[ 1] OpenSSH                    ALLOW IN    Anywhere                                                                                                                                                                                      
[ 2] OpenSSH (v6)               ALLOW IN    Anywhere (v6)

Now you can delete a rule by substituting its number in the command:

sudo ufw delete [rule_number]

Application profiles

Application profiles are ready-made sets of rules that simplify the life of a system administrator. They immediately take into account standard connection ports and allow to apply several rules with one command.

List available profiles

To check which profiles are available for activation, run the command:

sudo ufw app list
Available applications:                                                                                                                                                                                                                   
  OpenSSH

Enable application profile

By default, Ubuntu will always have an OpenSSH profile available, allowing SSH traffic to pass through standard port 22. To ensure that after enabling UFW you don’t lose control via SSH, run the following command:

sudo ufw allow OpenSSH

Now you can enable UFW and verify that the enabled rule for OpenSSH works:

sudo ufw status verbose
Status: active                                                                                                                                                                                                                            
Logging: on (low)                                                                                                                                                                                                                         
Default: deny (incoming), allow (outgoing), disabled (routed)                                                                                                                                                                             
New profiles: skip                                                                                                                                                                                                                        
To                         Action      From                                                                                                                                                                                               
--                         ------      ----                                                                                                                                                                                               
22/tcp (OpenSSH)           ALLOW IN    Anywhere                                                                                                                                                                                           
22/tcp (OpenSSH (v6))      ALLOW IN    Anywhere (v6)

Disable application profile

You can delete an activated rule using the “delete” command. Be extremely careful with this command and don’t disable OpenSSH profile, because if the firewall is enabled and there is no rule allowing OpenSSH, you will lose remote access to the server:

sudo ufw delete allow [app_profile_name]

IP blocklist

It’s no secret that the internet is filled with devices programmed to automatically scan and attempt to gain unauthorized access. It would be wise to block all addresses seen engaging in such activity. The IPsum project maintains a registry of malicious IP addresses based on data from 30 publicly available services that regularly publish lists of such addresses. This registry will be an excellent source of data for UFW.

Start with installing the ipset package:

sudo apt -y install ipset

Now you need to make a backup copy of the existing after.init configuration file:

sudo cp /etc/ufw/after.init /etc/ufw/after.init.orig

Clone the repository with pre-prepared configuration files:

git clone https://github.com/poddmo/ufw-blocklist.git

Change a working directory:

cd ufw-blocklist

Copy and replace the configuration file:

sudo cp after.init /etc/ufw/after.init

Copy the cron job file:

sudo cp ufw-blocklist-ipsum /etc/cron.daily/ufw-blocklist-ipsum

Change the owner of these two files to the superuser root:

sudo chown root:root /etc/ufw/after.init /etc/cron.daily/ufw-blocklist-ipsum

Set permissions to 750 (rwxr-x—) for both files as well:

sudo chmod 750 /etc/ufw/after.init /etc/cron.daily/ufw-blocklist-ipsum

Download a basic blocklist:

curl -sS -f --compressed -o ipsum.4.txt 'https://raw.githubusercontent.com/stamparm/ipsum/master/levels/4.txt'

Set permissions to 640 (rw-r-----) to the basic blocklist. It will be stored directly in the /etc directory, so changing the permissions is a reasonable precaution against tampering with this list:

sudo chmod 640 ipsum.4.txt

It’s time to place the list in the /etc directory:

sudo cp ipsum.4.txt /etc/ipsum.4.txt

Let’s start the initial script:

sudo /etc/ufw/after.init start

The following command will help display the current number of entries in the block list:

sudo ipset list ufw-blocklist-ipsum -terse | grep 'Number of entries'

Finally, make sure that the list is accepted and the UFW is working correctly:

sudo /etc/ufw/after.init status
Name: ufw-blocklist-ipsum                                                                                       
Type: hash:net                                                                                                  
Revision: 7                                                                                                     
Header: family inet hashsize 2048 maxelem 65536 bucketsize 12 initval 0x5822a4bb                                
Size in memory: 186912                                                                                          
References: 3                                                                                                   
Number of entries: 6744                                                                                         
      0        0 ufw-blocklist-input  all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-
set ufw-blocklist-ipsum src                                                                                       
      0        0 ufw-blocklist-forward  all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-
set ufw-blocklist-ipsum dst                                                                                     
      0        0 ufw-blocklist-output  all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-
set ufw-blocklist-ipsum dst

See also:



Updated: 28.03.2025

Published: 12.07.2024


Still have questions? Write to us!

By clicking «I Accept» you confirm that you have read and accepted the website Terms and Conditions, Privacy Policy, and Moneyback Policy.