How to Set Up a Firewall with UFW on Ubuntu 20.04

How to Set Up a Firewall with UFW on Ubuntu

UFW firewall is a pre-existed module on ubuntu that is used to monitor, filter, and secure incoming and outgoing traffic. we need to define some set of security rules to determine whether that specific network traffic should be allowed or not.

UFW is also called an Uncomplicated Firewall. it is handled by commands but it’s quite user-friendly to manage IP tables firewall rules. it’s objective to make firewall handling very easy.

This post explains how to Set Up a Firewall with UFW on Ubuntu 20.04. A proper configuration of a firewall is one of the most important parts of system security.

Read Also: How to Change Remote URL in Git?

Learn How to Set Up a Firewall with UFW on Ubuntu

You should either logged in as a root or as sudo privileged user as only they can manage the firewall. It will be best to use Sudo privileged users.

Install UFW

As UFW is a standard package of Ubuntu 20.04, there is a simple command to install it. First, run the update command If for some reason package is not listed to it will list in a repo, then you can install the package by the following command:

sudo apt update
sudo apt install ufw

Check UFW Status

UFW service is inactive by default. We need to check the status of the UFW with the following command:

sudo ufw status verbose

The output will show something like this:

Status: inactive

If you wish to start the UFW, that is not recommended yet as it might block you to access the server if you are accessing from remote location, so will suggest you to go through complete post first, if you still want to enable just run the following command:

sudo ufw enable

If the UFW service is activated, the output will look something like the below:

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)

UFW Default Policies

The default policies of the UFW Firewall just allow all the outbound traffic rest it blocks all incoming and forwarding traffic. It means that any outsider can’t connect to the server until we didn’t allow him to access our application or service. meanwhile, our server can communicate outside as outbound traffic is fully opened for us in UFW policies.

The default set of rules are located in /etc/default/ufw file, That can be changed in two ways either changing the file manually or with direct proper command line sudo ufw default <policy> <chain>.

Application Profiles

An application profile is a simple text file just in INI format, That explains the service and has firewall rules related to that service. By Default application profiles are located in /etc/ufw/applications.d directory.

To list all application profiles that are available in UFW can be seen by the following command:

sudo ufw app list

It’s Depend on the packages that are installed on your server, So the output can look something like the below:

Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

To look further into the specific profile and its rules run the below command:

sudo ufw app info 'Nginx Full'

The above command output will show you something like below that explains  ‘Nginx Full’ profile opens ports 80 and 443.

Profile: Nginx Full
Title: Web Server (Nginx, HTTP + HTTPS)
Description: Small, but very powerful and efficient web server

Ports:
  80,443/tcp

You can also create your profiles for any application.

Enabling UFW

If you’re accessing your Ubuntu server remotely, before activating the UFW firewall, you have to allow incoming SSH connections. Otherwise, you will be blocked to connect to the server.

To configure UFW to allow incoming traffic for SSH connections, Use the below command:

sudo ufw allow ssh
Rules updated
Rules updated (v6)

If you have changed the default SSH port to a non-standard port, you need to specifically open that port.

As an example, if ssh daemon listens on port 5532, Issue the following command to allow the port:

sudo ufw allow 5532/tcp

We have configured the UFW firewall to allow incoming SSH connections, Now you can enable the firewall by the below command:

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

You will get a warning that enabling the firewall may cause disruption on any existing ssh connections, so just type y and hit Enter as we already configured it to allow the ssh port properly.

Opening Ports

In many cases, you need to allow some other ports depending on the application/services you have configured. To open that service port issue the following command:

ufw allow port_number/protocol

You can find a few ways to allow HTTP connections.

Option one is to directly use the service name. UFW verify that from /etc/services file to gather the information of port and protocol for that specified service, use the below command to use this option:

sudo ufw allow http

You can also modify this by specifying the port number and protocol and using the command as below:

sudo ufw allow 80/tcp

When you don’t specify any protocol in the above command, UFW automatically creates a rule for both protocols tcp and udp.

Another option is using the application profile. As an example, ‘Nginx HTTP’:

sudo ufw allow 'Nginx HTTP'

Port Ranges

In any case, it requires you to open the complete port range, So UFW permits you to open the required port range. To allow that you need to separate starting and end ports using colon (:) and just specify the protocol as well to tell if it’s tcp or udp

As an example, you want to allow some ports from like 35000 to 36000 with both protocols tcp and udp, so you need to run the below command.

sudo ufw allow 35000:36000/tcp
sudo ufw allow 35000:36000/udp

