UFW Linux Firewall Cheatsheet
A Firewall is a network security device that monitors and filters incoming and outgoing network traffic based on an organization’s previously established security policies. At its most basic, a firewall is essentially the barrier that sits between a private internal network and the public Internet. A firewall’s main purpose is to allow non-threatening traffic in and to keep dangerous traffic out.
Install
To install UFW if you don't already have it, run:
This tutorial assumes you are using Debian or Ubuntu.
Enable UFW
UFW is disabled by default in Ubuntu and you have to enable it
1 |
sudo ufw enable |
Disable UFW
1 |
sudo ufw disable |
change ENABLED=no to ENABLED=yes
Get Status / Rules
1 |
sudo ufw status |
If you want the output to be numbered, so you know the rule IDs:
1 |
sudo ufw status numbered |
Default Deny
You probably want UFW to deny everything by default and add whitelist exceptions later.
To allow a any ip and protocol on a certain port:
1 |
ufw allow (port-number-here) |
Allow Protocol on Port
1 |
ufw allow $PORT/$PROTOCOL |
example:
1 |
ufw allow 22/tcp |
Allow IP Complete Access
1 |
ufw allow from $IP_ADDRESS |
Allow IP Range
1 |
ufw allow from $IP/$CIDR |
example:
1 |
ufw allow from 192.168.0.1/24 |
Allow IP Range On One Port
The following could be useful if you wanted to give an IP the ability to connect to the database port, but not SSH for example. It seems strange, but you need to use to any port
to allow specifying the port.
Block an IP
1 |
sudo ufw insert 1 deny from $IP_HERE |
The insert 1
is important, and ensures that the rule is injected at the front of the list of rules. Otherwise, if there was another rule that would accept the connection, e.g. “allow on port 80”, then UFW would accept the connection instead of blocking it. UFW does not have a concept of specificity, only the order of the rules.
If that doesn't work, it might be because you have no rules. In which case use:
1 |
sudo ufw deny from $IP_HERE |
Block Outgoing To IP
Today I needed to block my web browser going to an IP address in order to test something. The previous rule for blocking an IP just blocks incoming traffic, but in this case we want to block outgoing traffic.
1 |
sudo ufw deny out from any to $IP_ADDRESS |
Deleting Rules
There are many ways to delete rules in UFW, but the simplest way is to list the rules with their numbers/indexes and then delete by index with the following two commands:
1 |
sudo ufw status numbered sudo ufw delete $RULE_NUMBER |
Hi! Just wondering- what template did you use for your website? I want to use it on my blog
Thanks for thr great article!
Thank you so much!
Thank you so much!
It is very comforting to see that others are suffering from the same problem as you, wow!
It is very comforting to see that others are suffering from the same problem as you, wow!