Programster's Blog

Tutorials focusing on Linux, programming, and open-source

UFW Cheatsheet

Related Posts

Cheatsheet

Install

To install UFW if you don't already have it, run:

sudo apt update && sudo apt install ufw -y

This tutorial assumes you are using Debian or Ubuntu.

Enable UFW

UFW is disabled by default in Ubuntu and you have to enable it:

sudo ufw enable

Disable UFW

sudo ufw disable

You probably don't want to just enable it for one session, but to start up at boot. To do this, edit the configuration file:

sudo editor /etc/ufw/ufw.conf

... and change

ENABLED=no

to

ENABLED=yes

Get Status / Rules

sudo ufw status

If you want the output to be numbered, so you know the rule IDs:

sudo ufw status numbered

Default Deny

You probably want UFW to deny everything by default and add whitelist exceptions later.

ufw default deny

Open/Unblock Port

To allow a any ip and protocol on a certain port:

ufw allow (port-number-here)

Allow Protocol on Port

ufw allow $PORT/$PROTOCOL

E.g.

ufw allow 22/tcp

Allow IP Complete Access

ufw allow from $IP_ADDRESS

Allow IP Range

ufw allow from $IP/$CIDR

e.g.

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.

sudo ufw allow from 95.216.255.56/32 to any port 3306

Block an IP

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:

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.

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:

sudo ufw status numbered
sudo ufw delete $RULE_NUMBER

Please Note

I believe rules from iptables can mix with UFW. For example, I have set up some routing rules in iptables for OpenVPN before then configuring ufw to default block and allow ports 22 and 1194 and I can still browse the internet etc so packet forwarding is still working.

References

Last updated: 3rd August 2021
First published: 3rd August 2021