Specific IP Address and port

If you want to allow one specific remote IP to access all the ports, we need to use from keyword with the ip address. In another term you want to whitelist the ip just use the following command:

sudo ufw allow from 64.63.62.61

In another case, if you want to whitelist remote IP for a specific port number then use the to any port keyword with the port number.

As an example, you want to permit this ip 123.456.78.9 on port 80, run following command:

sudo ufw allow from 123.456.78.9 to any port 80

Subnets

If you want to allow an entire specific network IP pool or subnet then we can use the same syntax to allow the connection just you need to add CIDR or netmask with the IP.

Here is an example, showing that how to allow IP addresses to range in UFW from 192.168.1.1 to 192.168.1.254 to port 3306 (MySQL ):

sudo ufw allow from 192.168.1.0/24 to any port 3306

Specific Network Interface

If you want to allow connections on a specific network interface you can use the in on keyword with the name of the network interface, see the command below to understand it better:

sudo ufw allow in on eth2 to any port 3306

Denying connections

By default, UFW set the policy of denying all the incoming connections or traffic. Writing the deny rules is very much the same as writing allow rules; you just need to replace the allow keyword with deny.

By taking an example, we already have 80 and 443 opened on the server, and you find out that the server is under attack from the range 15.23.23.0/24 network. So we need to deny all traffic from 15.23.23.0/24, So to do deny all the incoming traffic just run the below command:

sudo ufw deny from 15.23.23.0/24

If you just want to deny only on ports 80 and 443, Use the below command:

sudo ufw deny proto tcp from 23.24.25.0/24 to any port 80,443

Deleting UFW Rules

UFW allows users to delete the rule in two ways.

  1. By rule number
  2. By specifying the actual rule.

Using option one removing rule is easier, To remove by rule number you need to check for several rules that you want to remove. To get a complete list of rules with numbers, use this below command:

sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 80/tcp                     ALLOW IN    Anywhere
[ 3] 8080/tcp                   ALLOW IN    Anywhere

So now you want to delete the rule allowing port 8080 and you can see the number of this rule is 3, now just delete this by following command:

sudo ufw delete 3

Option Two is to remove the rule by specifying the actual rule. As an example, if we have added a rule that opens port 8888 we need to delete by the following command:

sudo ufw delete allow 8888

Disabling UFW

You want to disable the firewall for any reason either for short time or a long time It’s Very easy to do that, just run the below command:

sudo ufw disable

If you have tested it out or you wish to enable it again, Just run the below command:

sudo ufw enable

Resetting UFW

Resetting UFW allows you to clear all the rules those are applied and then disable UFW, It will be like it’s just a newly installed package. So just to reset, run the below command:

sudo ufw reset

IP Masquerading

IP Masquerading is a form of NAT (Network Address Translation) in the Linux kernel that rewrite the source and destination IP addresses and ports to translate the network traffic.  you can permit one or more than one machines to communicate in a private network with the Internet using any of one machine that will act as a gateway.

Configuring IP Masquerading has several steps.

Firstly, we need to enable IP forwarding. We can do that, by updating the file /etc/ufw/sysctl.conf so to do that run:

sudo vi /etc/ufw/sysctl.conf

Look for the line that reads net/ipv4/ip_forward = 1 and uncomment the line, the line doesn’t exist add:

net/ipv4/ip_forward=1

Next, we need to update the UFW configuration to permit forwarded packets. To do that open the UFW firewall configuration file:

sudo vi /etc/default/ufw

Find the DEFAULT_FORWARD_POLICY key, and update the value from DROP to ACCEPT:

DEFAULT_FORWARD_POLICY="ACCEPT"

Now we need to configure a default policy in nat table for POSTROUTING chain and the masquerade rule. To do that, open the file /etc/ufw/before.rules by below command :

sudo nano /etc/ufw/before.rules

And add/update the following lines:

#NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]

# Forward traffic through eth0 - Change to public network interface
-A POSTROUTING -s 10.8.0.0/16 -o eth0 -j MASQUERADE

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

Change the eth0 in -A POSTROUTING the line to your server’s public network interface:

When changes are done, save and close the file.

At last, reload the UFW firewall rules by disabling and re-enabling using the below commands:

sudo ufw disable
sudo ufw enable

Conclusion

We have seen how to Set Up a Firewall with UFW on Ubuntu 20.04 server. You are aware of how to allow and deny the traffic so just now audit your services and improve the security by just allowing required services only.

Feel free to comment for any further information.