A firewall named UFW (Uncomplicated Firewall) come with Ubuntu Server. But it’s disable as default, so we need to enable it and do some configuration.
Introduction
Validated on
This how-to have been tested and known to work, but not limited to the following versions
- Ubuntu 22.04
- Ubuntu 24.04
Prerequisite
- Sudo or root access to your Ubuntu Server
- SSH access to your Ubuntu Server
- SSH software
- macOS, you can use Terminal
- Linux, you can use Terminal
- Windows, I do recommend you to use PuTTY
Recommendation
- If you haven’t secured SSH on your Ubuntu Server I do recommend you to read my guide about it
Enable or Disable
To enable UFW you simply write the following but remember that you should open the ports you need before enabling UFW. For example, SSH (standard port 22/tcp)
sudo ufw enable
If you want to disable UFW you just replace enable with disable
sudo ufw disable
Allow or Deny
To allow a port, you specify the port number and then the protocol. You can also allow a range of ports by adding start port number : end port number
sudo ufw allow 443/tcp
sudo ufw allow 80:85/tcp
If you want to enable both UDP and TCP, you just write the port number
sudo ufw allow 53
To deny a port you will write deny instead of allow, and you can also deny a range of ports
sudo ufw deny 443/tcp
sudo ufw deny 442:443/tcp
You can also restrict a rule to an IP number or subnet, in the example below only connections from 192.168.0.4 and subnet 192.168.1.0/24 are allowed on port 22
sudo ufw allow from 192.168.0.4 to any port 22 sudo ufw allow from 192.168.1.0/24 to any port 22
Status
You can see UFW’s status and what rules you’re using by the following command
sudo ufw status
You can also add numbered at the end of the above command, that make it easier to delete firewall rules
sudo ufw status numbered
Delete rule
You can simply delete a rule by the following command, add condition, port number and protocol
sudo ufw delete deny 80/tcp
If you have many rules, it can be a little tricky so then you can delete the rule by entering the rule number that you did see in Status
sudo ufw delete number 1
Recommendation
I do recommend that you deny all incoming traffic and allow all outgoing traffic. And then just open the incoming ports that you need.
sudo ufw default deny incoming sudo ufw default allow outgoing
Conclusion
We have seen how to enable and use UFW on Ubuntu Server and I strongly recommend you use it to make your server more secure